1

It is a Java beginner question. The program is not complicated, it just asks the user input grade and then finish it when the user input "y" , and then calculate max, min,average, and total.

My trouble is that I can't stop the loop when I type y. Thank you so much, if anyone can help me out. I have tried many approaches to figure that.

    do
       { 
        System.out.println("please go on");
        input = keyboard.next();                    
        grade = Integer.parseInt(input);
        InputTimes++;
        if (grade>Maxgrade)
        {   
            Maxgrade = grade;       
         }

        if(Mingrade>grade)
        {
            Mingrade= grade;            
        }

        if (input.equals("y"))
        {   
            GameOver = true;
            System.out.println("yyyyyyy");
            break;
        }   
        else 
        {
            GameOver = false;
            System.out.println("nnnnnn");   
        }   
        totalgradeNoF = grade+totalgradeNoF;

    }while(GameOver==false);
Redick
  • 13
  • 2

3 Answers3

0
Scanner keyboard = new Scanner(System.in);
int Maxgrade = 0, Mingrade = 0, InputTimes = 0, grade = 0, totalgradeNoF = 0;
boolean GameOver = false;
String input = "";
do {
    System.out.println("Please go on : ('y' to stop)");
    input = keyboard.nextLine();
    if (input.equals("y")) {
        GameOver = true;
    } else {
        grade = Integer.parseInt(input);
        InputTimes++;

        if (grade > Maxgrade) {
             Maxgrade = grade;
        }
        if (Mingrade > grade) {
             Mingrade = grade;
        }

        totalgradeNoF = grade + totalgradeNoF;
   }
} while (!GameOver);

Some things to change :

  • You need to check the "y" BEFORE and if it is not a "y" so you can cast to int
  • You don"t need to use breakso
  • You may use !GameoOver instead of GameOver==false
  • Don't need to set Gameover=false at each iteration, just at the initialisation
Kaushal28
  • 4,823
  • 4
  • 30
  • 57
azro
  • 35,213
  • 7
  • 25
  • 55
  • appreciate it, in the beginning, I thought java can automatically ignore my input which is not number. Thank you so much ! – Redick Jul 02 '17 at 20:49
0

When you enter 'y' NumberFormatException is coming, so you need to handle this exception and then you can exit from the loop after typing 'y'.

Mohit Tyagi
  • 2,594
  • 3
  • 14
  • 29
0

Use for Scanner methods nextInt() and nextLine() for reading input.

EX:-

Scanner scan = new Scanner(System.in);

then we can use scan.nextInt() for get int

and we can use scan.nextLine() for get Strings

https://www.tutorialspoint.com/java/util/scanner_next.htm
this link may be help for you.

sorry for my english.

Supun Perera
  • 89
  • 1
  • 10