0

There is a picture about the text file

I want to read the file in the console but every time I try it I get an error:

Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at 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);
        }
    }
}

So what sould I modify in this code? Also, I would like to know that how I read only the last line in the text?

  • 1
    For question1, u need to upload at least one sample line of that file. For question2, refer to:https://stackoverflow.com/questions/686231/quickly-read-the-last-line-of-a-text-file. U'd better do a google before asking. – ZhaoGang Dec 08 '18 at 13:46
  • Put that example input into the question itself and this question will be looking beautiful. Welcome to Stack Overflow. – Marcus Dec 08 '18 at 13:59
  • I added a picture in my question. –  Dec 08 '18 at 14:04
  • @GézaHorváth I think the root cause of this issue is the same as here:https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo. Try to add `sc.nextLine(); ` after `char szin = sc.next().charAt(0); ` and check if this issue disappear – ZhaoGang Dec 08 '18 at 14:35

1 Answers1

2
sc = new Scanner(new File("kerites.txt"));

“sc = new Scanner("kerites.txt") means that your scanner's resource is the string "kerites.txt",not a file。