【问题标题】:Why I get java.util.InputMismatchException problem?为什么我得到 java.util.InputMismatchException 问题?
【发布时间】:2018-12-08 13:35:45
【问题描述】:

There is a picture about the text file

我想在控制台中读取文件,但每次尝试都会出错:

线程“主”java.util.InputMismatchException 中的异常 java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(未知来源)在 java.util.Scanner.nextInt(未知来源)在 java.util.Scanner.nextInt(未知来源)在 feladat.feladat.main(feladat.java:26)

package feladat;

import java.util.ArrayList;
import java.util.Scanner;

class Kerites{
    int oldal;
    int hazszam;
    char szin;

    public Kerites(int oldal, int hazszam, char szin) {
        super();
        this.oldal = oldal;
        this.hazszam = hazszam;
        this.szin = szin;
    }
}

public class feladat {
     static Kerites kerites;
     static ArrayList<Kerites> keritesek = new ArrayList<>();
    public static void main(String []args) {
        Scanner sc = new Scanner("kerites.txt");

        while(sc.hasNextLine()){
            int oldal = sc.nextInt();
            int hazszam = sc.nextInt();
            char szin = sc.next().charAt(0); 


        kerites = new Kerites(oldal,
                hazszam,
                szin);
        keritesek.add(kerites);
        }
        System.out.println("A beolvasott adatok száma: " + keritesek.size());
        for (int i = 0; i < keritesek.size(); i++) {
            System.out.println(keritesek.get(i).oldal + " "
                    + keritesek.get(i).hazszam + " "
                    + keritesek.get(i).szin);
        }
    }
}

那么我在这段代码中修改了什么?另外,我想知道我是如何只阅读文本中的最后一行的?

【问题讨论】:

  • 对于问题1,您需要上传该文件的至少一个示例行。问题2,参考:stackoverflow.com/questions/686231/…。你最好在问之前先谷歌一下。
  • 将该示例输入放入问题本身,这个问题看起来会很漂亮。欢迎使用 Stack Overflow。
  • 我在我的问题中添加了一张图片。
  • @GézaHorváth 我认为这个问题的根本原因与这里相同:stackoverflow.com/questions/13102045/…。尝试在char szin = sc.next().charAt(0); 之后添加sc.nextLine(); 并检查此问题是否消失

标签: java java.util.scanner reader


【解决方案1】:
sc = new Scanner(new File("kerites.txt"));

“sc = new Scanner("kerites.txt") 表示你的scanner的资源是字符串“kerites.txt”,不是文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 2011-09-23
    • 1970-01-01
    相关资源
    最近更新 更多