2015-06-19 36 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.仅字母数字 - 没有特殊字符

当用户在文本框中输入“无效”字符时,会出现一个红色标签,警告用户无效输入。

这些只是简单的解决方案,并有更好的方法来解决这个问题