2015-06-19 65 views
-4

我需要編寫用戶輸入驗證程序的幫助。我已經做了一個家庭作業來編寫一個Java程序,使用數組或ArrayList來存儲10條消息,並要求用戶在0和10之間進行選擇,以顯示消息並生成另一個隨機消息。如何爲此代碼編寫簡單的輸入驗證

我能夠完成這個計劃,並提交它,但如果用戶把任何其它字符不是整數我的程序崩潰,或者,如果他提出的整數,V是不是0的範圍內,以10

我想重新提交輸入驗證的作業以獲得更好的成績,所以我決定向專業人士尋求幫助,我再次在5周前開始學習編程。

下面是我提交的功課:

public static void main(String[] args) { 
     System.out.println("Please read through the folowing 10 messages and follow the instruction under them."); 

    List<String> list = new ArrayList <String>(10); // making object in ArrayList 

     //create an ArrayList object 

    //Add elements to Arraylist 

    list.add(0, "I try to be good."); 
    list.add(1, "Nobody is Perfect."); 
    list.add(2, "Life is good"); 
    list.add(3, "This is me."); 
    list.add(4, "System out"); 
    list.add(5, "It's summer time"); 
    list.add(6, "i like green pepper,"); 
    list.add(7, "He is funny"); 
    list.add(8, "There are Challenges"); 
    list.add(9, "What is your name"); 

    shoutOutCannedMessage(list); 

    System.out.println("Retrieving stored messages from Arraylist"); 

    ShoutOutRandomMessage(); 

    } 


     //This method retrieves values from ArrayList using get method 


    public static void shoutOutCannedMessage(List<String> message) { 

    int size = message.size(); 
    for(int i=0;i<size;i++) 
    { 
System.out.println(message.get(i)); 

    } 
    // To retrieve User's Choice 
    int userChoice; 
    Scanner scanner = new Scanner(System.in); 
    // Inform the user to select one of the messages that poped up above 
    System.out.println("Please enter a number of your choice from 0 to 10"); 
    userChoice = scanner.nextInt(); 
    System.out.println(message.get(userChoice)); 
    } 
/** 
* 
*/ 
public static void ShoutOutRandomMessage() { 



    //holds the words to be generated. 

    String[] subject= {" He", " me", " She", "We"}; 
    String[] verb= {" do", " say", " get", " make", " know"}; 
    String[] adjective= {" good", " new", " first", " last", " long"}; 
    String[] object= {" cup", " map", " house", " computer"}; 
    String[] adverb= {" up. ", " so. ", " out. ", " now. ", " just"}; 


    Random r = new Random(); //intialize a Random 
    int selectedElement = r.nextInt(subject.length); 

    //randomly create sentence. 



{ 

String randomSentence=subject[selectedElement] 
    + verb[selectedElement]  
    + adjective[selectedElement] 
    + object[selectedElement] 
    + adverb[selectedElement]; 

System.out.println("ShoutOut: " + randomSentence); 

    } 
    } 
} 

回答

0

你從用戶那裏得到的數字存儲在變量userChoice。你需要檢查這個號碼是否有效。您只需添加if即可完成此操作。

替換此代碼:

System.out.println("Please enter a number of your choice from 0 to 10"); 
userChoice = scanner.nextInt(); 
System.out.println(message.get(userChoice)); 

與此:

System.out.println("Please enter a number of your choice from 0 to 10"); 
userChoice = scanner.nextInt(); 
if(userChoice >=0 && userChoice <=10) 
    System.out.println(message.get(userChoice)); 
else 
    System.out.println("The number you entered is not valid."); 

你可以走了一步,並檢查用戶輸入一個有效的數字。這可以這樣做:

System.out.println("Please enter a number of your choice from 0 to 10"); 
String userChoiceStr = scanner.next(); 
try{ 
    userChoice = Integer.parseInt(userChoiceStr); 
    if(userChoice >=0 && userChoice <=10) 
     System.out.println(message.get(userChoice)); 
    else 
     System.out.println("The number you entered is not valid."); 
} catch (NumberFormatException e) { 
    System.out.println("The number you entered is not valid."); 
} 

爲了讓用戶再試一次,如果他進入輸入錯誤: 你想的過程要重複,如果他進入輸入錯誤。重複進程意味着循環。 Java中有很多構造來編寫循環。在這種情況下,最好的選擇是使用do-while循環,因爲您希望用戶至少嘗試一次。

boolean isInputValid = false; 
do{ 
    System.out.println("Please enter a number of your choice from 0 to 10"); 
    String userChoiceStr = scanner.next(); 
    try{ 
     userChoice = Integer.parseInt(userChoiceStr); 
     if(userChoice >=0 && userChoice <=10) { 
      System.out.println(message.get(userChoice)); 
      isInputValid = true; 
     } 
     else 
      System.out.println("The number you entered is not valid."); 
    } catch (NumberFormatException e) { 
     System.out.println("The number you entered is not valid."); 
    } 
} while (!isInputValid); 
+0

非常感謝你快速回復巴爾克里希納,我用你提供瞭解決崩潰的問題,第二個例子,當用戶輸入像串而不是整數,但我現在面對的唯一一個探針是我不知道如何讓程序允許用戶再次嘗試,直到收到正確的輸入,再次感謝您。 – John

+0

查看更新的答案。希望你的代碼清楚。在Java程序中非常頻繁地使用像if-else,switch-case,for,while和do-while這樣的控制流構造,並且非常重要的是您能夠很好地理解它們。 –

+0

我非常感謝這一點,我必須說你比我的老師更擅長你解釋的事情,我真的希望你是我的老師哈哈......我將繼續閱讀本主題中的所有教程,因爲我真的很想成爲程序員,而不僅僅是通過這個類。多年來,我一直想進入編程,我相信現在是時候了。我會嘗試用Java自我刷新,然後轉向Python,希望有一天我也可以開始幫忙。我真的不能夠感謝你。 – John

0
public void AlphaOnly(String input,JLabel obj){ 
if(!"".equals(input)){ 
    obj.setText(" "); 
    warning=false; 

    char c[] = input.toCharArray(); 

    int count = 0; 
    for(int x=0; x<c.length; x++){ 
     if(!Character.isAlphabetic(c[x])){// && c[x]!='-' && c[x]!='(' && c[x]!=')' && c[x]!='+'&& c[x]!='/'&& c[x]!='\\'){ 
      count=+1; 

     } 
    } 
    if(count>0){ 
     obj.setText("*Please use valid characters."); 
     warning=true; 
    }else{ 
     obj.setText(" "); 
     warning=false; 
    } 
}else{ 
    obj.setText("*This Field cannot be left Empty."); 
    warning=true; 
} 
} 
public void DigitOnly(String input,JLabel obj){ 
char c[] = input.toCharArray(); 
if(!"".equals(input)){ 
    obj.setText(" "); 
    warning=false; 


     int count = 0; 
     for(int x=0; x<c.length; x++){ 
      if(!Character.isDigit(c[x])){// && c[x]!='-' && c[x]!='(' && c[x]!=')' && c[x]!='+'&& c[x]!='/'&& c[x]!='\\'){ 
      count=+1; 

      } 
     } 

      if(count>0){ 
       obj.setText("*Please use valid characters."); 
       warning=true; 
      }else{ 
       obj.setText(" "); 
       warning=false; 
       if(c.length<=4){ 
        obj.setText(" "); 
        warning=false; 
       }else{ 
        obj.setText("*Four digits Only."); 
        warning=true; 
       } 
      } 

}else{ 
    obj.setText("*This Field cannot be left Empty."); 
    warning=true; 
}  
}  
private void contactNumberCharOnly(String input,JLabel obj){ 
char c[] = input.toCharArray(); 
if(!"".equals(input)){ 
    if((c.length>=7)&&(c.length<=14)){ 
     obj.setText(" "); 
     warning=false; 

     int count = 0; 
     for(int x=0; x<c.length; x++){ 
      if(!Character.isDigit(c[x]) && c[x]!='-' && c[x]!='(' && c[x]!=')' && c[x]!='+'){ 
       count++; 
      } 
     } 
     if(count>0){ 
      obj.setText("*Please use valid characters."); 
      warning=true; 
     }else{ 
      obj.setText(" "); 
      warning=false; 
     } 
    }else{ 
     obj.setText("*This is not a valid contact no."); 
     warning=true; 
    } 
}else{ 
    obj.setText("*This Field cannot be left Empty."); 
    warning=true; 
} 
}  
private void isValidEmail(String input,JLabel obj){ 

    if(!"".equals(input)){ 
     obj.setText(" "); 
     warning=false; 
     if(input.length()>13){ 
      if((!input.contains("@"))||(!input.endsWith(".com"))||(input.contains(" "))||(input.contains("/"))||(input.contains("\\"))||(input.contains("+"))||(input.contains("="))){ 
       obj.setText("*Please use a valid Email Address."); 
       warning=true; 
      }else{ 
       obj.setText(" "); 
       warning=false; 
      } 
     }else{ 
      obj.setText("*Please use a valid Email Address."); 
      warning=true; 
     } 
    }else{ 
     obj.setText("*This Field cannot be left Empty."); 
     warning=true; 
    } 
} 
public void AlphaNumericOnly(String input,JLabel obj){ 
if(!"".equals(input)){ 
    obj.setText(" "); 
    warning=false; 

    char c[] = input.toCharArray(); 

    int count = 0; 
    for(int x=0; x<c.length; x++){ 
     if((!Character.isAlphabetic(c[x]))&&(!Character.isDigit(c[x]))){// && c[x]!='-' && c[x]!='(' && c[x]!=')' && c[x]!='+'&& c[x]!='/'&& c[x]!='\\'){ 
      count=+1; 

     } 
    } 
    if(count>0){ 
     obj.setText("*Please use valid characters."); 
     warning=true; 
    }else{ 
     obj.setText(" "); 
     warning=false; 
    } 
}else{ 
    obj.setText("*This Field cannot be left Empty."); 
    warning=true; 
} 
} 

我寫這些簡單的代碼來檢查「輸入」上一個項目,我做了。 這些檢查用戶輸入,如果他們是: 1.字母僅 2.號碼只 3.Valid電子郵件(儘管如果用戶輸入具有「@」 &「.com」之間這僅檢查) 4.有效接觸數(檢查只有在有7個或更多數字的情況下) 5.僅字母數字 - 沒有特殊字符

當用戶在文本框中輸入「無效」字符時,會出現一個紅色標籤,警告用戶無效輸入。

這些只是簡單的解決方案,並有更好的方法來解決這個問題