为什么输入了价格abc以后,s001,冰箱,那条输入的值就没有被存进去?
我是 否可以认为只有编号,名称和价格都是正确的情况下才可以被录入?
也就是一个报错,前面的接收值全部无效了?
正在回答
是的,同学可以这么理解。祝:学习愉快~
你好!老师的代码如下:当输入非数值型信息时,老师使用了console.next();接受错误信息,使其向下继续执行时。因为老师使用了循环,所以调用continue;结束了当前循环,执行下次循环。
在同学的代码中,也调用了next(),但是不是用的之前的Scanner对象sc去调用的next(),而是新创建了一个对象ak去调用next(),这样的话就相当于是一个新的流,这样是不能接受之前输入的非数字的。所以下面选中的代码可以改成String b=sc.next();
建议同学将不懂的地方描述的更清楚,必要的时候,可以在截图发在添加回答中。祝:学习愉快!
按照老师上课讲的,这里我的赋值不会成功,但是输入的值还是在等待着被录进去的。我这里sc.nextint()输入了s,报错。我就用String b来接收,为什么打印出来的b却是第二次输入的8?还有我这段代码应该怎么改?
package test;
import gouwuche.*;
import java.util.Scanner;
public class Test {
GoodsManage one=new GoodsManage();
ShoppingCart two=new ShoppingCart();
GoodsManage three=new GoodsManage();
Scanner sc=new Scanner(System.in);
public void hello1() {
System.out.println("商品管理");
System.out.println("1--商品信息导入");
System.out.println("2--显示所有商品信息");
System.out.println("9--返回上一级菜单");
}
public void hello2() {
try{this.hello1();
int i=sc.nextInt();
if(i==1) {
this.one.importGoods();
System.out.println("商品导入成功");
this.hello2();
}if(i==2) {
this.one.displayAllGoods();
this.hello2();
}if(i==9) {
hello5();
} }catch(Exception e){
System.out.println("请输入正确的数字");
hello5();
}
}
public void hello3() {
System.out.println("购物车管理");
System.out.println("1--添加商品到购物车");
System.out.println("2--修改购物车中的商品数量");
System.out.println("3--显示购物车中的所有商品信息");
System.out.println("4--结算");
System.out.println("9--返回上级菜单");
}
public void hello4() {
try{this.hello3();
int i=sc.nextInt();
if(this.two.getShoppingCart()!=null) {
if(i==1) {
this.two.addGoodsToCart(this.one);
this.hello4();
}if(i==2) {
this.two.updateNumInCart();
this.hello4();
}if(i==3) {
this.two.displayAllInCart();
this.hello4();
}if(i==4) {
this.two.settleAccounts();
this.hello4();
}if(i==9) {
this.hello5();
}else {
System.out.println("请先导入商品");
}
}}catch(Exception e) {
System.out.println("请输入正确的数字");
}}
public void hello5() {
System.out.println("主菜单");
System.out.println("1--商品管理");
System.out.println("2--购物车");
System.out.println("0--退出");
System.out.println("请输入对应操作");
int a=0;
try {
a=sc.nextInt();
}catch(Exception e){
Scanner ak=new Scanner(System.in);
System.out.println("请重新输入");
String b=ak.next();
System.out.println(b);
System.out.println(a);
hello5();
}
if(a==1) {
hello2();
}
if(a==2) {
hello4();
}if(a==0) {
System.exit(0);
}if(a!=1&&a!=2&&a!=0) {
System.out.println("请输入正确的数字");
hello5();
}
}
public static void main(String[] args) {
Test test1=new Test();
test1.hello5();
}
}
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星