我需要编写用户输入验证程序的帮助。我已经做了一个家庭作业来编写一个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);
}
}
}
非常感谢你快速回复巴尔克里希纳,我用你提供了解决崩溃的问题,第二个例子,当用户输入像串而不是整数,但我现在面对的唯一一个探针是我不知道如何让程序允许用户再次尝试,直到收到正确的输入,再次感谢您。 – John
查看更新的答案。希望你的代码清楚。在Java程序中非常频繁地使用像if-else,switch-case,for,while和do-while这样的控制流构造,并且非常重要的是您能够很好地理解它们。 –
我非常感谢这一点,我必须说你比我的老师更擅长你解释的事情,我真的希望你是我的老师哈哈......我将继续阅读本主题中的所有教程,因为我真的很想成为程序员,而不仅仅是通过这个类。多年来,我一直想进入编程,我相信现在是时候了。我会尝试用Java自我刷新,然后转向Python,希望有一天我也可以开始帮忙。我真的不能够感谢你。 – John