Java 自动售货机,计算时未识别输入变量
我已经创建了一个自动售货机驱动程序和类。它以前确实工作过,但我尝试做了一个do while循环,试图对第一个菜单屏幕(InsertMoney)进行一些验证。一周后,当我回来决定删除该位时,它还没有恢复到以前的工作状态 对于SelectItem,这只引用了InsertMoney方法,从那里它可以完美地工作 基本上,当你按“i”键插入钱时,无论你插入什么(paymentSum),都不会进行计算,无论你输入什么,它只会给出乘积,所有更改都设置为0。我试图修复它,但我已经到了一个阶段,在这个阶段,我不能为细节而烦恼,我只想让paymentSum在计算中发挥作用。如果我在任何一种方法的任何阶段对paymentSum进行JOptionPane输出,它确实会显示插入的钱,但我不知道为什么它不使用它进行计算 我只做了一个学期的编程,所以我想我的代码远没有得到优化,但我似乎找不到问题所在,我的大脑也变得模糊了,所以我想知道是否有人可以帮忙 驱动程序Java 自动售货机,计算时未识别输入变量,java,methods,constructor,global-variables,do-while,Java,Methods,Constructor,Global Variables,Do While,我已经创建了一个自动售货机驱动程序和类。它以前确实工作过,但我尝试做了一个do while循环,试图对第一个菜单屏幕(InsertMoney)进行一些验证。一周后,当我回来决定删除该位时,它还没有恢复到以前的工作状态 对于SelectItem,这只引用了InsertMoney方法,从那里它可以完美地工作 基本上,当你按“i”键插入钱时,无论你插入什么(paymentSum),都不会进行计算,无论你输入什么,它只会给出乘积,所有更改都设置为0。我试图修复它,但我已经到了一个阶段,在这个阶段,我不能
import javax.swing.JOptionPane; // Library for dialog boxes
public class VendingMachineDriver // Start of VendingMachineDriver class with main method
{
public static void main (String [] args) {
// Creating an object of VendingMachine class
VendingMachine objVendingMachine = new VendingMachine();
// Start of program repeat loop with constructors from VendingMachine class
do
{
objVendingMachine.InsertMoney();
objVendingMachine.SelectItem();
objVendingMachine.NotEnoughMoney();
objVendingMachine.GiveChange();
objVendingMachine.Repeat();
} // End of main method do loop
// Condition for ending program loop
while (objVendingMachine.again == JOptionPane.YES_NO_OPTION);
System.exit(0);
}
} // End of VendingMachineDriver class
自动售货机类
import javax.swing.JOptionPane; // Importing library for dialog boxes
import java.text.DecimalFormat; // Importing library for decimal number formatting
public class VendingMachine // Start of VendingMachine class with constructors
{
String spaymentSum; // Money inserted by user for parsing into Integer value
String productName; // Name of product
int paymentSum; // Money inserted by customer parsed into Integer value as pence
int coke, pepsi, sevenUp, mars, snickers, twix; // variables for products sold
int price; // Value holding the price of product selected
int changeLeft; // Change left from inserted money after selection
int again; // variable for descerning program repeat
DecimalFormat pence = new DecimalFormat("#p"); // Format display output for pence
/**
* SelectionMenu constructor to display welcome message, money insertion and select item options.
*/
public void InsertMoney()
{
String soption; // Variable for machine operation
boolean correctOption = false; // boolean variable for confirming input validation with default value
paymentSum = 0; // Intialising inserted money variable paymentSum
do // Start of loop valid option selection loop
{
// Vending machine welcome dialog
soption = JOptionPane.showInputDialog(
"============================================"
+ "\nWelcome to the College Vending Machine!"
+ "\n============================================"
+ "\n\nOptions: i for insert money, s for select item, q for quit."
+ "\n\n============================================");
// input validation for only i, s or q user input
if (soption.matches("isq"))
{
JOptionPane.showMessageDialog(null, "Invalid input! Please try again.");
}
// start of switch condition to catch specific characters (i, s and q) for machine operation
switch (soption)
{
case "q": // user chooses q to quit
JOptionPane.showMessageDialog(null, "Have a Nice Day!");
System.exit(0); // terminate application
break;
case "i": // if user chooses i: insert money;
do
{
spaymentSum = JOptionPane.showInputDialog(
"============================="
+ "\nPlease enter some money (in pence)"
+ "\n============================="); // Inserting money
// Validation against string and decimal numbers
if (spaymentSum.matches("[a-zA-Z]+(\\.[0-9]+)?$")) // Validation against string
{
JOptionPane.showMessageDialog(null,"Must be a positive number! Try again.");
spaymentSum = null;
}
else
{
paymentSum = Integer.parseInt(spaymentSum); // Parsing for calculations
if (paymentSum <= 0) // Validation against negative numbers
JOptionPane.showMessageDialog(null,"Must be a positive number! Try again.");
}
}
while (paymentSum <=0);
correctOption = true;
break;
case "s": // if user chooses s: select item
correctOption = true;
break;
default:
correctOption = false;
JOptionPane.showMessageDialog(null, "Incorrect choice entered. Try again.");
break;
}
}
while (correctOption != true);
}
/**
* Start of SelectItem constructor for selection of product
*/
public void SelectItem()
{
String sproductSelection; // Variable to detect which product is selected
productName = " Nothing"; // Default name of product when none is selected
coke = 60; // Price for Coke
pepsi = 75; // Price for Pepsi
sevenUp = 70; // Price for 7Up
mars = 65; // Price for Mars
snickers = 80; // Price for Snickers
twix = 55; // Price for Twix
// Product selection screen
sproductSelection = JOptionPane.showInputDialog(
"======================"
+ "\nCredit: " + pence.format(paymentSum)
+ "\n======================"
+ "\nWhat would you like to buy?"
+ "\n\n========"
+ "\nDRINKS"
+ "\n========"
+ "\nC = Coke: " + pence.format(coke) // Drinks
+ "\nP = Pepsi: " + pence.format(pepsi)
+ "\n7 = 7UP: " + pence.format(sevenUp)
+ "\n========"
+ "\nCHOCOLATES"
+ "\n========"
+ "\nM = Mars: " + pence.format(mars) // Chocolates
+ "\nS = Snickers: " + pence.format(snickers)
+ "\nT = Twix: " + pence.format(twix)
+ "\n======================"
+ "\n\n");
do // Start of do loop to ensure valid product selection
{
// Start of validation loop to repeat if sproductSelection = null (as in incorrect value entered)
if (null != sproductSelection)
// Using switch to capture input by user to match selected products
switch (sproductSelection)
{
case "C":
price = coke;
productName = "Coke";
break;
case "P":
price = pepsi;
productName = "Pepsi";
break;
case "7":
price = sevenUp;
productName = "7UP";
break;
case "M":
price = mars;
productName = "Mars";
break;
case "S":
price = snickers;
productName = "Snickers";
break;
case "T":
price = twix;
productName = "Twix";
break;
default: // If invalid options in case are selected
productName = null;
JOptionPane.showMessageDialog(null, "Incorrect choice entered. Try again.");
sproductSelection = JOptionPane.showInputDialog(
"======================"
+ "\nCredit: " + pence.format(paymentSum)
+ "\n======================"
+ "\nWhat would you like to buy?"
+ "\n\n========"
+ "\nDRINKS"
+ "\n========"
+ "\nC = Coke: " + pence.format(coke) // Drinks
+ "\nP = Pepsi: " + pence.format(pepsi)
+ "\n7 = 7UP: " + pence.format(sevenUp)
+ "\n========"
+ "\nCHOCOLATES"
+ "\n========"
+ "\nM = Mars: " + pence.format(mars) // Chocolates
+ "\nS = Snickers: " + pence.format(snickers)
+ "\nT = Twix: " + pence.format(twix)
+ "\n======================"
+ "\n\n");
}
}
while (productName == null); // End of validation loop when product selection is valid
} // End of class SelectItem
/**
* NotEnoughMoney method for when not enough money is inserted to purchase product
*/
public void NotEnoughMoney()
{
String spaymentSum2; // Money inserted by user for parsing into Integer value
int paymentSum2; // Money inserted by customer parsed into Integer value as pence
if (paymentSum == 0) // Continuing s: select item operation
{
spaymentSum = (JOptionPane.showInputDialog(
"======================================"
+ "\nTo buy " + productName
+ " you need to enter at least " + pence.format(price)
+ "\n======================================"
+ "\n\n")); // Inserting money
paymentSum = Integer.parseInt(spaymentSum); // Parsing for calculations
if (paymentSum < price) // If not enough money has been inserted
do // start of not enough money entered loop
{
spaymentSum2 = JOptionPane.showInputDialog(
"=========================================="
+ "\nYou have not entered enough to buy: "
+ productName + " at " + pence.format(price)
+ "\n\nBalance: " + pence.format(paymentSum)
+ "\nRemaining: " + pence.format((price-paymentSum))
+ "\n\nPlease insert more money (in pence) or q to quit: "
+ "\n=========================================="
+ "\n");
if ("q".equals(spaymentSum2)) // If user quits
{
JOptionPane.showMessageDialog(null,
"======================"
+ "\n" + pence.format(paymentSum)
+ " has been returned to you."
+ "\nThank you for your custom."
+ "\n======================");
System.exit(0);
}
else
{
paymentSum2 = Integer.parseInt(spaymentSum2); // Parsing additional funds added
paymentSum = paymentSum + paymentSum2; // new total including additional funds
}
}
while (paymentSum < price); // End of loop when enough money inserted
changeLeft = paymentSum - price; // Calculate change left after product purchase;
} // End of NotEnoughMoney method
}
/**
* GiveChange constructor to output change left after product purchase in various denominations
*/
public void GiveChange()
{
int fiver; //variable for £5 note
int £2pound; //variable for £2 coin
int £1pound; //variable for £1 coin
int p50; //variable for 50p coin
int p20; //variable for 20p coin
int p10; //variable for 10p coin
int p5; //variable for 5p coin
int p2; //variable for 2p coin
int p1; //variable for 1p coin
int changeCoins = changeLeft; // new variable used for calculating change in demoninations
// Calculating change for output in various denominations
fiver = changeCoins/500;
changeCoins = changeCoins%500;
if (fiver < 0)
fiver = 0;
£2pound = changeCoins/200;
changeCoins = changeCoins%200;
if (£2pound < 0)
£2pound = 0;
£1pound = changeCoins/100;
changeCoins = changeCoins%100;
if (£1pound < 0)
£1pound = 0;
p50 = changeCoins/50;
changeCoins = changeCoins%50;
if (p50 < 0)
p50 = 0;
p20 = changeCoins/20;
changeCoins = changeCoins%20;
if (p20 < 0)
p20 = 0;
p10 = changeCoins/10;
changeCoins = changeCoins%10;
if (p10 < 0)
p10 = 0;
p5 = changeCoins/5;
changeCoins = changeCoins%5;
if (p5 < 0)
p5 = 0;
p2 = changeCoins/2;
changeCoins = changeCoins%2;
if (p2 < 0)
p2 = 0;
p1 = changeCoins/1;
// Output screen for displaying the change in various denominations
JOptionPane.showMessageDialog(null,
"======================"
+ "\nYou have bought " + productName + " for " + pence.format(price)
+"\n\nYour change is: " + pence.format(changeLeft)
+ "\n\n£5 note(s): \t\t" + fiver //printing the number of £5 notes given as change
+ "\n£2 coin(s): \t\t" + £2pound //printing the number of £2 coins given as change
+ "\n£1 coin(s): \t\t" + £1pound //printing the number of £1 coins given as change
+ "\n50p coin(s): \t\t" + p50 //printing the number of 50p coins given as change
+ "\n20p coin(s): \t\t" + p20 //printing the number of 20p coins given as change
+ "\n10p coin(s): \t\t" + p10 //printing the number of 10p coins given as change
+ "\n5p coin(s): \t\t" + p5 //printing the number of 5p coins given as change
+ "\n2p coin(s): \t\t" + p2 //printing the number of 2p coins given as change
+ "\n1p coin: \t\t" + p1
+ "\n======================"); //printing the number of 1p coins given as change
} // End of GiveChange constructor
/**
* Repeat constructor used to ask if user wishes to buy another item
*/
public void Repeat()
{
// User request to repeat operation
again = JOptionPane.showConfirmDialog (null,
"================================"
+ "\nWould you like to make another purchase?"
+ "\n================================");
} // End of Repeat constructor
} // End of VendingMachine class
import javax.swing.JOptionPane;//导入对话框的库
导入java.text.DecimalFormat;//导入用于十进制数格式设置的库
公共类VendingMachine//使用构造函数启动VendingMachine类
{
字符串spaymentSum;//用户插入的用于解析为整数值的货币
String productName;//产品名称
int paymentSum;//客户插入的货币被解析为整数值,即便士
int可口可乐、百事可乐、sevenUp、mars、snickers、twix;//销售产品的变量
int price;//持有所选产品价格的值
int changeLeft;//选择后从插入的货币向左更改
再次int;//用于描述程序重复的变量
DecimalFormat pence=新的DecimalFormat(#p);//格式化pence的显示输出
/**
*选择Menu constructor可显示欢迎信息、金钱插入和选择项目选项。
*/
公开作废插入货币()
{
字符串soption;//用于机器操作的变量
boolean correctOption=false;//用于用默认值确认输入验证的布尔变量
paymentSum=0;//初始化插入的货币变量paymentSum
do//循环开始有效选项选择循环
{
//自动售货机欢迎对话框
soption=JOptionPane.showInputDialog(
"============================================"
+“\n请到大学自动售货机来!”
+“\n===================================================================”
+\n\n选项:i表示插入资金,s表示选择项目,q表示退出
+“\n\n==========================================================”;
//仅针对i、s或q用户输入的输入验证
if(soption.matches(“isq”))
{
showMessageDialog(null,“无效输入!请重试”);
}
//启动开关条件以捕捉机器操作的特定字符(i、s和q)
开关(soption)
{
案例“q”://用户选择q退出
showMessageDialog(null,“祝您愉快!”);
System.exit(0);//终止应用程序
打破
案例“i”://如果用户选择i:插入资金;
做
{
spaymentSum=JOptionPane.showInputDialog(
"============================="
+“\n请输入一些钱(便士)”
+“\n===============================”;//插入资金
//针对字符串和十进制数的验证
if(spaymentSum.matches(“[a-zA-Z]+(\\\.[0-9]+)?$”)//根据字符串进行验证
{
showMessageDialog(null,“必须是正数!请重试”);
spaymentSum=null;
}
其他的
{
paymentSum=Integer.parseInt(spaymentSum);//解析计算
如果(paymentSum在NotEnoughMoney方法中,“如果(this.paymentSum==0)”应该在“如果(this.paymentSum请使用调试器逐步检查您的应用程序并查看出了什么问题。感谢您的提示。我以前从未使用过调试器,但我将对此进行研究,因为我多年来一直听说它们,但不知道它们实际做了什么。非常感谢!!:)和往常一样,这是一件小事!我现在可以回去完成剩下的作业了。再次感谢!