Scanner未实际接收用户输入。

huangapple go评论73阅读模式
英文:

Scanner not actually taking in user input

问题

我尝试过不同的Scanner用法(我希望它可以读取文件,但我也尝试过仅使用字符串),但它就像忽略了代码一样,没有显示任何错误消息。

public static void main(String[] args)
throws FileNotFoundException {

  Scanner test = new Scanner(System.in);
  String testLine = test.next();

  Scanner input = new Scanner(new File("data.txt"));

  while(input.hasNextLine){
     String name = input.nextLine();
     String letters = input.nextLine();
     System.out.println(name + ": " + letters);
  }

}

英文:

I've tried different uses for Scanners (I want it to read in Files but I also tried just Strings), and it just skips over the code as if it doesn't exist. No error messages are shown.

   public static void main(String[] args)
      throws FileNotFoundException {
      
      Scanner test = new Scanner(System.in);
      String testLine = test.next();

      Scanner input = new Scanner(new File("data.txt"));

      while(input.hasNextLine){
         String name = input.nextLine();
         String letters = input.nextLine();
         System.out.println(name + ": " + letters);
      }
   }

答案1

得分: 1

你的代码无法编译,因为hasNextLine()是一个函数,而不是一个类成员。

实际上,你正在从System.in读取test.next(); - 你必须输入一些文本,然后你的代码将继续运行。它只是在等待用户输入 - 因此不会抛出异常。

英文:

Your code doesn't compile, because hasNextLine() is a function, not a class member.

You are actually reading from System.in at test.next(); - you have to enter some text, then your code will continue to run. It's just waiting for a user input - thus no exception is thrown.

答案2

得分: 1

在这行代码中:

String testLine = test.next();

您的程序正在等待您的输入。在您提供输入之前,它无法继续执行下一行。

编辑:
参考Charlie的评论,这是关于System.in的一句引用,来自文档

"standard"输入流。此流已打开并准备好提供输入数据。通常,此流对应于键盘输入或由主机环境或用户指定的其他输入源。

更多信息请查看此处

英文:

At this line of code:

String testLine = test.next();

your program is waiting for your input. It cannot proceed to next line till you provide an input.

EDIT: <br>
Taking cue from Charlie's comment below, here is a quote about System.in from docs.

> The "standard" input stream. This stream is already open and ready to supply input data. Typically this stream corresponds to keyboard input or another input source specified by the host environment or user.

More here..

huangapple
  • 本文由 发表于 2020年8月13日 12:34:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63388197.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定