我已经构建了一个货币转换程序,并且需要用户输入。在该计划的某一点,我要求他们想要兑换的货币。但是,没有任何东西阻止他们将“java”作为货币或任何其他词汇。抛出异常,即使数据类型正确
这里是我当前的代码,我会解释多一点什么我在寻找进一步下跌:
import java.util.Scanner;
public class Exchange {
public static void main(String[] args) {
int i = 1;
Scanner inn = new Scanner(System.in);
try{
while (i > 0){
double USDrate = 0.12808;
double EURrate = 0.107643821;
double GBPrate = 0.098872935;
System.out.println("Hello, what currency would you like to convert to?");
System.out.println("Types: USD/EUR/GBP");
String type = inn.nextLine();
System.out.println("Hello, how much would you like to convert?");
double NOK = inn.nextDouble();
if(type.equalsIgnoreCase("USD")){
System.out.printf(NOK + "kr equals $%.2f \n", (NOK*USDrate));
}else if(type.equalsIgnoreCase("EUR")){
System.out.printf(NOK + "kr equals €%.2f \n", (NOK*EURrate));
}else if(type.equalsIgnoreCase("GBP")){
System.out.printf(NOK + "kr equals £%.2f \n", (NOK*GBPrate));
}else {
// This is where I would like to throw an exception if what they put in doesn't make sense.
}
inn.nextLine();
System.out.println("Would you like to convert more?");
System.out.println(" YES/NO ");
String ans = inn.nextLine();
if(ans.equalsIgnoreCase("NO")){
i = 0;
}
}
}
catch(Exception e){
System.out.println("You've entered an incorrect value! Restart.");
}
}
}
我想除了采取while
-loop内的最后else
语句来下进行,正如你所看到的,我有一个评论,那就是那个意思。我还想在代码块中有同样的例外,我问他们是否想要转换更多。
任何人都可以提供帮助吗?如果您需要的任何细节丢失,我会根据要求给他们。
在此先感谢。
我想出了如何使它成为我想要的方式。也不例外必要的,但这里是我的解决方案:
import java.util.Scanner;
public class Exchange {
public static void main(String[] args) {
int i = 1;
Scanner inn = new Scanner(System.in);
try{
while (i > 0){
double USDrate = 0.12808;
double EURrate = 0.107643821;
double GBPrate = 0.098872935;
System.out.println("Hello, what currency would you like to convert to?");
System.out.println("Types: USD/EUR/GBP");
String type = inn.nextLine();
if(!type.equalsIgnoreCase("USD") && !type.equalsIgnoreCase("EUR") && !type.equalsIgnoreCase("GBP")){
System.out.println("Not available currency! Try again.");
break;
}
System.out.println("How much would you like to convert?");
double NOK = inn.nextDouble();
if(type.equalsIgnoreCase("USD")){
System.out.printf(NOK + "kr equals $%.2f \n", (NOK*USDrate));
}else if(type.equalsIgnoreCase("EUR")){
System.out.printf(NOK + "kr equals €%.2f \n", (NOK*EURrate));
}else if(type.equalsIgnoreCase("GBP")){
System.out.printf(NOK + "kr equals £%.2f \n", (NOK*GBPrate));
}
inn.nextLine();
System.out.println("Would you like to convert more?");
System.out.println(" YES/NO ");
String ans = inn.nextLine();
if(ans.equalsIgnoreCase("NO")){
i = 0;
}
}
}
catch(Exception e){
System.out.println("You've entered an incorrect value! Restart.");
}
}
}
使用的另一种方法:)感谢您的答案不管怎么说,他们帮了不少忙。
你有什么试过?你看起来是99%的方式。此外,你不一定需要在这里例外。您可以预先检查货币,并在输入错误时循环。 – Carcigenicate
为了“有一个例外”,你需要抛出它:抛出新的SomeException(),但我不认为这就是你想要的 – 2017-09-04 17:11:19
你将如何去预先检查货币和“循环,而输入是坏的“?如果你不介意。我很新鲜,所以我不明白所有条款。为什么我不想要一个例外,我什么时候需要它?请原谅所有问题,但我真的很感谢你的帮助。 –