gpt4 book ai didi

java - nextLine 方法给了我一个不正确的实现

转载 作者:太空宇宙 更新时间:2023-11-04 10:05:33 25 4
gpt4 key购买 nike

为什么nextLine()方法不起作用?我的意思是,在第二次扫描调用后我无法输入任何句子,因为程序运行到最后并退出。

输入:era时代食品食品正确正确sss sss退出

我应该使用另一个 Scanner 对象吗?

import java.util.*;

public class Today{

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

String str="";
String exit="exit";

System.out.println("Please enter some words : ");
while(true){

str=scan.next();
if(str.equalsIgnoreCase(exit)) break;
System.out.println(str);

}

System.out.println("Please enter a sentnce : ");
String sentence1 = scan.nextLine();

System.out.println("the word you entered is : " + sentence1);
}

}

最佳答案

什么Scanner#nextLine所做的是

Advance this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end.

由于您的输入是 eraera food food Correct Correct sss sss exit,因此您在 while 中用 Scanner#next 读取每个单词,因此当调用 Scanner#nextLine 时,它会返回 ""(空字符串),因为该行没有剩余任何内容。这就是为什么您会看到您输入的单词是:(文本开头是空字符串)。

如果您使用此输入:eraera food food Correct Correct sss sss exit lastWord,您会看到您输入的单词是:lastWord

为了解决这个问题,您唯一需要做的就是调用 scan.nextLine(); 首先移动到用户将提供的新输入的下一行,然后使用 Scanner#nextLine() 获取新单词,如下所示:

Scanner scan = new Scanner(System.in);
String str="";
String exit="exit";

System.out.println("Please enter some words : ");
while(true){
str=scan.next();
if(str.equalsIgnoreCase(exit)) break;
System.out.println(str);
}

scan.nextLine(); // consume rest of the string after exit word
System.out.println("Please enter a sentnce : ");
String sentence1 = scan.nextLine(); // get sentence

System.out.println("the word you entered is : " + sentence1);

演示:https://ideone.com/GbwBds

关于java - nextLine 方法给了我一个不正确的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52974735/

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