重复的局部变量n

时间:2014-10-18 06:07:39

标签: java

我一直在尝试解决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!");
            }

        }
    }

2 个答案:

答案 0 :(得分:2)

您的n方法签名中的参数number和mothod中定义的变量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

答案 1 :(得分:0)

不允许在同一范围内声明多个具有相同名称的变量。在您的代码中,您声明了一个名为' n'的变量。在名为number的方法中两次。由于这两个变量属于相同的方法范围,因此当您尝试引用变量时,编译器无法决定您引用的变量' n'。

请注意,只要它们位于不同的范围内,就可以声明多个具有相同名称的变量。例如,允许以下内容......

public class VariableScope {
    int scopedVar = 10; // First declaration
    public static void main(String[] args) {
            int scopedVar = 200; // Second declaration. 
                                 // This is perfectly valid. But it overrides the first declaration.

    }
}