[英]How to print elements from generic array list, using iterator in Java
[英]How to print elements from an array list
到目前為止,我一直在網上尋求幫助,但沒有任何幫助。 這就是我現在所擁有的,您能告訴我這是怎么回事嗎?
導入java.util。*;
class employeeProgram{
public static void main(String[] args){
for (int count = 0; count < 1; ){
Scanner input = new Scanner(System.in);
ArrayList<String> employeeNames = new ArrayList<String>();
String commnd;
print("What would you like to do? (Add, Remove, List, Exit): ");
commnd = input.next();
if ("Add".equals(commnd)){
print("Enter the name of the employee you'd like to add to the list: ");
employeeNames.add(input.next());
} else if ("Remove".equals(commnd)){
print("Enter the name of the employee you'd like to remove from the list: ");
employeeNames.remove(input.next());
} else if ("List".equals(commnd)){
for (int j = 0; j < employeeNames.size(); j++){
println(employeeNames.get(j));
println(j);
}
//println(employeeNames);
} else if ("Exit".equals(commnd)){
input.close();
break;
} else {
println("Invalid command.");
}
}
}
public static void println(Object x){
System.out.println(x);
}
public static void print(Object x){
System.out.print(x);
}
}
for循環還沒有開始,我知道很多,因為“ println(j)”也不起作用。 當我嘗試注釋掉的部分時,從輸入列表中獲得的全部是“ []”,僅此而已。 我是一個初學者,這是我使用ArrayLists的第一個程序,所以在此先感謝那些決定幫助我的人:)
在第一個for
循環之外定義您的employeeNames
列表。 ArrayList在每次循環迭代時都會重新初始化。
for(int count = 0; count <1; count ++)
您需要定義循環之外的arraylist,否則,每次迭代都會創建一個新的arrayList,並且對以前的arraylist所做的先前更改將被垃圾收集。
import java.util.*;
class employeeProgram{
public static void main(String[] args){
ArrayList<String> employeeNames = new ArrayList<String>();
for (int count = 0; count < 1; ){
Scanner input = new Scanner(System.in);
String commnd;
print("What would you like to do? (Add, Remove, List, Exit): ");
commnd = input.next();
if ("Add".equals(commnd)){
print("Enter the name of the employee you'd like to add to the list: ");
employeeNames.add(input.next());
} else if ("Remove".equals(commnd)){
print("Enter the name of the employee you'd like to remove from the list: ");
employeeNames.remove(input.next());
} else if ("List".equals(commnd)){
for (int j = 0; j < employeeNames.size(); j++){
println(employeeNames.get(j));
println(j);
}
//println(employeeNames);
} else if ("Exit".equals(commnd)){
input.close();
break;
} else {
println("Invalid command.");
}
}
}
public static void println(Object x){
System.out.println(x);
}
public static void print(Object x){
System.out.print(x);
}
}
另外,我將對該程序進行一些基本更改,首先-應該在知道執行多少次迭代的地方使用for循環。 在您的情況下,更適合使用while循環(或者更好的是do-while循環)。
最后,創建一個線性函數來封裝system.out.print和println似乎比必要的工作多。
每當您問一個問題時,您都在創建一個新的ArrayList。 在初始循環之外創建它。
ArrayList<String> employeeNames = new ArrayList<String>();
我會嘗試其他方法,而不是for循環:
盡管您在這里擁有的東西可能在技術上可行,但是for ...循環用於確定性過程。 在這里,您將其用作無限循環,希望在以后強制中斷。 這很危險,並可能導致錯誤。
我會改變這個:
for (int count = 0; count < 1; ){
對此:
bool done = false;
while(!done) {
然后,以后,當您想突圍時。 發出這一行:
done = true;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.