while循环中的输入(Scanner)变量

时间:2012-10-08 04:58:50

标签: java

我试图让程序询问一个百分比(等级),但我希望它在用户进行第一次输入并看到输出后再次询问。我遇到循环问题,因为变量myMark没有分配。

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


        }

    }


}

3 个答案:

答案 0 :(得分:2)

在使用之前,您需要先定义myMark。如下所示:

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

答案 1 :(得分:1)

- 您忘记了declare变量myMark

- 您已将其声明为Type(数据类型)

<强>例如

int myMark;

- 如果您将Scanner 置于循环之外会更好,因为您只想获取输入一次......

答案 2 :(得分:1)

myMark循环条件下使用之前,您应该声明while。 另外,您应该将Scanner声明为实例变量..

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