Question

I'm new to java and this is also my first time asking a question here. I have to write a program using an array that will store input data. I'm trying to prompt for six values between 70 and 90. Right now it only lets me input three numbers and then the other three are zeros, but I can't figure out what to change to fix that. Here's what I have:

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();
Était-ce utile?

La solution

You are incrementing i twice in your loop.

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
}

Of course, it's also possible that you really want -

// 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.
}

Autres conseils

You're incrementing your loop index twice on each iteration

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];



  }

Remove the i++ statement inside of the for loop and it should work. Also, the if (i == 6) then break statement is unneccesary since the loop will terminate when the "i is less than values.length" condition is no longer true.

So your loop should be

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];
  }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top