【问题标题】:The nextLine method is giving me an incorrect implementationnextLine 方法给了我一个不正确的实现
【发布时间】:2018-10-24 17:21:48
【问题描述】:

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

输入:era era food food correct correct sss sss exit

我应该使用另一个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);
}

}

【问题讨论】:

  • doesn't work具体是什么意思?
  • 第二次扫描调用后我无法输入任何句子
  • 请发布您正在使用的输入数据。
  • 请输入一些单词:时代食物食物正确正确sss sss退出请输入句子:您输入的单词是:
  • Please enter a sentence : 被打印出来后,你(实际上)输入了什么(句子)?

标签: java string java.util.scanner


【解决方案1】:

Scanner#nextLine 所做的是

将此扫描器前进到当前行并返回 被跳过。此方法返回当前行的其余部分, 不包括末尾的任何行分隔符。

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

如果您使用此输入:era era food food correct correct sss sss exit lastWord,您会看到the word you entered is : 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

【讨论】:

  • 是的,谢谢,它有效,而且也是一个更好的主意
猜你喜欢
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-22
  • 2011-12-03
  • 2010-09-21
  • 1970-01-01
相关资源
最近更新 更多