gpt4 book ai didi

java - 扫描仪在空格字符后不读取

转载 作者:行者123 更新时间:2023-12-01 17:49:47 26 4
gpt4 key购买 nike

我有 2 个来自用户的输入。一种是说问候,另一种是告诉我你的名字

但是当我在“hello”之后写下内容时,例如:Hello mate!! 扫描仪不会读取第二个输入,即 mate 并接受 hello 从第一个字符串开始,第二个字符串也相同

任何建议

谢谢

public static void main(String[] args) {
System.out.println("Choose what would you like to say ?");

String str1 = "";
String str2 = "";

System.out.println("Say any greetings word");
str1 = input();
System.out.println("Tell me your name");
str2 = input();

if (str2.equalsIgnoreCase("zia")) {
System.out.println("Hello Mr Zia, What a nice suprise");

}

else {
System.out.println(str1 + " " + str2);
}

}

public static String input() {
Scanner sc = new Scanner(System.in);
return sc.next();
}

最佳答案

首先,您需要 sc.nextLine() 来读取整个输入。

其次,您不应该每次都创建新的扫描仪。只需像这样重复使用扫描仪即可:

Scanner sc = new Scanner(System.in);
System.out.println("Say any greetings word");
str1 = sc.nextLine();
System.out.println("Tell me your name");
str2 = sc.nextLine();

如果不再需要扫描仪,请关闭它:

sc.close();

这样您甚至不再需要 input() 方法。

关于java - 扫描仪在空格字符后不读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51669112/

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