我正在使用hashmaps训练自己,并认为自己构建财务规划程序是个不错的主意。我试图提示用户输入一个字符串键(单据名称),然后将其应用于双值(也由用户输入),这相当于帐单的值。结果将是一个包含账单名称(如互联网或电力等)的散列表,以及这些账单的价值。用户无法在java中添加hashmap的密钥while循环
我建立了一个叫InputData类 - 如下:
package financial.planner;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class InputData {
private double salary;
private Map<String, Double> bills;
private boolean chooseContinue;
public InputData(){
super();
this.salary = 0.0;
this.bills = new HashMap<>();
this.chooseContinue = false;
}
//getters and setters for salary
public double getSalary(){
return this.salary;
}
public void setSalary(double aSalary){
this.salary = aSalary;
}
//getters and setters for bills
public Map<String, Double> getBills(){
return this.bills;
}
public void setBills(Map<String, Double> aBills){
this.bills = aBills;
}
//getters and setters for chooseContinue
public boolean getChooseContinue(){
return this.chooseContinue;
}
public void setChooseContinue(boolean aChooseContinue){
this.chooseContinue = aChooseContinue;
}
public void FPSalary(){
Scanner scanVar = new Scanner(System.in);
System.out.print("Enter salary: \n");
this.setSalary(scanVar.nextDouble());
}
public void FPBills(){
Scanner scanVar = new Scanner(System.in);
Map<String, Double> billsMap = new HashMap<>();
while(!this.getChooseContinue())
{
System.out.println("Enter bill name: \n");
String billName = scanVar.nextLine();
System.out.println("Enter bill value: \n");
double billValue = scanVar.nextDouble();
billsMap.put(billName, billValue);
this.FPChooseContinue();
}
this.setBills(billsMap);
setChooseContinue(false);
}
public void FPChooseContinue(){
Scanner scanVar = new Scanner(System.in);
System.out.println("Any more to add (y or n)?\n");
String yesOrNo = scanVar.nextLine();
switch (yesOrNo) {
case "y":
break;
case "n":
this.setChooseContinue(true);
break;
default:
System.out.print("Please enter y or n");
}
}
}
在我的主:
package financial.planner;
public class FinancialPlanner
{
public static void main(String[] args)
{
InputData IDobject = new InputData();
System.out.println("Financial Planner 1.0");
IDobject.FPSalary();
IDobject.FPBills();
System.out.println(IDobject.getBills());
}
}
程序运行时根据计划,除非我尝试添加第二个键(即帐单名称) - 它忽略此请求并直接运行到帐单值:
财务计划1.0输入工资:30000输入票据名称:
气体输入纸币值:
450的任何更多的补充(Y或N)?
y输入法案名称:
输入法案值:
37任何更多的补充(是或否)?
N {= 37.0,天然气= 450.0}
我倒是很欣赏有经验的程序员借给我一只手搭在这一个 - 林可能做一些非常愚蠢的 - 但我喜欢编程和希望得到更好的!请帮忙!任何其他关于我的代码的建议也将不胜感激。
什么是你试图做调用超();在InputData的构造函数中? – Lucas
我可能计划在某个时候将该类作为子类使用,并将其放入 - 这是一种不好的做法吗? – user2792655