Java 我不能在While循环中返回有什么原因吗?
我正在我的程序中处理一个方法,该方法必须返回值purchaseMethod。while循环需要运行,直到Q被输入控制台。我遇到的问题是,我无法在while循环中返回。这有什么办法吗?可能制作数组或for循环?如果return语句必须在while循环之外,那么如何将purchaseAmount的值保持为totalJava 我不能在While循环中返回有什么原因吗?,java,while-loop,Java,While Loop,我正在我的程序中处理一个方法,该方法必须返回值purchaseMethod。while循环需要运行,直到Q被输入控制台。我遇到的问题是,我无法在while循环中返回。这有什么办法吗?可能制作数组或for循环?如果return语句必须在while循环之外,那么如何将purchaseAmount的值保持为total public static int getShoppingList(){ Scanner input = new Scanner(System.in); int eigh
public static int getShoppingList(){
Scanner input = new Scanner(System.in);
int eight = 8;
int hat = 32;
int patch = 2;
int sword = 20;
int map = 100;
int shirt = 150;
int quanEight = 0;
int quanHat = 0;
int quanPatch = 0;
int quanSword = 0;
int quanMap = 0;
int quanShirt = 0;
int count = 0;
System.out.println("Enter Item Code, ? or Q: ");
String code = input.next();
// Convert input into character
char ch = code.charAt(0);
// Convert string into uppercase
ch = Character.toUpperCase(ch);
// Calculate total
while (count != 0){
int purchaseAmount = ( quanEight * eight) + ( quanHat * hat) + ( quanPatch * patch) + ( quanSword * sword) + ( quanShirt * shirt) + ( quanMap * map);
if (ch == '?'){
System.out.println("Valid Item codes are: 8 I H M S T.");
System.out.println("Q to quit.");
}
else if (ch == '8'){
quanEight ++;
}
else if (ch == 'I'){
quanHat++;
}
else if (ch == 'H'){
quanPatch++;
}
else if (ch == 'M'){
quanMap++;
}
else if (ch == 'S'){
quanSword++;
}
else if (ch == 'T'){
quanShirt++;
}
else if (ch == 'Q'){
count++;
System.out.println("Pirate Trading Post");
System.out.println(quanEight + " Genuine Piece Of Eight\n " + quanHat + " Pirate Hat\n " + quanPatch +
" Eye Patch\n " + quanSword + " Sword\n " + quanMap + " Treasure Map\n " + quanShirt + " T-Shirt\n ");
System.out.println("Total: " + purchaseAmount + " bits");
return purchaseAmount;
}
}
}
这是一个编译问题:
int count = 0;
while (count != 0){ // count **IS** 0, does not enter
// your stuff
}
// no return
如果使用return命令打算将purchaseAmount返回给getShoppingList方法的调用方,我建议您将return移到方法的末尾,并在其while中加一个分隔符,而不是purchaseAmount。像这样:
while (count != 0){
// your stuff
if (...) {
// ...
} else if (ch == 'Q'){
// ...
break;
}
}
return purchaseAmount;
从while循环内返回是完全正确的-但是问题是,您也不会在while循环外返回-非void方法始终必须返回一个值。