我正在尝试教我的朋友Java。我试过这个简单的计算器。
ip_col_1+".".ip_col_2+"."+ip_col_3+"."+ip_col_4
如果你做平方根,它打印输入另一个数字,然后抛出异常...我知道发生了什么,但为什么以及如何防止它?
只是旁注,有人可以向我解释public static void main(String[] args) {
boolean powerOn = true;
while(powerOn) {
@SuppressWarnings("resource")
Scanner userInput = new Scanner(System.in);
System.out.println("Welcome to the calculator\nPlease enter a number (Enter 3.14 for PI)");
double firstNumber = userInput.nextDouble();
if(firstNumber == 3.14) firstNumber = Math.PI;
System.out.println("Please enter an operation(+,-,*,/, Square Root)");
String operation = userInput.next();
if(operation.equalsIgnoreCase("Square Root")) System.out.println(Math.sqrt(firstNumber));
else {
System.out.println("Please enter another number");
double secondNumber = userInput.nextDouble();
if(secondNumber == 3.14) secondNumber = Math.PI;
if (operation.equals("+")) {
if(firstNumber == 9 && secondNumber == 10) System.out.println("21");
else System.out.println(firstNumber+secondNumber);
}
else if (operation.equals("-")) System.out.println(firstNumber-secondNumber);
else if (operation.equals("*")) System.out.println(firstNumber*secondNumber);
else if (operation.equals("/")) System.out.println(firstNumber/secondNumber);
}
System.out.println("Power off?");
String off = userInput.next();
if(off.contains("y")) System.exit(1);
}
}
和Scanner#next()
之间的区别吗?