我应该知道该怎么做,但也许我只是累了。无论如何,我需要编写一个简单的 while 循环,询问用户他们想要每个项目的数量(使用扫描仪)。有四项。目前的代码如下所示:
int item1Amount;
int item2Amount;
int item3Amount;
int item4Amount;
int c = 1;
while (x != -1) {
System.out.print("Enter the number of Item " + c + " you would like to purchase: ");
item1Amount = input.nextInt();
c++;
}
我在逻辑上遇到的问题是,当它返回循环时,它将要求项目 2、3 和 4,但仍将用户输入输入为 item1Amount
。如何才能正确完成此操作?
最佳答案
使用 ArrayLists(最干净的版本):
ArrayList<Integer> itemAmounts = new ArrayList<Integer>();
int c = 1;
int x = 0;
while(x!=-1){
System.out.print("Enter the number of Item "+c+" you would like to purchase: ");
int x = input.nextInt();
itemAmounts.add(x);
c++;
}
使用数组(仅限四个项目)
final int NUMB_ITEMS = 4;
int[] itemAmounts = new int[NUMB_ITEMS];
int c = 0;
int x = 0;
while(x!=-1 && c < NUMB_ITEMS){
System.out.print("Enter the number of Item "+(c+1)+" you would like to purchase: ");
int x = input.nextInt();
itemAmounts[c] = x;
c++;
}
没有任何数据结构:
int item1Amount;
int item2Amount;
int item3Amount;
int item4Amount;
int c = 1;
int a = 0;
while(x!=-1 && c<= 4){
System.out.print("Enter the number of Item "+c+" you would like to purchase: ");
a=input.nextInt();
switch(c){
case 1:
item1Amount = a;
break;
case 2:
item2Amount = a;
break;
case 3:
item3Amount = a;
break;
case 4:
item4Amount = a;
break;
default:
break;
}
c++;
}
没有任何数据结构,也没有开关(呃……第 4 章很糟糕):
int item1Amount;
int item2Amount;
int item3Amount;
int item4Amount;
int c = 1;
int a = 0;
while(x!=-1 && c<= 4){
System.out.print("Enter the number of Item "+c+" you would like to purchase: ");
a=input.nextInt();
if(c == 1){
item1Amount = a;
} else if(c == 2){
item2Amount = a;
} else if (c == 3){
item3Amount = a;
} else if (c == 4) {
item4Amount = a;
}
c++;
}
关于java - 在java中使用while循环在每次迭代中添加到不同的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25902204/