Advertisement
Guest User

Untitled

a guest
Oct 21st, 2014
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. import java.util.*;
  2. public class hasnextex
  3. {
  4. static Scanner kb = new Scanner(System.in);
  5. public static void main(String[] args)
  6. {
  7.  
  8. // number entered and the running total
  9. int inputNum, sum = 0;
  10.  
  11. // count of valid and invalid numbers seen
  12. int numValid = 0, numInvalid = 0;
  13. double average;
  14.  
  15.  
  16. System.out.print("Enter a positive value (EOF to quit): ");
  17. while ( kb.hasNext() )
  18. {
  19. inputNum = kb.nextInt();
  20. if (inputNum >= 0) //If the number inputted is greater than or equal to zero
  21. {
  22. sum = sum + inputNum; // add the number to the total running sum
  23. numValid = numValid + 1; //increase the number of valid numbers entered by one
  24. }
  25. else
  26. {
  27. System.out.println("The number " + inputNum + " is invalid."); //negative numbers are invalid, so alert the user
  28. numInvalid = numInvalid + 1; //increase the number of invalid numbers enterd by 1
  29. }
  30. System.out.print("Enter a positive value (EOF to quit): ");
  31. }
  32.  
  33. average = sum / numValid; //divide the total sum of all the numbers entered by the total number of valid numbers entered
  34.  
  35. System.out.println("There were " + numValid + " valid numbers entered");
  36. System.out.printf("The sum of the valid numbers was %d and the average was %.2f.%n", sum, average);
  37. //the %d is saying, "print the first int mentioned
  38. //after the quotes here". The %.2f is saying, "print the
  39. //first float value mentioned after the quotes here, but
  40. // only to the first 2 decimal points." The %n is saying nextline.
  41. System.out.println("There were " + numInvalid + " invalid numbers");
  42. }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement