简体   繁体   中英

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

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

for user1.guess1's value here other class is returning only 0 instead of value entered by the user. need help here how I can get the original value entered by the user.

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

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.

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