0

我正在为学校做一个项目,似乎找不到这个错误的原因。我对编程非常陌生,感谢您的帮助。先感谢您。

import java.util.Scanner;
 public class Lemonade {

public static void main(String[] args) {
    Scanner user = new Scanner(System.in);
    int lemons_per_pitcher = 12;
    int spoons_per_bag = 1000;
    int spoons_per_pitcher = 50;
    System.out.println("Enter the amount of lemons you have.");
    int lemon = user.nextInt();
    System.out.println("Enter the amount of bags of sugar you have.");
    int bags = user.nextInt();
    int spoons = bags * 1000;
    int sugar = spoons / 50;
    int lemons2 = lemon / 12;
    if( lemons2 > sugar){
        int pitcher = lemons2;
    }else{
        int pitcher = sugar;
    }
    if( lemon < 12 || bags < 1){
        System.out.println("You can make a maximum of 0 pitchers");
    } else{
        System.out.println("This is the maximum amount of pitchers you can         make is: " + pitcher);
    }
}

}

4

2 回答 2

3

pitcher是一个本地值,因此您可以在 main 方法中定义它。

尝试这个:

public static void main(String[] args) {
        int pitcher;
        Scanner user = new Scanner(System.in);
        int lemons_per_pitcher = 12;
        int spoons_per_bag = 1000;
        int spoons_per_pitcher = 50;
        System.out.println("Enter the amount of lemons you have.");
        int lemon = user.nextInt();
        System.out.println("Enter the amount of bags of sugar you have.");
        int bags = user.nextInt();
        int spoons = bags * 1000;
        int sugar = spoons / 50;
        int lemons2 = lemon / 12;
        if (lemons2 > sugar) {
            pitcher = lemons2;
        } else {
            pitcher = sugar;
        }
        if (lemon < 12 || bags < 1) {
            System.out.println("You can make a maximum of 0 pitchers");
        } else {
            System.out
                    .println("This is the maximum amount of pitchers you can         make is: "
                            + pitcher);
        }
    }

您只能在定义变量的块中使用变量。

例如:

{
    int i = 0;
}
i++; // ERROR : There no i in this block

在你的代码中:

if( lemons2 > sugar){
    int pitcher = lemons2;
}else{
    int pitcher = sugar;
} // pitcher no more exists after block
于 2013-08-15T22:11:10.970 回答
1

问题在于这些条件:

if( lemons2 > sugar){
    int pitcher = lemons2;
}else{
    int pitcher = sugar;
}

当您声明投手时,您将其范围限制为仅在直接括号内。这意味着您可以使用变量投手的唯一地方是:

if( lemons2 > sugar){
    int pitcher = lemons2; //Here
}else{
    int pitcher = sugar; //And here
}

在其他任何地方调用它都会给你一个错误。

你应该做的是在第一个条件上方声明投手:

int pitcher = 0;
if( lemons2 > sugar){
    pitcher = lemons2;
}else{
    pitcher = sugar;
}
于 2013-08-15T22:20:51.437 回答