简体   繁体   中英

Removing all the zeros from an array using scanner

I needed an array that takes integers from a user until '0' is entered; then it prints average, max and min. I wrote an array with 700 elements and it breaks. When I input 0 everything works well. The problem is when I input 0 it takes 0 as an element. I solved that somehow so it can calculate the average correctly but it still takes some 0 from somewhere. For example, I input 8 and then 3 and then 0, and the output is the average is 4.000000, the biggest one is 5, the smallest one is 0, but the smallest one should be 3. I guess it's because the remaining 697 elements are considered as 0.

I found a lot of answers for this problem but I want to solve it without copying the array or creating a new one. Is there anything that I can do to fix this without adding an array or another for loop or something? Like a line that means 'when the 0 is entered remove all remaining elements and don't use them for anything'?

import java.util.Scanner;
import java.util.stream.IntStream;
public class PlayingWithNumbers2 {
    private static Scanner input;

    public static void main(String[] args) {
        input = new Scanner(System.in);
        int[] array = new int[700];
        System.out.println("Enter numbers enter 0 to end");
        int i;
        int max = array[0];
        int min = array[0];
        int a = array[0];
        for (i = 0; i < array.length; i++) {    
            a=input.nextInt();
            if(a==0){
                break;
            }
            array[i] = a;
            if(array[i]>max)
                max = array[i];
            else if(array[i]<min)
                min = array[i];
        }
        double sum = IntStream.of(array).sum();
        double Ave = sum/i;
        System.out.printf(" The Average is %f \n the biggest one is %d \n the smallest one is %d", Ave, max, min);`
    }
}

You can use range() :

double sum = IntStream.of(array).range(0, i).sum();
double Ave = sum/(i-1);

In this way, you'll be counting only numbers that are truly entered by the user and leave 'fake' 0 out of your sum.

The problem with the min/max is both are initialized to array[0] which means both are initialized to '0' and so the min check will always keep it at 0 as it is below anything you enter. You also need to remove the else condition. Try this

    int max = Integer.MIN_VALUE;
    int min = Integer.MAX_VALUE;

then inside the loop change the checks to be

   if(array[i]>max)
     max = array[i];

   if(array[i]<min)
     min = array[i];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM