在方法 checker() 和 runFirst 之间,变量“running”和“productChoice”被重置,我不知道为什么。我尝试过如何声明 RetailSalesProgram,但似乎没有任何效果。我只需要知道如何使变量不重置。
import javax.swing.JOptionPane;
public class RetailSalesProgram
{
private String customerName = "Default";
private int customerChoice;
private boolean running;
private double productChoice, a, b, c ,d ,e, total;
// sets values
public RetailSalesProgram()
{
running = true;
a= 2.98;
b= 4.50;
c= 9.98;
d= 3.15;
e= 2.29;
}
/ takes the methods and puts them into main
public void runFirst()
{
RetailSalesProgram rsp = new RetailSalesProgram();
rsp.greet();
do
{
rsp.shop();
rsp.checker();
rsp.totaling();
System.out.println(running);
System.out.println(total);
}
while (running == true);
}
//the initial greeting before they shop
private void greet()
{
customerName = JOptionPane.showInputDialog(null, " Welcome to my store!\n Please enter your name");
JOptionPane.showMessageDialog(null, "Hello " + customerName + "!");
}
//this is the menu for the shop
private void shop()
{
customerChoice = Integer.parseInt(JOptionPane.showInputDialog(null, " 1. Can of beans $2.98\n2. Calculator $4.50\n3. Yoga mat $9.98\n4. Bottle of Gatorade $$3.15\n5. Birthday card $2.29\n6. Exit program"));
while (customerChoice < 1 || customerChoice > 6)
{
JOptionPane.showMessageDialog(null, "That was not a valid entry");
customerChoice = Integer.parseInt(JOptionPane.showInputDialog(null, " 1. Can of beans $2.98\n2. Calculator $4.50\n3. Yoga mat $9.98\n4. Bottle of Gatorade $$3.15\n5. Birthday card $2.29\n6. Exit program"));
}
System.out.println(customerChoice);
}
// This is where im having problems. It is suppose to change the instance variables.
private void checker()
{
switch (customerChoice)
{
case 1:
productChoice = a;
break;
case 2:
productChoice = b;
break;
case 3:
productChoice = c;
break;
case 4:
productChoice = d;
break;
case 5:
productChoice = e;
break;
case 6:
running = false;
break;
}
System.out.println(total);
System.out.println(running);
}
// This just takes a total of the product.
private void totaling()
{
productChoice += total;
}
//////////////////////////////////////////////////////////////////////////
// will run everything for runFirst()
public static void main(String[]args)
{
RetailSalesProgram rsp = new RetailSalesProgram();
rsp.runFirst();
}
}