Java。我的一堂课的用户输入没有返回主程序

时间:2018-07-21 20:44:48

标签: java class compiler-errors instance-variables

Java。我的一堂课的用户输入不返回主程序

对于user1.guess1的值,此处其他类仅返回0,而不是用户输入的值。 在这里需要帮助,如何获取用户输入的原始值。

class randtestdrive
{ 
  public static void main(String[] args){    
    user user1 = new user();
    user1.guess();

    int a = user1.guess1 ;
    int b = 5;

    //for user1.guess1's value here other class is returing only 0 instead of value entered by the user.
    // need help here how I can get the orignal value entered by the user.
    System.out.println(user1.guess1+" test A's value");

    if (a==b)
      System.out.println("Hit");
    else if(user1.guess1 != b)
      System.out.println("Missed!"); 
  }
}
class user
{ 
  Scanner in = new Scanner(System.in);  
  int guess1;
  void guess()
  {
    System.out.println("Guess the random number in 1-10");
    int guess1 = in.nextInt();
  }
}

1 个答案:

答案 0 :(得分:1)

This:

int guess1 = in.nextInt();

is a local variable, not an instance variable, remove the int, and it will work.

This is your user class:

class user {
    Scanner in = new Scanner(System.in);
    int guess1;

    void guess() {
        System.out.println("Guess the random number in 1-10");
        int guess1 = in.nextInt();
    }
}

When you create a new user, the instance variable is assigned 0 by default. And then you read into a local variable, which is discarded at the end of your guess() method. So you get a 0 in your main method.