gpt4 book ai didi

java - 当输入不是 "q"并且不使用扫描仪加倍时如何输出错误

转载 作者:行者123 更新时间:2023-12-01 06:07:02 25 4
gpt4 key购买 nike

public class CurrencyConverter
{
double dollar;
double rate; //constructors
double euro;

//构造函数

public CurrencyConverter()
{
dollar=0;
rate=0.95;
}

//对象

public void setDollar(double d)
{
dollar= d;
}
public double getCurrency()
{
euro= rate*dollar;
return euro;

当输入不是“q”并且代码中不是 double 时如何输出错误我尝试使用 if 方法,但它不起作用

import java.util.Scanner;

public class CurrencyTester {

private static Scanner in;

public static void main(String[] args) {

CurrencyConverter one = new CurrencyConverter();
System.out.println("Convert dollar to euro");
System.out.println("");

do {
System.out.println("Enter Dollars:");
in = new Scanner(System.in);
String d = in.next();
if ("Q".equalsIgnoreCase(d)) {
System.out.println("Stop!");
break;
} else {
double ds = Double.parseDouble(d);
one.setDollar(ds);
System.out.println("Euro:");
System.out.println(one.getCurrency());
}
} while (true);

}
}

最佳答案

当您检查输入是否为 q 时,第一部分是正确的,您需要检查输入是否为 double,因此您可以使用 try{}catch(){}像这样:

do {
System.out.println("Enter Dollars:");
Scanner in = new Scanner(System.in);
String d = in.next();
if ("Q".equalsIgnoreCase(d)) {
System.out.println("Stop!");
break;
} else {
//check if your input is valid double or not, if not show an error message
try {
double ds = Double.parseDouble(d);
one.setDollar(ds);
System.out.println("Euro:");
System.out.println(one.getCurrency());
} catch (NumberFormatException e) {
System.out.println("*********Not double*********");
}
}
} while (true);

关于java - 当输入不是 "q"并且不使用扫描仪加倍时如何输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42398196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com