简体   繁体   中英

Input (Scanner) variable in while loop

Im trying to make the program to ask for a percentage (grade) but I want it to ask again after the user has made the first input and has seen the output. I'm having trouble with the loop because the variable myMark is no assigned.

import java.util.Scanner;
public class passFail{


    public static void main(String[] args){

        Scanner result = new Scanner(System.in);
        int myMark = 0;

        while(myMark >=0 && myMark <=100){

            System.out.println("Please enter the percentage you have received:");
            myMark = result.nextInt();

            if(myMark <=49 && myMark >=0){

                System.out.println("You have failed!");
            }

            else if(myMark <=59 && myMark >=50){
                System.out.println("You have passed!");
            }

            else if(myMark <=69 && myMark >=60){
                System.out.println("You have received a Credit");
            }

            else if(myMark <=79 && myMark >=70){
                System.out.println("You have received a Distinction!");
            }

            else if(myMark <=100 && myMark >=80){
                System.out.println("You have received a High Distinction");
            }

            else{
                System.out.println("Please enter a whole number");
            }


        }

    }


}

You need to define myMark first before using it. Something like below:

  Scanner result = new Scanner(System.in); 
  int myMark = result.nextInt();

  while(myMark >=0 && myMark <= 100){

        System.out.println("Please enter the percentage you have received:");
        myMark = result.nextInt();
      ..................

- You have forgotten to declare the variable myMark .

- You have declare it to a Type (Data Type)

Eg:

int myMark;

- And it would be nicer if you place the Scanner outside the loop , cause you want to get the input only once...

You should declare your myMark before using it in while loop condition.. Also, you should declare your Scanner as instance variable..

public class Demo {
    private Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {

        int myMarks = 0;
        while (myMarks >= 0 && myMark < 100) {
            // Rest is all same
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM