帮帮JAVA新手的小忙!谢谢

chen106203291 2012-06-02 09:46:26
class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean flag = true;
while (flag) {
System.out.println("请输入1-100以内的数字");

try {
int score = sc.nextInt();
if (score <= 100 && score >= 1) {
System.out.println((char) ('E' - ((score - 1)) / 20));
} else {
System.out.println("您输入的数字超过范围");
}
} catch (Exception e) {
System.out.println("您输入的数字不符合要求");
}
sc.nextLine();
System.out.println("是否继续y/n");
String s = sc.next();
if (s.equals("y")){
flag = true;
}
else if(s.equals("n")){
System.out.println("谢谢使用再见");
break;
}
}
}
}

这个代码中System.out.println((char) ('E' - ((score - 1)) / 20));是什么意思啊?
还有这个catch (Exception e)什么意思啊?
sc.nextLine();
这个next后面接Line是不是表示下行输入,next后面接Int是表示?
...全文
99 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
sdojqy1122 2012-06-02
  • 打赏
  • 举报
回复
好像是俺写的。。。。

(char) ('E' - ((score - 1)) / 20)
这句话的意思就是
if (a >= 1 && a <= 20) {
System.out.println("E");
} else if (a >= 21 && a <= 40) {
System.out.println("D");
} else if (a >= 41 && a <= 60) {
System.out.println("C");
} else if (a >= 61 && a <= 80) {
System.out.println("B");
} else if (a >= 81 && a <= 100) {
System.out.println("A");
}

'E'先转化成ascii值,然后加上对应的数组就得到ABCDE了。。直接在把ascii值转化为字符。然后打印。
try{}catch(Exception e){}
这是个很简单的异常捕获,如果发现输入错误,就会抛异常,然后捕获到,进行处理。
sc.nextLine();这一句的解释就是 int score = sc.nextInt();这里不是输入了 一个数字 和换行符吗?
所以如果不加这一句 String s = sc.next();这行代码就会捕获到那个换行符,也就是导致了直接跳过输入的bug。所以加上那一句是为了把换行符拿掉的。这样不会干扰后的sc.next();
感觉解释比代码还长。

50,503

社区成员

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

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