【发布时间】:2018-09-20 02:34:30
【问题描述】:
让用户在控制台中输入字符串并且他们键入的特定字符串等于 if 语句时,我遇到了很多麻烦。我想在控制台中输入“SquareRoot”,然后它会转到 if 语句,但是当我输入它时,什么也没有发生。我能做些什么来解决这个问题?如何使用户输入等于字符串和 if 语句?我的“if”语句有问题吗?
Scanner userInput = new Scanner(System.in);
String SquareRoot;
System.out.println("Type 'SquareRoot' - find the square root of (x)")
SquareRoot = userInput.next();
if(SquareRoot.equals("SquareRoot")) {
Scanner numInput = new Scanner(System.in);
System.out.println("Enter a number - ");
double sR;
sR = numInput.nextDouble();
System.out.println("The square root of " + sr + "is " + Math.sqrt(sR));
【问题讨论】:
-
squareRoot = userInput.nextLine();(SquareRoot看起来像一个类名)。 -
Scanner userInput = new Scanner- 看起来不正确,可能只是错字? -
是的,很抱歉这是一个错字。我修好了:)
-
另外,你不需要实例化一个新的
Scanner对象,只需重复使用userInput -
显示的代码后面是什么?它应该类似于
} else { System.out.println("Invalid input: " + SquareRoot ); },因此用户可以看到程序检测到他们输入的内容。