我需要編寫用戶輸入驗證程序的幫助。我已經做了一個家庭作業來編寫一個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