Kronos
Kronos

Reputation: 13

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");
            }


        }

    }


}

Upvotes: 0

Views: 4005

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213223

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
        }
    }
}

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

- 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...

Upvotes: 1

kosa
kosa

Reputation: 66637

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();
      ..................

Upvotes: 2

Related Questions