FileReader need assistance
hi folks.
uhm how do i read all the inputs from a file, well the problem is it only reads the first line? can you help me, im not yet familiar with the methods thanks
Here's the main class
Code :
import java.util.*;
import java.io.*;
public class readFile
{
public static void main(String[]args) throws IOException
{
Scanner sc = new Scanner(new FileReader("cool.in"));
int min = Integer.parseInt(sc.next());
int max = Integer.parseInt(sc.next());
System.out.println(min+" "+max);
}
}
and here's the "cool.in" file to be read
Re: FileReader need assistance
the scanner.next() method reads in a "word" (aka, stuff separated by whitespaces).
So, the first call to next() would return "1", the second one would return "10", the third "20", and so on until there's nothing left to read.
What you can do if you want to read in all the inputs is use a while loop to read in all the values. This will require some data structure to hold all the values (usually a list of some sort), unless you don't want to save the values you read in.
Code :
Scanner reader = new Scanner(new FileReader("cool.in"));
while (reader.hasNext())
{
System.out.println("Reading min... " + reader.next());
System.out.println("Reading max..." + reader.next());
}
Re: FileReader need assistance
thanks for the quick reply..im adding some info if you dont mind
well im gonna also used the first column as "min" and the next column for "max"
its like this
Code :
for(int x=min ;x <=max; x++)
{
[I]script[/I]
}
something like that
the problem is it only reads the first line which is
1 10
Re: FileReader need assistance
Just put it inside the the while loop:
Code :
while (reader.hasNext())
{
int min = Integer.parseInt(reader.next());
int max = Integer.parseInt(reader.next());
for(int x=min ;x <=max; x++)
{
[i]script[/i]
}
}
Re: FileReader need assistance
thank you very much i should include the min and max for it to be included thank you problem sovled