我一直在尝试解决Java中的问题,并尝试寻找答案。
除了可能已经声明了两次变量,我什么都找不到,我什么也看不到。

我正在尝试获取用户输入的整数“ n”作为瓶子的起始数量。
请帮助并告诉我如何更改和解决此问题。

这是我的代码部分:

public class BottlesOfBeer {

    private static Scanner bottles;
    public static void number(int n) {
        bottles = new Scanner(System. in );
        bottles.useDelimiter("\n");

        System.out.println("Enter the starting number of " + "bottles in the song " + "'99 Bottles of Beer on the Wall':");
        int n = bottles.nextInt();

        if (n > 1) {
            System.out.print(n + " bottles of beer on the wall, " + n + " bottles of beer, ya' take one down, " +
                "ya' pass it around, ");
            n = n - 1;
            System.out.println(n + " bottles of beer on the wall.");
            number(n);
        } else {

            if (n == 1) {
                System.out.print(n + " bottle of beer on the wall, " + n + " bottle of beer, ya' take one down, " +
                    "ya' pass it around, ");
                n = n - 1;
                System.out.println(n + " bottles of beer on the wall.");
                number(n);
            } else {
                System.out.println("No more bottles of beer on the wall, " +
                    "no bottles of beer, ya' can't take one down, " + "ya' can't pass it around, 'cause there are" + " no more bottles of beer on the wall!");
            }

        }
    }

最佳答案

您在n方法的签名中同时包含参数number和在方法内部定义的变量n。由于编译器无法区分两者,因此您必须重命名其中之一。

public static void number(int n) { // first n
    bottles = new Scanner(System.in);
    bottles.useDelimiter("\n");

        System.out.println("Enter the starting number of "
                + "bottles in the song "
                + "'99 Bottles of Beer on the Wall':");
        int n = bottles.nextInt(); // second n

10-07 16:35
查看更多