dimanche 22 juillet 2018

Order in while loop when using hasNextInt statement

I'm just starting out with java. I'm trying to write a code that adds numbers to an ArrayList using user input. I found a way to run a while loop that stops when I input anything but a number, using a 'hasNextInt' statement, but for some reason it goes straight for the input and only then prints out the message from the first if statement. What am I doing wrong?

Output looks like this:

This program takes grades from 1 to 100 You may begin typing numbers now To stop setting grades, type any word (like 'done') Enter the 1st number: 68 54 Enter the 2nd number 94 Enter the 3rd number

This is the code I wrote:

public static void main(String args[]){
  Scanner input = new Scanner(System.in);
  ArrayList<Integer> myClassroom = new ArrayList<Integer>();
  GradeAnalyzer myAnalyzer = new GradeAnalyzer();
  System.out.println("This program takes grades from 1 to 100");
  System.out.println("You may begin typing numbers now");
  System.out.println("To stop setting grades, type any word (like 'done') ");
  int counter = 1;
  System.out.println("Enter the 1st number:");
  while(input.hasNextInt()) {
      if(counter == 21 || counter == 31 || counter == 41 || counter == 51 || counter == 61) {
          System.out.println("Enter the " + counter + "st" + " number");
      }else if(counter == 2 ||counter == 22 ||counter == 32 ||counter == 42 ||counter == 52 ||counter == 62) {
          System.out.println("Enter the " + counter + "nd" + " number");
      }else if(counter == 3 ||counter == 23 ||counter == 33 ||counter == 43 ||counter == 53 ||counter == 63){
          System.out.println("Enter the " + counter + "rd" + " number");
      }else if(counter == 1) {
          System.out.print("");
      }else {
          System.out.println("Enter the " + counter + "th" + " number");
      }
      int cijfer = input.nextInt();
      if(cijfer < 0 || cijfer > 100) {
          System.out.println("Please enter a number between 1 and 100.");
      }else {
          myClassroom.add(cijfer);
          counter++;
      }
  }  
  System.out.println("You entered " + counter + " valid numbers.");

Aucun commentaire:

Enregistrer un commentaire