我正在尝试使用2个用户输入填充2d列表数组。
我遇到的问题是,在下面的代码中,第一个for
语句没有产生我期望的结果,第二个for
正在做所需的事情。此外,使用下面的代码我无法关闭扫描仪。
public static void main(String[] args) {
ArrayList<String> listCon = new ArrayList<String>();
ArrayList<String> listCol = new ArrayList<String>();
Scanner txtInput = new Scanner(System.in);
char addTo = 'y';
do {
System.out.println("\nCurrent list is " + listCon + listCol + "\n");
System.out.println("Would you like to add a country to the list?\n\t"
+ "( y ) = YES\n\t( n ) = NO");
addTo = txtInput.next().toLowerCase().charAt(0);
if (addTo == 'y') {
System.out.println("Enter country name: ");
listCon.add(txtInput.next().toLowerCase());
System.out.println("Enter colour: ");
listCol.add(txtInput.next().toLowerCase());
} else if (addTo == 'n') {
int i = 1;
int countCon = listCon.size();
if(countCon == 0) {
System.out.println("No countries have been entered.");
} else {
String str = "country";
if(countCon > 1) {
str = "countries";
}
System.out.println("Thankyou for your input. We found " + countCon + " " +
str + " in the list.");
System.out.println("Listed " + str + ":\n");
for(String n : listCon) {
char[] conDigit = n.toCharArray();
conDigit[0] = Character.toUpperCase(conDigit[0]);
n = new String(conDigit);
for(String b : listCol) {
char[] colDigit = b.toCharArray();
colDigit[0] = Character.toUpperCase(colDigit[0]);
b = new String(colDigit);
System.out.println("Country " + i + " : " + n + " - \t" + b);
i = i + 1;
}
break;
}
break;
}
} else {
System.out.println("Incorrect input detected. please try again. \n");
}
} while (true);
}
}
答案 0 :(得分:1)
您需要从第一个break
循环中删除额外的for
以进行迭代。否则,在第一次迭代后中断。
for(String n : listCon) {
....
for(String b : listCol) {
...
}
break; //remove this!
}
break;
修改强>
之后的结果是国家1:法国 - 蓝色国家2:英国 - 白色国家3:爱尔兰 - 绿色
你需要像这样迭代:
for (int i = 0; i < listCon.size() && i < listCol.size(); i++) {
String n = listCon.get(i);
char[] conDigit = n.toCharArray();
conDigit[0] = Character.toUpperCase(conDigit[0]);
n = new String(conDigit);
String b = listCol.get(i);
char[] colDigit = b.toCharArray();
colDigit[0] = Character.toUpperCase(colDigit[0]);
b = new String(colDigit);
System.out.println("Country " + i + " : " + n + " - \t" + b);
}