Reputation: 3441
I'm having problems reading in a text file with java. The text file has the following format:
String
String
String
String
Int
Int
Int
Int
With each String and int value having a new line character at the end and a blank line in between the stings and ints. I want to save each string value into a string array but I can't quite figure out how to get the scanner to stop at the blank line. I tried various methods such as going until there is an int, going until the value of hasNext is " ", and trying to just read the strings but nothing is working. Can someone provide anyhelp?
Upvotes: 1
Views: 275
Reputation: 2854
while (mScanner.hasNextLine()){
String line = mScanner.nextLine();
if (line.length() == 0)
break;
else
mArrayList.add(line);//do stuff
}
Upvotes: 0
Reputation: 53849
Not sure from your example if you have exactly 4 String
s and 4 Integer
s or more, so something like the following should work:
List<String> strings = new ArrayList<String>();
List<Integer> ints = new ArrayList<Integer>();
while(scanner.hasNext() && !scanner.hasNextInt()) {
strings.add(scanner.next());
}
while(scanner.hasNextInt()) { // If you also want to store the ints
ints.add(scanner.nextInt());
}
Upvotes: 4
Reputation: 36259
public static void main (String [] args)
{
Scanner sc = new Scanner (System.in);
int count = 0;
while (sc.hasNext ())
{
String s = sc.next ();
++count;
System.out.println (count + ": " + s);
if (count == 4)
break;
}
while (sc.hasNext ())
{
int i = sc.nextInt ();
System.out.println (count + ": " + i);
}
}
cat dat
Foo
Bar
Foobar
Baz
1
2
4
8
Test: cat dat | java ScanIt
1: Foo
2: Bar
3: Foobar
4: Baz
4: 1
4: 2
4: 4
4: 8
From the original question I had, as you see, a slightly different idea about the file format, but you see: I don't do anything special for newlines or empty newlines.
So the program should work for you too.
Upvotes: 0