簡體   English   中英

如何讀取 Java 中的空行?

[英]How can I read an empty line in Java?

如果用戶按下回車,我希望能夠讀取空行,但同時我希望能夠在他插入任何內容時讀取包含內容的行。

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

問題是每次用戶插入任何內容時,我只收到一個空字符串。

我認為 sc 是掃描儀 object 所以我已經完成了這樣的代碼。

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> 

希望這對你有用

我同意@Wahidullah Shah的觀點。

但是,我相信您的問題是由於在nextInt()next()等之后使用nextLine()引起的。 我做出這個假設是基於您只提供了一小部分代碼的事實。

問題是, nextInt()不消耗return character 之后立即調用nextLine()時,它只會消耗返回字符,從而為您提供空字符串。

研究鏈接:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM