首先我知道ArrayLists並且不希望將它們用於此程序。我正在爲當地動物園制定一個計劃(很開始的階段,不會是最終版本)。它需要用戶輸入並允許他們輸入動物和他們吃的食物。如果我一次輸入一種食物,我的程序就能正常工作,但我正在努力解決的是如何處理用戶輸入,並添加多種食物。 (提示會引導他們輸入以逗號分隔的食物,但是有些用戶可能只是在兩者之間使用空格,我需要通過錯誤消息或簡單地接受它和CSV來解釋。)有沒有辦法做到這一點,以後檢索添加逗號的值?對不起,我對Java很新,感謝您的幫助!在添加到Java中的數組之前刪除字符
代碼的用戶輸入:
//create array
static String[][] animalFood;
String[][] addArray(int x) {
animalFood = new String[x][2];
Scanner in = new Scanner(System.in);
//loop through array and add amount of items user chose
for (int row = 0; row < animalFood.length; row++){
System.out.print("Enter an animal name: ");
animalFood[row][0] = in.nextLine();
System.out.print("Enter the food the animal eats: ");
animalFood[row][1] = in.nextLine();
}
System.out.println("Thank you for adding information to the zoo!");
System.out.println("You entered the following information: ");
//loop through and print the informationa added
for(int i = 0; i < animalFood.length; i++)
{
for(int j = 0; j < animalFood[i].length; j++)
{
System.out.print(animalFood[i][j]);
if(j < animalFood[i].length - 1) System.out.print(" - ");
}
System.out.println();
}
代碼搜索功能:
String[][] searchArray(String name) {
String matchResult = "There was no " + name + " found in the zoo!";
String itemToMatch = name.toUpperCase();
String arrayItem = "";
String food = "";
for (int i = 0; i < animalFood.length; i++) {
arrayItem = animalFood[i][0];
arrayItem = arrayItem.toUpperCase();
if(arrayItem.equals(itemToMatch)){
matchResult = "The animal " + name + " was found in the zoo! It eats " + animalFood[i][1];
}
else {
//nothing found
}
}
System.out.println(matchResult);
if (food != null) {
System.out.println(food);
}
return animalFood;
}
你如何確定用戶輸入不正確,需要修改?例如,如果用戶輸入「紅蘿蔔;紅木」,這是否需要分離爲「胡蘿蔔;紅色;木材」? – Nier
可能的重複:http://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java – Nier