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

2020-04-09 21:26:15 +08:00
 jzq526

遇上了一个问题,程序:

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 的这个特殊情况?

1664 次点击
所在节点    Java
2 条回复
liangch
2020-04-09 21:37:14 +08:00
随便一个例子。
https://www.geeksforgeeks.org/scanner-nextint-method-in-java-with-examples/

人家是要先 hasNextInt 的。回去看文档吧。
jzq526
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.

应该可以解释为什么会有剩下的、没有处理的字符。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/660944

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX