如何将已评估的扫描对象添加到数组中?

时间:2014-07-21 02:29:00

标签: java arrays variables

我想从用户扫描20个整数。用户输入负值后,扫描将停止。

之后,如何添加用户输入数组的正值?

System.out.println("\nEnter up to 20 non-negative numbers:");

for(i = 0; i <= list20.length; i++) {
    System.out.print("Number " + (i+1) + ": ");
    input = scan.nextInt();

    if(input > 0) { 
        input = input.list20[i] // How to add positive integer here??
    }
    else
    break;
}

1 个答案:

答案 0 :(得分:0)

// first, zero out the array using whatever method you want
for(i = 0; i < list20.length; i++)
{
    list20[i] = 0;
}

// then request the values
System.out.println("\nEnter up to 20 non-negative numbers:");
for(i = 0; i < list20.length; i++)
{
    System.out.print("Number "+ (i+1) + ": ");
    input = scan.nextInt();

    if(input>=0)
    { 
        list20[i] = input;
    }
    else
    {
        break;
    }
}

// then total the non-negative values
int total = 0;
if(i >= 20) {
    for(int value : list20)
    {
        if(value > 0) {
            total += value;
        }
    }
}