gpt4 book ai didi

Java:使用scanner.nextLine().equals ("example"))需要重复输入

转载 作者:行者123 更新时间:2023-12-01 11:45:19 25 4
gpt4 key购买 nike

我正在使用扫描仪来检测用户的输入,其想法是用户可以随时在终端中键入“help”或“test”以显示输出。

到目前为止,我的代码可以正常工作,因为我在键入时必须按两次 Enter 才能看到输出。这是我到目前为止所拥有的:

import java.util.Scanner;

public class Game
{
static Scanner command = new Scanner(System.in);

public static void main(String[] args)
{
GAME:
while (var.running == true)
{
check.controls();
command.nextLine();
}
}
}

public class check extends Game
{
public static void controls()
{
if (command.next().equals("help"))
{
System.out.println("This is the help Menu");
}

else if (command.next().equals("test"))
{
System.out.println("fail");
}
}
}

我的问题是,当输入“help”然后立即输入“test”时,注释将首次注册。

最佳答案

问题在于,在 check 类中,您要扫描两次以查看输入的数据是否等于 test。假设您输入了 test,第一个条件将读取 test 并使用字符串 help 对其进行评估,因此条件为 false,然后它将对第二个条件执行相同的操作,它再次要求另一个输入,如果您这次输入 test,它将使用 test 对其进行评估,并且条件为 true。

修复方法如下:

class check extends Game
{
public static void controls()
{
String commands = command.next();
if (commands.equals("help"))
{
System.out.println("This is the help Menu");
}

else if (commands.equals("test"))
{
System.out.println("fail");
}
}
}

所以基本上,您不需要扫描 next() 两次,只需扫描一次并使用 if else if 语句对其进行评估

关于Java:使用scanner.nextLine().equals ("example"))需要重复输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29187326/

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