这是一个找零问题,我需要输入价格和付款额,然后它将计算出客户支付一定金额(以硬币和钞票)后应该收到的找零额。
import java.util.Scanner;
public class Change {
public static void main(String[] args) {
int change;
int a; //a stands for 1000 kr bills.
int b; //b stands for 500 kr bills.
int c; //c stands for 200 kr bills.
int d; //c stands for 100 kr bills.
int e; //e stands for 50 kr bills.
int f; //f stands for 20 kr bills.
int g; //g stands for 10 kr coins.
int h; //h stands for 5 kr coins.
int i; //i stands for 2 kr coins.
int j; //j stands for 1 kr coins.
Scanner sc = new Scanner(System.in);
System.out.println("Price:");
double p = sc.nextDouble(); // p stands for the price.
System.out.println("Payment:");
int k = sc.nextInt(); //k stands for the payment.
int q = (int)Math.round(p);
change = k-q;
a = (k-q)/1000;
b = ((k-q)-(a*1000))/500;
c = ((k-q)-(a*1000+b*500))/200;
d = ((k-q)-(a*1000+b*500+c*200))/100;
e = ((k-q)-(a*1000+b*500+c*200+d*100))/50;
f = ((k-q)-(a*1000+b*500+c*200+d*100+e*50))/20;
g = ((k-q)-(a*1000+b*500+c*200+d*100+e*50+f*20))/10;
h = ((k-q)-(a*1000+b*500+c*200+d*100+e*50+f*20+g*10))/5;
i = ((k-q)-(a*1000+b*500+c*200+d*100+e*50+f*20+g*10+h*5))/2;
j = ((k-q)-(a*1000+b*500+c*200+d*100+e*50+f*20+g*10+h*5+i*2))/1;
System.out.println("Change:"+change);
System.out.println("1000 kr bills:"+a);
System.out.println("500 kr bills:"+b);
System.out.println("200 kr bills:"+c);
System.out.println("100 kr bills:"+d);
System.out.println("50 kr bills:"+e);
System.out.println("20 kr bills:"+f);
System.out.println("10 kr coins:"+g);
System.out.println("5 kr coins:"+h);
System.out.println("2 kr coins:"+i);
System.out.println("1 kr coins:"+j);
}
}
当我运行它时,它仅显示价格,而在输入价格并点击输入后,它显示Exception in thread "main" java.util.InputMismatchException
。
答案 0 :(得分:2)
当您double p = sc.nextDouble();
,但您输入的内容不是double
时,您将得到InputMismatchException
。例如,如果您输入“ 5g”,它将抛出异常。
(此内容适用于所有scanner.next<something>
。如果您int number = sc.nextInt()
给出了非整数值,则也会得到该异常。)
如果您确定要提供double
变量输入(例如12.58),但仍收到异常,请尝试使用逗号(例如12,58)给它。当然,与此相反。
扫描程序会根据默认的Locale
读取分隔符。
如果要确保使用点(。)分隔非整数,可以更改默认语言环境:
Locale.setDefault(Locale.US);