V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
jzq526
V2EX  ›  Java

求助, Java 中 Scanner 类的 nextInt()方法问题

  •  
  •   jzq526 · 2020-04-09 21:26:15 +08:00 · 1638 次点击
    这是一个创建于 1450 天前的主题,其中的信息可能已经有所发展或是发生改变。

    遇上了一个问题,程序:

    import java.util.Scanner;
    public class InputTEst {
        public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            int i;
            String temp="abcd\n";
            String s;
            System.out.println("输入一个整数:");
            i=sc.nextInt();
            temp=sc.nextLine();
            System.out.println("输入一个字符串:");
            s=sc.nextLine();
            System.out.println("i="+i+",s="+s.toCharArray().length+",temp="+(int)temp.toCharArray().length);
        }
    }
    

    如果没有temp=sc.nextLine();这一行,那么输入一个整数后,无需再输入字符串,程序就会结束,并显示 s 的长度为 0 。

    (刚发现,不要在意为什么把字符串 s 转成字符数组才求长度,因为还没有从刚才写的程序中回过神来,随手就这么写了)

    根据之前的经验,我推测应该是前面的sc.nextInt()方法并没有正确处理 windows 下面的回车( windows 下面按下回车键产生两个字符,回车和换行,\r\n,Linux 、UNIX 和 MAC 都只有一个字符)。粗略看了一下 nextInt 方法的代码,也没有什么头绪,

    所以请教大神: nextInt 方法到底是检测到不是整数的数据就停下来来,还是压根就没有考虑到 windows 的这个特殊情况?

    第 1 条附言  ·  2020-04-10 12:28:12 +08:00
    又看了看源码和官方文档,大体上明白了。
    nextInt 方法会根据一些分隔符来判断要捕获的内容,包括回车和换行。所以这个方法不会处理这些分隔符,和系统无关。
    剩下的分隔符就留在缓冲区当中了。
    和 hasNextInt 方法也没有关系,这个方法只管判断输入的信息能不能转换为 int 类型,不负责处理
    2 条回复    2020-04-09 21:57:11 +08:00
    liangch
        1
    liangch  
       2020-04-09 21:37:14 +08:00
    随便一个例子。
    https://www.geeksforgeeks.org/scanner-nextint-method-in-java-with-examples/

    人家是要先 hasNextInt 的。回去看文档吧。
    jzq526
        2
    jzq526  
    OP
       2020-04-09 21:57:11 +08:00
    @liangch 刚看了一下,hasNextInt 是用来判断后面有没有可以转换为 int 的数据,而且处理的是一个特定字符串,不是键盘的输入,可能解释不了我的问题。

    我想知道的是,为什么使用 nextInt 方法之后,还剩下了一个(或者一些?)未处理的字符?

    不过在 oracle 官网的文档中找到这么一段:If the next token matches the Integer regular expression defined above then the token is converted into an int value as if by removing all locale specific prefixes, group separators, and locale specific suffixes, then mapping non-ASCII digits into ASCII digits via Character.digit, prepending a negative sign (-) if the locale specific negative prefixes and suffixes were present, and passing the resulting string to Integer.parseInt with the specified radix.

    应该可以解释为什么会有剩下的、没有处理的字符。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2750 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 15:06 · PVG 23:06 · LAX 08:06 · JFK 11:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.