繁体   English   中英

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

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

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

这个:

int guess1 = in.nextInt();

是局部变量,而不是实例变量,请删除int ,它将起作用。

这是您的user类别:

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()方法的末尾被丢弃。 因此,您的主方法得到0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM