Is it possible to type:
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:
int number = scan.nextInt();
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(".");
}
}
}
}
Comment