所以我是一个noob编码器(网站的新手),试图自学,我现在正在制作一个简单的计算器。 Atm,我用if语句添加了pi来检查输入。但是,当我输入一个双倍的时候,它什么也做不了,我不知道为什么。
package testing;
import java.util.Scanner;
public class Calculator {
@SuppressWarnings("resource")
public static void main(String[] args) {
String piCheck = "pi";
Double n1 = null;
Scanner reader = new Scanner(System.in);
System.out.println("Welcome to Calculator!");
System.out.println(" ");
System.out.println("Enter a number, ");
System.out.println("or enter 'pi' to insert PI,");
if (reader.nextLine().toLowerCase().contains(piCheck)) {
n1 = Math.PI;
} else {
n1 = reader.nextDouble();
}
Scanner reader2 = new Scanner(System.in);
System.out.println("Would you like to multiply, divide, add, subtract?");
String uOperation = reader2.nextLine();
int operation = 1;
switch (uOperation.toLowerCase()) {
case "multiply":
operation = 1;
break;
case "multiplication":
operation = 1;
break;
case "times":
operation = 1;
break;
case "divide":
operation = 2;
break;
case "division":
operation = 2;
break;
case "add":
operation = 3;
break;
case "addition":
operation = 3;
break;
case "subtract":
operation = 4;
break;
case "subtraction":
operation = 4;
break;
default:
System.out.println("Invalid operation! Rerun Calculator!");
break;
}
if (operation == 1) {
System.out.println("What do you want to multiply " + n1 + " by?");
} else if (operation == 2) {
System.out.println("What do you want to divide " + n1 + " by?");
} else if (operation == 3) {
System.out.println("What do you want to add to " + n1 + "?");
} else if (operation == 4) {
System.out.println("What do you want to subtract from " + n1 + "?");
} else {
System.out.println("Something went wrong!");
}
double n2 = reader.nextDouble();
System.out.println("Here's your result!");
double resultM = n1*n2;
double resultD = n1/n2;
double resultA = n1+n2;
double resultS = n1-n2;
if (operation == 1) {
System.out.println(n1 + " multiplied by " + n2 + " equals:");
System.out.println(resultM);
} else if (operation == 2) {
System.out.println(n1 + " divided by " + n2 + " equals:");
System.out.println(resultD);
} else if (operation == 3) {
System.out.println(n1 + " plus " + n2 + " equals:");
System.out.println(resultA);
} else if (operation == 4) {
System.out.println(n1 + " take away " + n2 + " equals:");
System.out.println(resultS);
} else {
System.out.println("Something went wrong!");
}
}
}
答案 0 :(得分:4)
您的问题是您正在读取条件中的输入,因此如果输入double,则else子句需要输入更多输入,因为reader.nextLine()
已经消耗了第一个输入。
您必须保存输入并重复使用它:
String input = reader.nextLine();
if (input.toLowerCase().contains(piCheck)) {
n1 = Math.PI;
} else {
n1 = Double.parseDouble(input);
}