我正在研究这种简单的货币转换器,只是为了强化我学到的一些概念。一切都按计划工作,除非转换器第一次运行,while循环的第二次迭代导致第一个答案同时使用if和else。输出如下:
将美元转换为哪种货币? [日元,元,比索,英镑,欧元] 磅
您想转换多少美元? 5
您已将$ 5.0转换为3.8磅
将美元转换为哪种货币? [日元,元,比索,英镑,欧元] 请选择一种货币 将美元转换成哪种货币? [Yen,Yuan,Peso,Pound,Euro]
货币类:
package currency;
import java.util.HashMap;
import java.util.Map;
public class Currency {
private Map<String, Double> ct;
private double newCurrency;
private String answer;
private double amount;
public Currency() {
this.ct = new HashMap<String, Double>();
}
// Getters and Setters
public void setAnswer(String answer) {
this.answer = answer;
}
public String getAnswer() {
return this.answer;
}
public void setAmount(double amount) {
this.amount = amount;
}
public double getAmount() {
return this.amount;
}
// Current available currencies
public void loadMap() {
ct.put("Pound", 0.76);
ct.put("Euro", 0.85);
ct.put("Yen", 112.23);
ct.put("Yuan", 6.61);
ct.put("Peso", 18.87);
System.out.println(ct.keySet());
}
// Multiples amount times currency
public double multiplyCurrency(String answer, double amount) {
newCurrency += ct.get(getAnswer()) * getAmount();
return newCurrency;
}
public double getNewCurrency() {
return this.newCurrency;
}
// Checks user if Map contains userinput.
public boolean checkAnswer(String answer) {
if (!ct.containsKey(answer)) {
return false;
} else {
return true;
}
}
@Override
public String toString() {
return "You have converted $" + getAmount() + " into " + getNewCurrency() + " " + this.answer + "\n";
}
}
逻辑课程:
package logic;
import java.util.Scanner;
import currency.Currency;
public class Logic {
private Currency currency;
private Scanner reader;
private boolean running;
private String answer;
public Logic() {
this.currency = new Currency();
this.reader = new Scanner(System.in);
this.running = true;
this.answer = null;
}
public void start() {
//Runs until quit
while (running) {
System.out.println("Convert US dollar into which currency?");
currency.loadMap();
answer = reader.nextLine();
currency.setAnswer(answer);
// checks to make sure the value is in the map
if (currency.checkAnswer(currency.getAnswer()) == true) {
System.out.println("\n" + "How many dollars would you like converted?");
double amount = reader.nextDouble();
currency.setAmount(amount);
currency.multiplyCurrency(currency.getAnswer(), currency.getAmount());
System.out.println("");
System.out.println(currency);
} else {
System.out.println("Please select a currency");
}
}
}
}
主类:
package logic;
public class Main {
public static void main(String[] args) {
Logic l = new Logic();
l.start();
}
}
我真的很感激任何反馈,所以我可以记录,并且永远不会再发生这种情况。提前谢谢。
答案 0 :(得分:0)
在Currency
课程中,只需将answer = reader.nextLine();
更改为answer = reader.next();
归因于this - 即在nextDouble();
另外,请注意,如果用户未输入货币的确切文本,则只会打印else
语句并重新开始。
答案 1 :(得分:0)
Scanner.nextDouble
方法不会消耗输入的最后一个换行符,因此在下一次调用Scanner.nextLine
时会消耗换行符。
你基本上遇到了与this post
一个简单的解决方法是将值读取为String并将其解析为double,以便替换
double amount = reader.nextDouble();
通过
double amount = Double.parseDouble(reader.nextLine());