繁体   English   中英

无法从另一个类JAVA调用方法

[英]Can't call a method from another class JAVA

我正在做一个数字猜测程序。 生成一个随机数,然后用户尝试猜测它。 该程序将打印“太高”或“太低”,并让用户再次猜测。 我在将第一个猜测后的猜测输入到进行猜测的方法中时遇到问题。

这是我的课:

import java.util.Scanner;

public class Lab8
{
    public static void main (String [] args)
    {
        Scanner in = new Scanner(System.in);

        System.out.println("Enter a number: ");
        MyNumberGuess MyNumberGuess = new MyNumberGuess(in.nextInt());

        while (MyNumberGuess.tooLow() == true || MyNumberGuess.tooHigh() == true)
        {

            if (MyNumberGuess.tooHigh() == true)
            {
                System.out.println("Too high");
                System.out.println("Enter a number: ");
                MyNumberGuess.MyNumberGuess(in.nextInt());
            }
            else if (MyNumberGuess.tooLow() == true)
            {
                System.out.println("Too low");
                System.out.println("Enter a number: ");
                MyNumberGuess.MyNumberGuess(in.nextInt());
            }
        }

        System.out.println("Correct");
        System.out.println("You made " + MyNumberGuess.getNumGuesses() + " guesses");
    }
}

这是另一个类以及问题方法:

import java.util.*;

public class MyNumberGuess
{
    public static final int MAX_GUESS = 1000; 

    private int theNumber, numGuesses, prevGuess;

    public MyNumberGuess(int inGuess)
    {
       Random generator = new Random(); 
       numGuesses = 1;
       prevGuess = inGuess;
       theNumber = generator.nextInt(MAX_GUESS);
    }
}

照原样,在此行的第一个类中进行编译时,出现“找不到符号”错误:

MyNumberGuess.MyNumberGuess(in.nextInt());

我尝试以不同的方式调用它,而不使用参数,并尝试仅调用变量,以为它们应该是私有的。 任何帮助表示赞赏。

您以前使用过

MyNumberGuess MyNumberGuess = new MyNumberGuess(in.nextInt());

创建您的类的实例。 那你为什么要用

MyNumberGuess.MyNumberGuess(in.nextInt());

做同样的事情?

这个

public MyNumberGuess(int inGuess)
{
   Random generator = new Random(); 
   numGuesses = 1;
   prevGuess = inGuess;
   theNumber = generator.nextInt(MAX_GUESS);
}

是一个构造函数。 您需要使用new运算符调用它。

只需重新初始化变量

MyNumberGuess = new MyNumberGuess(in.nextInt());

请注意,java约定指出变量的名称应以小写字母开头。


另外一点,这段代码

  while (MyNumberGuess.tooLow() == true || MyNumberGuess.tooHigh() == true)

是多余的。 调用MyNumberGuess.tooLow()的方法已经返回了truefalse值,那么为什么将它与== true进行比较? 只需直接使用即可。 例如

if (MyNumberGuess.tooLow()) // read it as "If my number guess is too low"

要么

if (!MyNumberGuess.tooLow()) // read it as "If my number guess is not too low"

适当地使用while

不要使用确切的类名作为变量名

MyNumberGuess MyNumberGuess = new MyNumberGuess(in.nextInt());

更换外壳

MyNumberGuess myNumberGuess = new MyNumberGuess(in.nextInt());

您缺少大括号,您有您的类定义,然后您有函数定义,但没有结尾分号。 而且您不应该对多个变量使用相同的名称。

我有一个奇怪的问题:无论我是不能访问我的一个类的公共方法的,无论它是静态的还是设置实例化它都是如此。 我最终删除了该类,并使用不同的名称创建了一个新类。 我一定一直在踩一个内置的类名。

暂无
暂无

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

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