[英]Why can i input anything for my operation?
So I'm trying to make a simple calculator in java but have no clue how to get an input for which operation. 所以我试图在java中创建一个简单的计算器,但不知道如何获取输入操作。 The program asks for two numbers, then asks for an operator. 该程序要求两个数字,然后要求操作员。 Everything works fine when i run it until i get to the operation type. 当我运行它直到我进入操作类型时,一切正常。 The compiler just skips right over it and doesn't even let me type anything in for it. 编译器只是跳过它,甚至不让我输入任何内容。 Any clues? 有线索吗?
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();
Try: 尝试:
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();
This will parse the number you enter to Double
and read the Carriage return. 这将解析您输入的数字为Double
并读取回车符。
If you want error control (If the user inputs a string instead of a number): 如果您想要错误控制(如果用户输入字符串而不是数字):
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)
Instead of 代替
Op = keyboard.nextLine();
Try using 尝试使用
Op = keyboard.next();
Looks like the nextLine(); 看起来像nextLine(); method gives you a problem when invoked with methods like nextInt(), nextDouble(). 使用nextInt(),nextDouble()等方法调用时,方法会出现问题。
Observation: If the nextLine() is invoked alone, this doesn't happen. 观察:如果单独调用nextLine(),则不会发生这种情况。
Basically the nextDouble
doesn't recognize the carriage return. 基本上nextDouble
不识别回车。 Use the nextLine
after each nextDouble
. 在每个nextDouble
之后使用nextLine
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.