2017-03-16 55 views
0

我正在嘗試爲我正在練習的小型個人銀行帳戶項目實現某些功能。我想這樣做,以便如果用戶輸入一個空格,或者根本不輸入任何內容(意味着他們按下輸入,而不輸入值)帳戶的默認名稱切換到「默認」。如何接受掃描器輸入的空白​​值

像這樣:

Scanner read = new Scanner(System.in); 
System.out.print("Enter your account's name: "); 
String input = read.next(); 
String name = ""; 

if (input == "" || input == null) { 
    name = "Default"; 
} else { 
    name = input; 
} 

可能是一個愚蠢的問題,但是這是一個地方我有一個小麻煩。如果我輸入一個空格然後按回車鍵,則不會繼續設置名稱。如果在提示輸入時按Enter鍵,則不會繼續設置名稱。有沒有辦法設置它?

編輯:我不想知道一個字符串是否等於另一個字符串通過.equals()(謝謝你順便說一句)。掃描儀仍然不接受空白輸入。

+4

使用.equals()比較java中的字符串 – Sweeper

+0

,==用於原始值相等或對象引用相等。像Sweeper提到的那樣,通過.equals()確定對象值的相等性() –

+0

True。但是,無論如何,我仍然無法輸入空白字符並讓掃描儀接受它。 :/ – Jack

回答

0
Scanner sc=new Scanner(System.in); 
    System.out.print("Enter your account's name: "); 
    String input = sc.nextLine(); 
    String name = ""; 
    // System.out.println(input); 
    if (input.isEmpty()) { 
     name = "Default"; 
    } else { 
     name = input; 
    } 
System.out.println(name); 

這個f9試試吧。