为了账号安全,请及时绑定邮箱和手机立即绑定

把int a=input.nextInt();放在Try块外只要开始输入的是字母就报错,但是如果把int a=input.nextInt();放在Try块内一执行就死循环,不知道要怎么改........

package com.imooc;


import java.util.Scanner;

import java.util.InputMismatchException;

public class Test {

public void test1(){

String []books={"高数","数据结构","大学英语","C语言","数电","模电"};

Scanner input=new Scanner(System.in);

int c=1;

do{

System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");

int a=input.nextInt();

try{

if(a!=1&&a!=2){

throw new Exception();

}else if(a==1){

System.out.println("输入图书名称:");

String name=input.next();

try{

for(int i=0;i<books.length;i++){

if(name.equals(books[i])){

System.out.println("book:"+books[i]);

}else if(i<books.length){

continue;

}else{

throw new Exception();

}

}throw new Exception();

}catch(Exception e){

System.out.println("图书不存在!");

}//continue;

}else if(a==2){

System.out.println("输入图书序号:");

try{

int b=input.nextInt();

if(b>=0&&b<=5){

System.out.println("books:"+books[b]);

continue;

}else{

throw new Exception();

}

}catch(InputMismatchException e){

System.out.println("命令输入错误!请根据提示输入数字命令!");

}catch(Exception e){

System.out.println("图书不存在!");

}continue;

}

}catch(Exception e){

System.out.println("命令输入错误!请根据提示输入数字命令!");

}continue;

}while(c==1);

}

}


正在回答

3 回答

你把你的int型改为String型,因为如果定义int型,输入其它类型肯定提示错误类型转换

0 回复 有任何疑惑可以回复我~

if(a!=1&&a!=2){

throw new Exception();

}else if(a==1){

没事抛那么多异常干嘛.这逻辑也有问题

0 回复 有任何疑惑可以回复我~

你可以尝试把try catch 放在 do while循环外 试试看

0 回复 有任何疑惑可以回复我~
#1

慕村5150547

你代码错了 太乱了。 你好好整理一下 什么东西乱用的
2016-12-15 回复 有任何疑惑可以回复我~
#2

慕村5150547 回复 慕村5150547

还有就是你已经确定了 int a 它是整型 你输入其他的字符型 肯定报错啊
2016-12-15 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

把int a=input.nextInt();放在Try块外只要开始输入的是字母就报错,但是如果把int a=input.nextInt();放在Try块内一执行就死循环,不知道要怎么改........

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信