【问题标题】:How can I read an empty line in Java?如何在 Java 中读取空行?
【发布时间】:2020-08-14 13:26:38
【问题描述】:

如果用户按下回车,我希望能够读取空行,但同时我希望能够在他插入任何内容时读取包含内容的行。

System.out.println("Name> ");
String nome = sc.nextLine();
System.out.println("--" + nome + "--");
System.out.println("Id> ");
String id = sc.nextLine();
System.out.println(" ")

问题是每次用户插入任何内容时,我只收到一个空字符串。

【问题讨论】:

  • scsc.nextLine() 之前你会做什么 - 你有像sc.next()sc.nextDouble() 这样的电话吗?
  • 从那个 sn-p 中,您没有打印出id,只是一个空白空间。

标签: java string input


【解决方案1】:

我认为 sc 是一个扫描器对象,所以我已经完成了你的代码。

Scanner sc = new Scanner(new InputStreamReader(System.in));
    System.out.println("Name> ");
    String nome = sc.nextLine();
    System.out.println("--" + nome + "--");
    System.out.println("Id> ");
    String id = sc.nextLine();
    System.out.println(" ");

这很好用

this is the output for a line with content 
Name> 
wahidullah
--wahidullah--
Id> 
200

this is the ouput for an empty line
Name> 

----
Id> 

希望这对你有用

【讨论】:

    【解决方案2】:

    我同意@Wahidullah Shah

    但是,我认为您的问题是由 nextLine()nextInt() 之后使用引起的em>、next() 等。 我做出这个假设是基于您只提供了一小部分代码。

    问题是,nextInt() 不消耗返回字符。当 nextLine() 之后被调用时,它只是消耗 return 字符,从而给你空字符串.

    研究链接:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 1970-01-01
      相关资源
      最近更新 更多