Lukasz Medza
Lukasz Medza

Reputation: 499

Java - Using scanner to read multiple items on the same line

I'm trying to load in a text file that is formatted like so:

 int String int

 int String int

 int String int

What I want to do is to read the three values and put them into a constructor

My usual approach to a problem like this would be to simply do

        int t = infile.nextInt();
        String d = infile.nextLine();
        int p = infile.nextInt();


        Entry e = new Entry(t,d,p);

However, this only works if t,d and p are on separate lines because of nextInt() and nextLine()

My question is, how do I proceed to read in the 3 values from the same line, and then move on to the next line?

Upvotes: 0

Views: 3947

Answers (2)

duffymo
duffymo

Reputation: 308763

I would read the entire line as a String, tokenize it at whitespace, and parse out the three values into their appropriate types:

String line = infile.nextLine();
String [] tokens = line.split("\\s+");
int v1 = Integer.parseInt(tokens[0]);
String v2 = tokens[1];
int v3 = Integer.parseInt(tokens[2]);
Entry e = new Entry(v1, v2, v3);

Upvotes: 2

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

Parse it like this:

int t = infile.nextInt(); //reads int
String d = infile.next(); //reads the next String before a blank space " "
int p = infile.nextInt(); //reads int
Entry e = new Entry(t,d,p); //use your data
infile.nextLine(); //read the line escape "\n" or "\r\n"

Upvotes: 3

Related Questions