当子类在超类中执行时,方法在子类中无法正常工作?

时间:2014-10-31 06:06:36

标签: java inheritance

我做了一个数字猜测程序,我试图将它输入到一个子类中。数字猜测程序在它自己的类中是成功的但是当我运行它不是最初的类时,那么由于某种原因,随机生成相同的数字(0)?这是超类代码:

import java.util.*;

public class GuessTheNumber {

    static int randomNum;
    static int guess;

    public static void main(String [] args) {
        random();
        do {
            guess();
        }
        while (guess != randomNum);

    }

    public static void random() {
        // Math.Random() - 1s and 0s
        randomNum = (int) (Math.random() * 11);
    }

    public static void guess() {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a guess: ");
        guess = input.nextInt();

        System.out.println("Your guess is " + guess + ".");
        if (guess == randomNum)
            System.out.println("Your guess is correct! Yay!");
        else if (guess < randomNum)
            System.out.println("Guess higher.");
        else if (guess > randomNum)
            System.out.println("Guess lower.");
    }

}

以下是随机生成器不起作用的子类的代码:

import java.util.*;

public class GuessTheNumber {

    static int randomNum;
    static int guess;

    public static void main(String [] args) {
        random();
        do {
            guess();
        }
        while (guess != randomNum);

    }

    public static void random() {
        // Math.Random() - 1s and 0s
        randomNum = (int) (Math.random() * 11);
    }

    public static void guess() {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a guess: ");
        guess = input.nextInt();

        System.out.println("Your guess is " + guess + ".");
        if (guess == randomNum)
            System.out.println("Your guess is correct! Yay!");
        else if (guess < randomNum)
            System.out.println("Guess higher.");
        else if (guess > randomNum)
            System.out.println("Guess lower.");
    }

}

我不确定我是否以某种方式将随机数生成器改为不再工作,或者是否因为我没有正确执行将超类'方法放入子类中。 (如果术语/语法有任何错误或者这个问题不清楚,我很抱歉。显然已经很晚了。谢谢。)

2 个答案:

答案 0 :(得分:0)

尝试使用rand.nextInt()代替randomNum = (int) (Math.random()。也就是说,

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1)*11

,应该可以正常工作。

答案 1 :(得分:-1)

我们必须在super class的帮助下调用子类中的超类方法,并且方法的sigiture也是一样的。