![](/img/trans.png)
[英]How to input new line string using java-util-scanner in this situation?
[英]How can I handle new line character using java-util-scanner in this situation?
我有一個簡單的家庭作業,我正在制作一個簡單的UI(不是GUI),我正在使用掃描儀進行輸入。
我想讀3個字符串(姓名,地址,社會安全號碼)
如果用戶沒有插入任何東西只需按Enter鍵,我的代碼就會中斷。 而不是我需要的3個字符串,我得到更多的字符串,他們錯過了匹配。
Scanner input = new Scanner(System.in);
if (input.hasNext()) {
name = input.nextLine();
}
Scanner input = new Scanner(System.in);
if (input.hasNext()) {
address = input.nextLine();
}
Scanner input = new Scanner(System.in);
if (input.hasNext()) {
ssnumb = input.nextLine();
}
因此,如果用戶按Enter鍵,則創建一個新的行字符,輸入溢出。 我怎樣才能避免這種情況或消除空行?
例:
輸入
缺口
火星
一些數字
我會:
Name:
Address:
尼克
Social Security Number:
火星
像這樣的東西:
Scanner input = new Scanner(System.in);
while(!input.next().isEmpty()) { // only when you enter literal string
//do your scanner stuff here
}
嘗試
Scanner input = new Scanner(System.in);
String name = "";
while(name.trim().isEmpty()) {
name = input.next();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.