我是java的新手,这也是我第一次在这里提出问题。 我必须使用存储输入数据的数组编写程序。 我正在尝试提示输入70到90之间的六个值。现在,它只允许我输入三个数字,然后其他三个为零,但是我不知道要更改什么来解决该问题。 这是我所拥有的:

Scanner scanner = new Scanner(System.in);

int[] values = new int[6];
int i;
int sum = 0;
for (i = 0; i < values.length; i++) {
    System.out.print("Enter a number between 70 and 90: ");
    values[i] = scanner.nextInt();
    i++;
    if (i == 6) {
        break;

    }
    sum = sum + values[i];


}


double average = (sum / 6);
Arrays.sort(values);
System.out.println(Arrays.toString(values));
System.out.println("Average is " + average);
Arrays.sort(values);

int min = values[0];
System.out.println("Minimum is " + min);
System.out.println("Its index is " + Arrays.asList(values).indexOf(min));
int max = values[values.length - 1];
System.out.println("Maximum is " + max);
System.out.println("The difference between the largest and smallest elements is "
        + (max - min));

scanner.close();

===============>>#1 票数:4 已采纳

您在循环中将i递增两次。

for(i=0; i<values.length; i++){ // <-- this is a good place for it.
    System.out.print("Enter a number between 70 and 90: ");
    values[i] = scanner.nextInt();
    // i++; // only need one.
    // if(i == 6){
    //    break;
    // }
    sum += values[i]; // <-- you can use += too
}

当然,您也可能确实想要-

// This also declares i at more restricted scope.
for (int i=0; i < values.length; ) { // <-- remove i increment.
    System.out.print("Enter a number between 70 and 90: ");
    int value = scanner.nextInt();
    if (value < 70 || value > 90) {
        continue; // <-- will not increment i. 
                  // because I removed the increment in the for loop.
                  // also could have done --i, then continue;
    }
    values[i] = value;
    sum += value; // <-- you can use += too
    i++; // <-- after adding to the sum.
}

===============>>#2 票数:2

您在每次迭代中将循环索引增加两次

for(i=0; i<values.length; i++){
    System.out.print("Enter a number between 70 and 90: ");
    values[i] = scanner.nextInt();
    i++;
    if(i == 6){
        break;

    }
    sum = sum + values[i];



  }

在for循环中删除i ++语句,它应该可以工作。 另外,if(i == 6)then break语句不是必需的,因为当“ i小于values.length”的条件不再成立时,循环将终止。

所以你的循环应该是

for(i=0; i<values.length; i++){
    System.out.print("Enter a number between 70 and 90: ");
    values[i] = scanner.nextInt();
    sum = sum + values[i];
  }

  ask by noremacb translate from so

未解决问题?本站智能推荐: