pkrist
pkrist

Reputation: 25

Trying to read from text file

I am trying to read the following from a text file:

12
650 64 1
16 1024 2

My attempt:

import java.util.Scanner;
import java.io.*;

class Test{

    public static void main(String[] args){
        String filnavn = "regneklynge.txt";
        Scanner innFil = null;
        try {
            File fil = new File(filnavn);
            innFil = new Scanner(fil);
            while (innFil.hasNextLine()) {
                String linje = innFil.nextLine(); 
                int tall = Integer.parseInt(linje);
                System.out.println(tall);
            }
        } catch(FileNotFoundException e) {
            System.out.println("Filen kunne ikke finnes");
        }
    }
}

The first number(12) Works fine, but then I get this

Exception in thread "main" java.lang.NumberFormatException: For input string: "650 64 1"

Upvotes: 1

Views: 114

Answers (2)

sirandy
sirandy

Reputation: 1838

As long as you are reading the full line:

String linje = innFil.nextLine(); 

You can't treat them as an Integer because it's already a String

int tall = Integer.parseInt(linje);
// linje now has this = "650 64 1"

So that provokes the Exception: java.lang.NumberFormatException

Here is an approach to print the numbers:

import java.util.Scanner;
import java.io.*;

class Test{

    public static void main(String[] args){
        String filnavn = "regneklynge.txt";
        Scanner innFil = null;
        try {
            File fil = new File(filnavn);
            innFil = new Scanner(fil);
            while (innFil.hasNextLine()) {
                if (innFil.hasNextInt()) {
                    System.out.println(innFil.nextInt());
                } else {
                    innFil.next();
                }
            }
        } catch(FileNotFoundException e) {
            System.out.println("Filen kunne ikke finnes");
        }
    }
}

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Suggestions:

  • You need two while loops, one nested inside of the other
  • the first one, the outer loop, you loop while (innFile.hasNextLine()) {...}
  • inside this loop you call String linje = innFile.nextLine(); once
  • Then create a 2nd Scanner object, Scanner lineScanner = new Scanner(linje);
  • and create a 2nd inner while loop that loops while (lineScanner.hasNextInt() {...}
  • inside of this loop, extract a single int via int tall = lineScanner.nextInt();
  • and put it into your ArrayList.
  • Be sure to call lineScanner.close(); after exiting the inner while loop and before exiting the outer loop.

Upvotes: 1

Related Questions