我正在为学校做一个项目,似乎无法找到这个错误的原因。我是编程和欣赏帮助的新手。提前谢谢。
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);
}
}
}
答案 0 :(得分: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
答案 1 :(得分: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;
}