【问题标题】:Java. My one class's input from user is not return to main program爪哇。我的一类用户输入没有返回到主程序
【发布时间】:2018-07-21 20:44:48
【问题描述】:

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

【问题讨论】:

    标签: java class compiler-errors instance-variables


    【解决方案1】:

    这个:

    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() 方法结束时被丢弃。所以你会在你的 main 方法中得到一个0

    【讨论】:

    • guess() 返回一个 int(即用户输入的值)会更有意义。那么根本不需要实例变量。您只需使用int a = user1.guess();
    • @FredK 绝对是,但他没有要求进行代码审查 :)
    • 非常感谢@Wow。我无法弄清楚我错过了什么,你的建议奏效了。如果您能向我解释或指导我与 Java 相关的主题,那就太好了。这样,我就可以提高我在该主题上的技能。
    猜你喜欢
    • 2015-05-08
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    • 1970-01-01
    • 2013-08-31
    相关资源
    最近更新 更多