java - 如何使字符串等于扫描仪和“if”语句?
问题描述
让用户在控制台中输入字符串并且他们输入的特定字符串等于 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));
解决方案
您的代码大部分是正确的:
您有一些拼写错误会阻止您的代码成功编译。您应该考虑使用 IDE,例如 Eclipse,因为它会在您键入时为您突出显示这些类型的问题。
您不应该创建第二个 Scanner 对象,重用现有的
完成后请务必关闭扫描仪
这是您更正的代码:
public static void main(String[] args)
{
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"))
{
// You shouldn't create a new Scanner
// Scanner numInput = new Scanner(System.in);
System.out.println("Enter a number - ");
double sR;
// Reuse the userInput Scanner
sR = userInput.nextDouble();
System.out.println("The square root of " + sR + " is " + Math.sqrt(sR));
}
// Be sure to close your Scanner when done
userInput.close();
}
推荐阅读
- spring-boot - 有没有办法在春季启动测试中从 src/test/resources/application.properties 加载属性?
- python - 我在python的链表中遇到问题
- java - 在 Firebase 中搜索时如何执行 OR 查询?
- javascript - Javascript/html 文件无法在浏览器中正确打开???浏览器只是无限加载(在 safari 和 chrome 上尝试过)
- python - 在将数据添加到包含列表作为其值的字典中时,我以前的所有键都会更新为列表的最新值
- javascript - 从 firebase 读取如何工作?
- python - Pandas:ValueError:数组的长度必须相同 - 当 orient=index 不起作用时
- java - PKIX 路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:代理后面
- python - 字典列表在 Python 中引发了一个关键错误
- javascript - 从数组映射中过滤多个项目 React JS