栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Scanner(System.in)-无限循环

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Scanner(System.in)-无限循环

如果

nextInt()
失败,则抛出异常,但不使用无效数据。从文档中:

当扫描程序抛出时

InputMismatchException
,扫描程序将不会传递导致异常的令牌,因此可以通过其他方法检索或跳过该令牌。

然后

meth()
,您再次递归调用,这将尝试第二次使用相同的无效数据,再次失败(不使用它),然后递归。

首先,我不会在这里首先使用递归。首选简单循环。接下来,如果输入无效,则应在再次尝试之前适当地使用它。最后,考虑使用

hasNextInt
而不是仅使用
nextInt
并捕获异常。

所以也许是这样的:

import java.util.Scanner;class Test {   public static void main(String[] args){       try (Scanner scanner = new Scanner(System.in)) {System.out.println("Enter the number here:");while (!scanner.hasNextInt() && scanner.hasNext()) {    System.out.println("Error");    // Skip the invalid token    scanner.next();}if (scanner.hasNext()) {    int value = scanner.nextInt();    System.out.println("You entered: " + value);} else {    System.out.println("You bailed out");}       }   }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/414342.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号