Results 1 to 2 of 2
- 01-24-2013, 04:57 AM #1
Member
- Join Date
- Jan 2013
- Posts
- 1
- Rep Power
- 0
Reading a multiple line file with StringTokenizer?
I have a file of integers:
3 5
6
I want to read the file and put 3, 5, and 6 in separate integers. This is my code so far:
Eclipse outputs these warnings:Java Code:import java.io.*; import java.util.*; public class milk2 { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new FileReader("milk2.in")); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("milk2.out"))); StringTokenizer st = new StringTokenizer(f.readLine()); int i1 = Integer.parseInt(st.nextToken()); f.readLine(); // I put this in to skip the space in between the first two integers int i2 = Integer.parseInt(st.nextToken()); int i3 = Integer.parseInt(st.nextToken()); out.println(i1); out.println(i2); out.println(i3); out.close(); System.exit(0); } }
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(Unknown Source)
at milk2.main(milk2.java:21)
I know the problem is with reading the second line because if I get rid of int i3, the first two integers are read and stored to i1 and i2 like they should be. But I can't read the next line. So how do I skip to the next line and continue reading?
- 01-24-2013, 10:10 AM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 10,484
- Rep Power
- 16
Re: Reading a multiple line file with StringTokenizer?
StringTokenizer is a legacy class that should no longer be used.
You should be using String.split() instead.
That will give you an array of Strings that you can then work with.
What's happening with yours is that you are trying to read in 3 tokens when the first line only has 2.Please do not ask for code as refusal often offends.
Similar Threads
-
reading particular line from textfile file
By karrydhawan in forum New To JavaReplies: 3Last Post: 01-05-2012, 12:22 PM -
Reading Next Line of File
By smitsky in forum New To JavaReplies: 5Last Post: 12-04-2011, 05:35 PM -
Java- Writing a file and reading a file line by line
By Nazneen Ali in forum New To JavaReplies: 7Last Post: 07-20-2011, 07:56 AM -
Reading a specific line from a file
By efebatistaarda in forum New To JavaReplies: 6Last Post: 02-22-2011, 02:57 PM -
Reading in data from file line by line
By bluekswing in forum New To JavaReplies: 1Last Post: 10-02-2007, 12:19 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks