Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class hasnextex
- {
- static Scanner kb = new Scanner(System.in);
- public static void main(String[] args)
- {
- // number entered and the running total
- int inputNum, sum = 0;
- // count of valid and invalid numbers seen
- int numValid = 0, numInvalid = 0;
- double average;
- System.out.print("Enter a positive value (EOF to quit): ");
- while ( kb.hasNext() )
- {
- inputNum = kb.nextInt();
- if (inputNum >= 0) //If the number inputted is greater than or equal to zero
- {
- sum = sum + inputNum; // add the number to the total running sum
- numValid = numValid + 1; //increase the number of valid numbers entered by one
- }
- else
- {
- System.out.println("The number " + inputNum + " is invalid."); //negative numbers are invalid, so alert the user
- numInvalid = numInvalid + 1; //increase the number of invalid numbers enterd by 1
- }
- System.out.print("Enter a positive value (EOF to quit): ");
- }
- average = sum / numValid; //divide the total sum of all the numbers entered by the total number of valid numbers entered
- System.out.println("There were " + numValid + " valid numbers entered");
- System.out.printf("The sum of the valid numbers was %d and the average was %.2f.%n", sum, average);
- //the %d is saying, "print the first int mentioned
- //after the quotes here". The %.2f is saying, "print the
- //first float value mentioned after the quotes here, but
- // only to the first 2 decimal points." The %n is saying nextline.
- System.out.println("There were " + numInvalid + " invalid numbers");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement