Question

I wrote a simple program (pardon my not using try-catch for exceptions) to add numbers to a list and find their sum, average, max and min. I would like to include a code to check for blank. I tried to do that with hasNext(). However, when I run the program and enter some blanks, it does not it does not tell me "You did not enter a number" as I intended. At the moment, I blocked off the hasNext() part so the rest of the program can run smoothly. I am a new to Java and programming. I have checked related posts on this forum and cannot seem to find a solution.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class BigAndSmall {
    public static void main(String[] args) {
        ArrayList<Double> list = new ArrayList<>();

        Scanner sc = new Scanner(System.in);

        double input = 0;
        double max = 0;
        double min = 0;
        double sum = 0;

        do{ 
            System.out.println("Enter a number or 0 to quit: ");
            input = sc.nextDouble();
            list.add(input);

        /*  if (!sc.hasNextDouble()) {
                System.out.println("You did not enter a number");
            }
            */
        }while(input != 0.0);       

        if (input == 0.0) {
            for (int i = 0; i < list.size(); i++) {
                sum = sum + list.get(i);                
            }
        }

            double avg = sum/list.size();
            System.out.println("Sum: " + sum);
            Collections.sort(list);                  
            System.out.println("Largest: " + Collections.max(list));
            System.out.println("Average: " + avg);
            System.out.println("Smallest: " + list.get(0));

        }
    }
Was it helpful?

Solution

Try using BufferedReader for inputs.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
double d;
try {
    d = Double.parseDouble( br.readLine() );
    list.add( d );
} catch( NumberFormatException nfe ) {
    System.out.println( "You did not enter a number!" );
}

Put this code inside the loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top