所以我试图在java中创建一个简单的计算器,但不知道如何获取输入操作.该程序要求两个数字,然后要求运算符.当我运行它直到我进入操作类型时,一切正常.编译器只是跳过它,甚至不让我输入任何内容.有线索吗?
Scanner keyboard = new Scanner(System.in);
double x;
double y;
double sum =0;
double minus =0;
double times =0;
double divide =0;
double nCr =0;
String Op;
System.out.print("X: ");
x = keyboard.nextDouble();
System.out.print("Y: ");
y = keyboard.nextDouble();
System.out.print("Op: ");
Op = keyboard.nextLine();
解决方法:
尝试:
System.out.print("X: ");
x = Double.parseDouble(keyboard.nextLine());
System.out.print("Y: ");
y = Double.parseDouble(keyboard.nextLine());
System.out.print("Op: ");
op = keyboard.nextLine();
这将解析您输入的数字为Double并读取回车符.
如果您想要错误控制(如果用户输入字符串而不是数字):
Boolean check = true;
do
{
try
{
//The code to read numbers
}
catch(InputMismatchException e)
{
System.err.println("Please enter a number!");
check = false;
}
}
while(check == false)