Java。我的 class 来自用户的输入不是 return 到主程序

Java. My one class's input from user is not return to main program

Java。我的 class 来自用户的输入不是 return 到主程序

for user1.guess1's value here other class is returning only 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();
  }
}

这个:

int guess1 = in.nextInt();

是局部变量,不是实例变量,去掉int就可以了。

这是你的 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();
    }
}

创建新用户时,实例变量默认分配 0。然后你读入一个局部变量,它在你的 guess() 方法结束时被丢弃。所以你在 main 方法中得到了一个 0