ConorH99
ConorH99

Reputation: 25

Using ints/doubles and Strings in the same Scanner variable

So I'm new to java programming, coming from Python, and there's a few concepts that I can't quite understand.

I'm writing a program which allows the user to enter as many numbers as they want and the program should output the average of all of the numbers. I used a while loop to loop through the inputs by the user as many times as they wanted, but I needed a way of exiting the loop so that the program could proceed with calculating the average of all of the inputs. I decided that if the user enters an "=" sign instead of a number, then the program would break out of the loop, but since the Scanner variable was looking for a double, and the "=" sign is not a number, I would have to make it a String. But because the Scanner is looking for a double, the program threw an error when it encountered the "=".

How can I get the program to exit the loop when the user types "="? I know I could just allow the user to enter a number that breaks the loop, but if it was a real world program and the user entered a number, it would count that number along with the previous ones when calculating the average. The code I have so far is as follows:

import java.util.Scanner;
// imports the Scanner class

public class Average{
    public static void main(String[] args){
        double num, total = 0, noOfInputs = 0, answer;
        Scanner scanner = new Scanner(System.in);

        while(true){
            System.out.print("Enter number: ");
            //Prompts the user to enter a number

            num = scanner.nextDouble();
            /*Adds the number inputted to the "num" variable. This is the
            source of my problem*/

            if(num.equals("=")){
                break;}
            /*The if statement breaks the loop if a certain character is
            entered*/

            total = total + num;
            //Adds the number inputted to the sum of all previous inputs

            noOfInputs++;
            /*This will be divided by the sum of all of the numbers because
              Number of inputs = Number of numbers*/
        }

        answer = total / noOfInputs;
        System.out.print(answer);

        }
}

Upvotes: 0

Views: 433

Answers (1)

Athamas
Athamas

Reputation: 611

Several ways to do this.

You could read every number as a string, and then if it is a number, parse it to get the value.

Integer.parseInt(String s)

Or you could check what comes next and read accordingly:

while (scanner.hasNext()) {
                if (sc.hasNextInt()) {
                   int a = scanner.nextInt();
                } else if (scanner.hasNextLong()) {
                   //...
                }
}

Or you could just catch the InputMismatchException, and work from there.

try{
  ...
} catch(InputMismatchException e){
  //check if  '=' ...
}

Upvotes: 2

Related Questions