gpt4 book ai didi

java - 带有 .hasNext 条件的 While 循环无限运行

转载 作者:行者123 更新时间:2023-12-01 07:03:03 24 4
gpt4 key购买 nike

我知道这个问题在 StackOverflow 上已经被问过很多次了,但我尝试了很多不同的解决方案,但没有一个有效。所以我决定向社区询问该怎么做。这是我的代码中的相关片段。

public class Calculator
{
public static void main(String[]args)
{
ArrayList<String> inputStorage = new ArrayList<String>();
Scanner input = new Scanner(System.in);
String rawInput;
boolean mainLoop = true;

String exitInput;
String mainMenuInput;

while(mainLoop == true)
{
mainMenuInput = input.nextLine()
switch(mainMenuInput)
{
case "Expression":
System.out.println("Type an expression");
while(input.hasNext)
{
rawInput = input.next();
inputStorage.add(rawInput);
}
break;

case "Equation":
System.out.println("Type an equation");
while(input.hasNext)
{
rawInput = input.next();
inputStorage.add(rawInput);
}
break;
case "exit":
System.out.println("Are you sure you want to exit")
exitInput = input.nextLine();
switch(exitInput)
{
case "yes":
case "Yes":
mainLoop = false;

case "no":
case "No":
break;

default:
System.out.println("That was not an option")
break;
}
default:
System.out.println("That was not an option");
break;

}
}

请注意,这只是我的代码的一部分,它从控制台接收输入,不包含任何其他内容。我还有其他设置需要代码采用这种格式。

以下是我尝试过但未成功的方法的列表:

  • 将 input.hasNext() 替换为 input.hasNextLine()
  • 将 input.hasNext() 替换为 input.next() != null
  • 如果 input.next = null 则设置退出条件
  • 如果 input.next() = "\n"则设置退出条件
  • 如果 input.next() = "\r"则设置退出条件

以下列出了对我的其余代码不起作用的内容:

  • BufferedReader(及其所有方法和方面)
  • 将 input.next() 替换为 input.nextLine()

话虽如此,我已经找到了一种方法,即根据字符 newLine 的 ASKII 值制定退出条件。唯一的问题是我没有找到将字符的 ASKII 值实现到 java 代码中的好方法(或者至少没有一个可以与我的代码一起使用),并且为了实现它,我需要知道 Scanner 类如何使用下一行字符。但这只是一个建议的解决方案,我确信有人有更好的方法来在按下 Enter 时结束这样的输入循环。

感谢您的宝贵时间。

最佳答案

最后你永远不会将 mainLoop 设置为 false。您实际上也不需要嵌套的 while 循环,只需要包含 hasNext

的循环

关于java - 带有 .hasNext 条件的 While 循环无限运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36094804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com