我一直在做這個任務幾周,需要一些幫助。請不要將我引用到JavaDocs,因爲我已經無數次地檢查了它們,並且無法找到我的程序的解決方案。 這是我需要做的:創建一個ArrayList購物清單並在表中顯示結果
- 根據用戶鍵入的輸入一次一個地添加項目到ArrayList。系統會提示用戶將字符串存儲在ArrayList中,然後按回車鍵。用戶將能夠繼續添加項目到ArrayList,直到他們只需輸入而不輸入任何內容。
一旦用戶執行此(命中而無需鍵入任何輸入),則程序將顯示所有該ArrayList的元素,兩者的索引和字符串值,在表中。它會做到這一點通過單循環
這是代碼,我到目前爲止有:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.ArrayList;
// declares a name for the class
public class GroceryList2 {
/**
* Allows the program to be run and throws the Input-Output exception
* error
*/
public static void main(String[] args) throws IOException {
BufferedReader userInput =
new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(System.in);//allows for input
// declares the ArrayList to be a String
ArrayList<String> myArr = new ArrayList<String>();
myArr.add("Milk");
myArr.add("Cheese");
myArr.add("Eggs");
myArr.add("Bread"); //the values of the ArrayList already entereed
// the loop that allows the criteria to run
while(true) {
if(myArr.isEmpty()== false) {
System.out.println("Enter the items for the grocery list: ");
String item = in.next();//asks and allows for input
myArr.add(item);
}
else if(myArr.isEmpty()== true) {
for (int i=0; i<myArr.size(); i++) {
// displays the list after the input
System.out.print(
"The Grocery List "+ i+ ": "+ myArr.get(i));
}
}
}
}
}
代碼編譯,但是當我剛按下回車鍵,不顯示購物清單,它等待另一個條目。
您將元素添加到列表中,然後您驚訝列表不是空的? – WilQu
歡迎來到StackOverflow。在這裏傾銷你的代碼,尤其是家庭作業,並問「出了什麼問題?」通常沒有生產力,也不是每個FAQ的有效問題。如果你對爲什麼你的代碼沒有做到你期望的那樣感到困惑,那麼調試器是一個很好的開始。 –
我覺得有趣的是,這應該是一個可以幫助人們的論壇,然而很多人似乎都認爲這些人是優秀的。我尋求幫助,因爲我花了數小時甚至數週時間,無法找到所需的解決方案。我嘗試過改變代碼的方式,因爲我知道怎麼做,查看了所有的文檔,但我不明白,因此我在尋求幫助。爲了將來的參考,這個作業實際上並不是爲了任何功勞,而是爲了我自己的知識,如果你不會幫助那很好,但是你也可能只是沒有回答。 –