ConBon789 ConBon789 - 2 years ago 62
Java Question

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. The most recent is, when I was writing an averaging numbers program, where the user could enter as many numbers as they want, and the program would 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 the program could then get the average of all of the inputs. I decided on if the user enters an "=" sign, instead of a number, then it would break the loop, but, since the Scanner variable was looking for a double, and the "=" sign is a number, I would have to make it a string. But, obviously the Scanner is looking for a double, so i was getting an error. I need help. How can I get the program to exit the loop when the user types "="? I know i could just make a number break the loop, if it was entered, but if it was a real world program, and the user entered a number, it would average the numbers inputted before it, rather than including that number. The code 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.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*/

/*The if statement breaks the loop if a certain character is

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

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

answer = total / noOfInputs;


Answer Source

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.

} catch(InputMismatchException e){
  //check if  '=' ...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download