上机练习-购物结算
本段代码对于初学者使用,cmd运行,用的Scanner
需求说明:
-循环输入商品编号和购买数量
-当输入n时结账
-结账时计算应付金额并找零
代码如下:
System.out.println("choose the thing");
System.out.println("1.T_shirt"+'\t'+"2.shose"+'\t'+"3.pingpang");
int money=0;
int allmoney=0;
int all=0;
Scanner sc = new Scanner(System.in);
String continu=“y”;
while(continu=="y"){
System.out.println("请输入商品编号");
int number = sc.nextInt();
System.out.println("请输入购买数量");
int many = sc.nextInt();
if(number == 1){
money=10;
}else if(number==2){
money=20;
}else{
money=15;
}
allmoney=many*money;
System.out.println("buy information:"+number+'\t'+"many"+many);
System.out.println("合计:"+'\t'+allmoney);
System.out.println("是否继续购买?");
continu = sc.nextLine();
all = all + allmoney;
}
System.out.println("应支付金额:"+'\t'+all);
System.out.println("请支付");
int coustom = sc.nextInt();
if(all>coustom){
System.out.println("您输入的金额小于应付款:"(all-coustom));
}else{
System.out.println("找零:"+(coustom-all));
}
注意:
Scanner
如果将nextInt()方法写在nextLine()方法之前,nextLine()会被直接跳过!因为nextInt()方法返回值的时候只清空回车符以前的东西,而回车符会继续保留在队列中继续向下执行,这时nextLine()读取队列会将回车符读取,因此,程序直接执行完毕没有让你再次输入。
解决方法:可以将nextLine()用next()替换;或者nextInt()用nextLine()替换,再进行类型转换。