我正在使用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