【问题标题】:Where is the error for stringTokenizer used to read and integer number and a string?stringTokenizer 用于读取整数和字符串的错误在哪里?
【发布时间】:2019-09-15 17:03:23
【问题描述】:

我必须使用 Java 程序读取输入中的文件(.txt 文件),并且我正在使用 Eclipse。在第一行,我有一个数字和一个字符串(例如“1 studente”)。我尝试使用 stringTokenizer,但在输入“1 studente”时出现 NumberFormatException 错误。我该如何解决?

我试图放置一个异常,但 StringTokenizer 没有读取“studente”,我发现另一个错误:NosuchElementException

下面是代码

public static void main(String[] args) {    
    try {
        BufferedReader br = new BufferedReader(new FileReader("partecipanti.txt"));
        String line = br.readLine();
        while(line!=null) {
            StringTokenizer tok = new StringTokenizer(line, " ");
            int cod = Integer.parseInt(tok.nextToken());
            String tipo = tok.nextToken();
            String nome = br.readLine();
            String cognome = br.readLine();

...

这是我得到的错误。 java.lang.NumberFormatException:对于输入字符串:“1 个学生”

【问题讨论】:

  • 这很奇怪。我无法重现。可能1studente 之间的字符不是普通的空格字符,而是其他一些看起来像空格的字符。
  • 你能分享你的文件吗?

标签: java parseint stringtokenizer


【解决方案1】:

根据official documentation,不鼓励使用StringTokenizer

StringTokenizer 是为了兼容性而保留的遗留类 原因尽管在新代码中不鼓励使用它。推荐 任何寻求此功能的人都使用 String 的 split 方法 或 java.util.regex 包。

您应该改用String.split。您可以传递正则表达式 (\\s) 以按空格分隔。

public static void main(String[] args) {    
    try {
        BufferedReader br = new BufferedReader(new FileReader("partecipanti.txt"));
        String line = br.readLine();
        while(line!=null) {
           String[] tok = line.split("\\s");
           int cod = Integer.parseInt(tok[0]);
           String tipo = tok[1];
           String nome = br.readLine();
           String cognome = br.readLine();
        }
}

【讨论】:

    猜你喜欢
    • 2013-10-21
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    • 2018-09-12
    • 2020-01-28
    • 1970-01-01
    相关资源
    最近更新 更多