为什么只能输入一个数字?

recentlywe 2021-04-22 03:10:10
为什么只能输入一个数字,输入不了第二个数字?

public class Demo extends Exception {//自定义异常,必须继承Exception或其子类
public Demo() {
super();
}
public Demo(String code) {
super(code);
}
}

import java.util.Scanner;

public class Test {

public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("code:");
Scanner input = new Scanner(System.in);

try {
int code = input.nextInt();
show(code);
} catch (Demo e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
System.out.println("程序结束");
}
public static void show(int code) throws Demo{
if(code<1||code>3) {
throw new Demo("课程编码越界");//使用throws关键字声明异常对象
}else if (code==1) {
System.out.println("c++");
}else if(code==2){
System.out.println("java");
}
else {
System.out.println("mysql");
}
}
}
...全文
238 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
barton92 2021-04-22
  • 打赏
  • 举报
回复
稍微改了下,抛出异常就停止
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("code:"); try { while(true) { show(); } } catch (Demo e) { // TODO Auto-generated catch block e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); } System.out.println("程序结束"); } public static void show() throws Demo{ Scanner input = new Scanner(System.in); int code = input.nextInt(); if(code<1||code>3) { throw new Demo("课程编码越界");//使用throws关键字声明异常对象 }else if (code==1) { System.out.println("c++"); }else if(code==2){ System.out.println("java"); } else { System.out.println("mysql"); } } }
时间胶嚢 2021-04-22
  • 打赏
  • 举报
回复
加个循环就可以了 while(1){ try { int code = input.nextInt(); show(code); } catch (Demo e) { // TODO Auto-generated catch block e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); } System.out.println("程序结束"); } }

51,396

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧