我需要让变量orderNum为每个订单号增加1.现在这是在一个switch语句中我尝试了一个for循环和orderNum ++但是happing是什么,orderNum只给我1个每个语句。所以我不确定我在哪里出错了我已经搜索了网但却找不到答案。
感谢您的帮助
public class orders extends javax.swing.JFrame{
private char productName;
private char productCode;
private double price;
private double discount;
private int quantity;
private double total;
private String message;
private int orderNum;
private final double MAXORDER = 1000;
private final double MINORDER = 0.1;
orders(char productCode, int quantity) {
this.productCode = productCode;
this.quantity = quantity;
}
public String calculate() {
double price = 0;
//int i = 0;
String productName= " ";
boolean isDiscounted = false;
boolean isValidOrder = true;
if (quantity > MAXORDER){
message = "**ERROR** Invalid quantity. Quantity cannot be greater than 1000";
isValidOrder = false;
}
else if (quantity < MINORDER){
message = "**ERROR** Invalid quantity. Quantity cannot be 0 or less ";
isValidOrder = false;
}
if (isValidOrder) {
int orderNum =0;
// while (i<100){
switch (productCode) {
case 'A':
orderNum+=1;
productName = "Pencil";
price = quantity * 0.60;
break;
case 'b':
orderNum+=1;
productName = "Rubber";
price = quantity * 0.90;
break;
case 'c':
orderNum+=1;
productName = "Meat";
price = quantity * 100.00;
break;
default:
isValidOrder = false;
message = "Not this time";
break;
}
if(isValidOrder){
message = "Order Number: " + orderNum + "\n" + "You are buying " + productName + "\n" + "The quantity of: " + quantity + "\n" + "For the price of $" + price;
System.out.println("Tom is : " + orderNum);
}
}
// }
return message;
}
}
答案 0 :(得分:2)
您刚刚将orderNum
声明为0,我认为您希望将其作为班级成员。另外,我建议使用++
而不是+= 1
。像
private static int orderNum = 0;
public String calculate() {
double price = 0;
// int i = 0;
String productName = " ";
boolean isDiscounted = false;
boolean isValidOrder = true;
if (quantity > MAXORDER) {
message = "**ERROR** Invalid quantity. Quantity cannot be greater than 1000";
isValidOrder = false;
} else if (quantity < MINORDER) {
message = "**ERROR** Invalid quantity. Quantity cannot be 0 or less ";
isValidOrder = false;
}
if (isValidOrder) {
// while (i<100){
switch (productCode) {
case 'A':
orderNum++;
productName = "Pencil";
price = quantity * 0.60;
break;
case 'b':
orderNum++;
productName = "Rubber";
price = quantity * 0.90;
break;
case 'c':
orderNum++;
productName = "Meat";
price = quantity * 100.00;
break;
default:
isValidOrder = false;
message = "Not this time";
break;
}
if (isValidOrder) {
message = "Order Number: " + orderNum + "\n"
+ "You are buying " + productName + "\n"
+ "The quantity of: " + quantity + "\n"
+ "For the price of $" + price;
System.out.println("Tom is : " + orderNum);
}
}
// }
return message;
}
答案 1 :(得分:1)
您正在定义两个orderNum
变量:类成员字段和方法内的局部变量。对于每个方法调用,局部变量将始终初始化为零,因此您需要将其删除以增加字段变量。
答案 2 :(得分:1)
你有shadowed orderNum变量,在if(isValidOrder)
之后声明它,删除它,一切都应该没问题