2015-12-08 124 views
0

我是新來的Java,我想知道是否有一種不同的方法,我可以使用,而不是has.nextInt(),因爲這種方法弄亂我的掃描儀。例如替代方法.hasNextInt?

do { 
    System.out.println("Please enter your full name: "); 
    memberName = input.nextLine(); 
    if (input.hasNextInt()) { 
     System.out.println("Your name cannot contain a number"); 
     input.next(); 
    } else { 
     successful = true; 
    } 
} while (successful == false); 

控制檯

Create new member 
Please enter your full name: 
jack 
jack 

我必須輸入我的名字兩次運動之前在 我知道那裏有問題,有像這一點,但我已經受夠了任何存在的解決方案沒有運氣。由於

編輯

我想,以確保輸入不包含在所有的任何號碼,如果是的話那麼

System.out.print("Your name cannot contain any numbers"); 

發生

+2

你有什麼期望'input.hasNextInt()'做什麼? –

+0

你能提供一些你想接受的名字的例子嗎?你想接受'foo123'嗎?或者如果有人有兩個名字像傑克亞當史密斯那樣? – Pshemo

+0

我只想接受只有喬博客,jon stevens的信件。我不想接受任何數字或foo123 @Pshemo –

回答

1

if(input.hasNextInt()){的用法是錯誤的這裏。當你想找到你以前輸入的字符串中的數字是memberName

您可以使用正則表達式用於此目的:

Pattern digitPattern = Pattern.compile("\\d+");  

然後你就可以用它來驗證任何字符串:

System.out.println(digitPattern.matcher("Marcinek 234").matches()); 
+0

你能舉個例子嗎? –

+1

我想我已經做到了。 – Marcinek

0
從用戶輸入

如果你只想看行,你可以使用:

hasNextLine() 

或Y OU可以只使用:

hasNext() 

而試圖改變這一點:

while (successful == false); 

有了這個:

while (successful); 
0

你可以使用:enteredName.contains( 「1」),以檢查數字。 例如:

boolean containsNumbers = false; 
for(int i = 0; i<9; i++){ 
if (name.contains(""+i)) containsNumbers = true; 
} 
1
do { 
    System.out.println("Please enter your full name: "); 
    memberName = input.nextLine(); 
    if (memberName.contains("1234567890")) { 
     System.out.println("Your name cannot contain a number"); 
    } else { 
     successful = true; 
    } 
    input.next(); 
} while (successful == false); 

你在你的if語句來檢查使用的輸入,但是您分配成員名稱到整條生產線。

1

嘗試創建您自己的方法,它將測試傳遞的名稱是否有效。它可以看看比如像這樣:

private static boolean isValidName(String name){ 
    return name.matches("[a-z]+(\\s[a-z]+)*");//can be optimized with precompiled Pattern 
} 

現在你的代碼可以是這樣的:

System.out.println("Please enter your full name: "); 
do { 
    memberName = input.nextLine(); 
    successful = isValidName(memberName); 
    if (!successful) { 
     System.out.println("Your name is not valid. Valid name can contain only letters and spaces. No digits are allowed."); 
     System.out.println("Please try again: "); 
    } 
} while (!successful); 
System.out.println("welcome: "+memberName);