Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JAVA我的一个类的用户输入并没有返回到主程序_Java_Class_Compiler Errors_Instance Variables - Fatal编程技术网

JAVA我的一个类的用户输入并没有返回到主程序

JAVA我的一个类的用户输入并没有返回到主程序,java,class,compiler-errors,instance-variables,Java,Class,Compiler Errors,Instance Variables,爪哇。我的一个类的用户输入并没有返回到主程序 对于user1.guess1的值,这里其他类只返回0,而不是用户输入的值。 这里需要帮助我如何获得用户输入的原始值 class randtestdrive { public static void main(String[] args){ user user1 = new user(); user1.guess(); int a = user1.guess1 ; int b = 5; //fo

爪哇。我的一个类的用户输入并没有返回到主程序

对于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,它就会工作

这是您的用户类:


创建新用户时,默认情况下实例变量被指定为0。然后读入一个局部变量,该变量在猜测方法结束时被丢弃。因此,在main方法中得到一个0。

guess返回一个int(即用户输入的值)更有意义。那么就根本不需要实例变量了。您只需使用int a=user1.guess@FredK绝对同意,但他没有要求代码审查:非常感谢@Wow。我不知道我错过了什么,你的建议奏效了。如果您能在java中向我解释或指导与之相关的主题,那就太好了。这样,我就可以提高我在这个话题上的技巧。
int guess1 = in.nextInt();
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();
    }
}