在java中使用while循环在每次迭代中添加到另一个变量

时间:2014-09-18 00:01:37

标签: java while-loop

我应该知道怎么做但也许我只是累了。无论如何,我需要编写一个简单的while循环,询问用户他们想要的每个项目有多少(使用Scanner)。有四个项目。该代码目前看起来如下:

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输入用户输入。怎么能正确完成?

4 个答案:

答案 0 :(得分:2)

使用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++;
}

答案 1 :(得分:0)

将此行移到循环之外。

int c=1;

您正在为c添加1,然后再次用1覆盖它。

您还应该使用数组来设置数组中的购买金额而不是单个变量。

ArrayList itemAmounts = new ArrayList();

...

itemAmounts.add(input.nextInt());

答案 2 :(得分:0)

您似乎正在使用非常非传统的方法,但最简单的解决方案是简单地使用整数数组:

int[] arr = new int[4];
int c = 0;
while (c <= 4) { // loop until 4 values have been given
    System.out.print("Enter the number of Item " + (c + 1) + " you would like to purchase: ");
    arr[c] = input.nextInt();
    c++;
}

打印c + 1使输出具有人类可读性,同时保持数组登录的零索引。我从循环条件中删除了x,因为它没有被使用。

答案 3 :(得分:0)

导入扫描仪并使用ArrayList。在循环中,使用YourList.Add(YourElement)将元素添加到ArrayList;

如果要使用变量,可以将值分配给变量,然后将其添加到列表中。您只需要将您的while循环硬编码为while&lt; 4