Java 如何为此代码编写简单的输入验证

Java 如何为此代码编写简单的输入验证,java,Java,我需要一个关于编写用户输入验证程序的帮助。我的作业是编写一个Java程序,使用数组或ArrayList,在其中存储10条消息,并要求用户在0和10之间进行选择,以显示一条消息,并生成另一条随机消息 我能够完成这个程序并提交它,但是如果用户输入的字符不是整数,或者输入的整数v不在0到10之间,我的程序就会崩溃 我想通过输入验证重新提交作业,以获得更好的成绩,所以我决定向专业人士寻求帮助,我大约5周前才开始学习编程 以下是我提交的作业: public static void main(String[

我需要一个关于编写用户输入验证程序的帮助。我的作业是编写一个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 );

  }
  }
}
publicstaticvoidmain(字符串[]args){
System.out.println(“请通读下面的10条消息,并按照它们下面的说明操作”);
List List=新建ArrayList(10);//在ArrayList中生成对象
//创建ArrayList对象
//向Arraylist添加元素
列表。添加(0,“我试着做个好人。”);
增加(1,“没有人是完美的。”);
增加(2,“生活是美好的”);
添加(3,“这就是我。”);
列表。添加(4,“系统输出”);
增加(5,“现在是夏天”);
增加(6,“我喜欢青椒”;
添加(7,“他很有趣”);
列表。添加(8,“存在挑战”);
增加(9,“你叫什么名字”);
首件连接消息(列表);
System.out.println(“从Arraylist检索存储的消息”);
ShoutOutRandomMessage();
}
//此方法使用get方法从ArrayList检索值
公共静态void shoutOutCannedMessage(列表消息){
int size=message.size();

对于(int i=0;i您从用户处获得的数字存储在变量
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.");
public void AlphaOnly(字符串输入,JLabel obj){
如果(!“”.equals(输入)){
obj.setText(“”);
警告=错误;
char c[]=input.toCharArray();
整数计数=0;
对于(int x=0;x0){
obj.setText(“*请使用有效字符”);
警告=正确;
}否则{
obj.setText(“”);
警告=错误;
}
}否则{
obj.setText(“*此字段不能为空。”);
警告=正确;
}   
}
仅数字公开无效(字符串输入,JLabel obj){
char c[]=input.toCharArray();
如果(!“”.equals(输入)){
obj.setText(“”);
警告=错误;
整数计数=0;
对于(int x=0;x0){
obj.setText(“*请使用有效字符”);
警告=正确;
}否则{
obj.setText(“”);
警告=错误;
如果(c.length=7)和(c.length=13){
如果(!input.contains(“@”)| |(!input.endsWith(“.com”)| |(input.contains(“”))| |(input.contains(“/”)| |(input.contains(“+”)|(input.contains(“+”))|(input.contains(“=”){
obj.setText(“*请使用有效的电子邮件地址”);
警告=正确;
}否则{
obj.setText(“”);
警告=错误;
}
}否则{
obj.setText(“*请使用有效的电子邮件地址”);
警告=正确;
}
}否则{
obj.setText(“*此字段不能为空。”);
警告=正确;
} 
}
public void AlphaNumericOnly(字符串输入,JLabel obj){
如果(!“”.equals(输入)){
obj.setText(“”);
警告=错误;
char c[]=input.toCharArray();
整数计数=0;
对于(int x=0;x0){
obj.setText(“*请使用有效字符”);
警告=正确;
}否则{
obj.setText(“”);
警告=错误;
}
}否则{
obj.setText(“*此字段不能为空。”);
警告=正确;
}   
}
我写了这些简单的代码来检查我所做项目的“输入”。 这些检查用户输入是否为: 1.仅限信件 2.仅限数字 3.有效电子邮件(尽管这仅检查用户输入是否有“@”和“.com”) 4.有效的联系人号码(仅当有7个或更多号码时才检查) 5.仅字母数字-无特殊字符

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


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

非常感谢您的快速回复Balkrishna,我使用了您提供的第二个示例,它解决了当用户输入字符串而不是整数时崩溃的问题,但我现在面临的唯一问题是我不知道如何使程序允许请用户重试,直到收到正确的输入。再次感谢。请参阅更新的答案。希望代码对您来说是清楚的。控制流结构(如if-else、switch-case、for、while、do-while)在Java程序中非常频繁地使用,您必须很好地理解它们。对此我非常感谢,我必须告诉您你解释事情的方式比我的老师好,我真的希望你是我的老师,哈哈……我会继续阅读这篇文章中的所有教程,因为我真的想成为一名程序员,而不仅仅是通过这门课。多年来我一直想进入编程领域,我相信现在是时候了。我会努力用Java来复习自己然后转到Python,希望有一天我也能开始帮忙。我真的非常感谢你。不客气。祝你好运。现在,如果这个答案对你有帮助,你可以接受答案(单击左侧的复选符号)。
 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.");
 }
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);
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;
}   
}