Double and Int

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kid Programmer
    New Member
    • Mar 2008
    • 176

    Double and Int

    Is it possible to type:
    Code:
    int number = scan.nextInt();
    and not get an error if the user enters 0.0? I am trying to write a program that will average numbers until the user enters text. I want the user to be able to enter decimals as well. Here is my source:
    Code:
    import java.util.Scanner;		//import a scanner
    
    public class NumberAverager {	//create a class
    	
    	public static void main(String[] args) {		//start the main function
    		int divideby = 0, number = 0, sum = 0, average = 0;			//declare variables
    		Scanner scan = new Scanner(System.in);			//create the scanner
    		//explain the program
    		System.out.println("This program will average WHOLE numbers.");
    		System.out.println("To stop averaging numbers enter anything that is not a whole number.");
    		System.out.println("Please enter the numbers: ");
    		//create a loop to execute as long as the user enters numbers
    		while ( scan.hasNextInt() ) {
    			number = scan.nextInt();		//prompt the user for numbers
    			sum = sum + number;				//add up the numbers
    			divideby ++;					//increase the amount to divide the numbers by
    			if ( scan.hasNextInt() == false) {		//if the user doesn't enter a whole number
    				average = sum / divideby;			//calculate the average
    				//print the average
    				System.out.print("The total average of the numbers is ");
    				System.out.print(average);
    				System.out.println(".");
    			}
    		}
    	}
    }
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    No, that's a double literal. Use the Scanner's hasNext*Type* methods to determine what type the input is or parse the input as a String (scanner's next() method) and use a bunch of nested try/catch blocks to attempt different types.

    As a general rule, though, just pick one of doubles or ints and use it for something like this. Any int can be represented as a double, so if you want to enable decimals, just use doubles exclusively.

    Comment

    • BigDaddyLH
      Recognized Expert Top Contributor
      • Dec 2007
      • 1216

      #3
      Originally posted by Laharl
      As a general rule, though, just pick one of doubles or ints and use it for something like this. Any int can be represented as a double, so if you want to enable decimals, just use doubles exclusively.
      I agree. If the user can enter a sequence like:

      2 3 5 8 13 23.3 36.6

      There is no benefit in reading some of them as ints and others as doubles. Read them all in as doubles.

      Comment

      • Kid Programmer
        New Member
        • Mar 2008
        • 176

        #4
        Thank you I understand :-)

        Comment

        Working...