java - 为什么我不能在 While 循环内返回?
问题描述
我正在我的程序中研究一个必须返回值 purchaseMethod 的方法。while 循环需要一直运行到控制台输入“Q”为止。我遇到的问题是我无法在 while 循环中返回。有没有办法解决?可能制作一个数组或for循环?如果 return 语句必须在 while 循环之外,我将如何将值保持为 purchaseAmount 的总计值。
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
推荐阅读
- java - 为什么 request.getParameter("") 使用 jquery formdata 返回 null
- php - 如何创建一个以 php 变量命名的 mysql 表?
- javascript - 使用 jquery 设置会话 - ajax,php 不起作用
- java - Java Grid Layout错误的按钮大小和错误的位置
- android - 如何在 Whatsapp 中将文本设置为描述(关于)?
- javascript - 如何在使用 JavaScript 加载页面后自动触发“ESC”键
- c# - 获取 IP 外部地址,并将其用于登录
- css - 创建编织图像列表
- mongodb - 在我的情况下,索引会提高读取性能吗?
- python - 计算字符串中的韩语字符