2014-03-03 76 views
-4
import java.util.Scanner; 
public class UserInput { 

    public static void main(String[] args) { 
    // TODO Auto-generated method stub 

     boolean alpha = false; 
     boolean numeric = false; 
     boolean accepted = true; 
     boolean underscore=false; 

     Scanner s = new Scanner(System.in); 
     System.out.println("please Enter an Idintifire: " +s); 
      char c = s.next().trim().charAt(0); 
      if (Character.isDigit(c)) 
      { 
       numeric = true; 

      } else if (Character.isLetter(c)) 
      { 
       alpha = true; 

      } 
      else if (Character.isUnicodeIdentifierPart(c)) 
      { 
       underscore = true; 
      } 
      else 
      { 
       accepted = false; 

      } 

     if (accepted && alpha && numeric && underscore) 
     { 
      System.out.println("this is an idintifire " +c); 
     } 

     else { 
      System.out.println(c+ " this not an idintifire "); 

     } 
     s.close(); 
     } 
    }  

輸出:我從Eclipse中有奇怪的錯誤

please Enter an Idintifire: java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q?\E][infinity string=\Q?\E] 

我希望用戶只輸入一個單個字母數字字;例如,(ab_23)不是(ab 23)

有什麼建議嗎?

回答

0
Scanner s = new Scanner(System.in); 
System.out.println("please Enter an Idintifire: " +s); 

您正在打印上面一行中創建的掃描儀對象的值。嘗試刪除打印語句中的s。

 System.out.println("please Enter an Idintifire: "); 

編輯:

Scanner s = new Scanner(System.in); 
System.out.println("please Enter an Idintifire: "); 
String input = s.next(); 
for(int i=0;i< s.length();i++){ 
char c = input.charAt(i); 
     if (Character.isDigit(c)) 
     { 
      numeric = true; 

     } else if (Character.isLetter(c)) 
     { 
      alpha = true; 

     } 
     else if (Character.isUnicodeIdentifierPart(c)) 
     { 
      underscore = true; 
     } 
     else 
     { 
      accepted = false; 

     } 

    } 

    if (accepted && alpha && numeric && underscore) 
    { 
     System.out.println("this is an idintifire " +input); 
    } 

    else { 
     System.out.println(input+ " this not an idintifire "); 

    } 
+0

我改變了它,但是當我進入(ab_23)的程序沒有檢查輸入,它只是檢查的第一個字符,有什麼辦法創建一個for循環來讀取所有輸入並將其與其他條件進行比較。 – user3368970

+0

它僅檢查第一個字符,因爲您只在if else構造之前選擇了0處的字符。檢查我的答案的編輯部分。 – Adarsh