Detected a new line within a series of numbers in Java
Let's say I have a series of numbers like...
1 2 3 4
5 6 7 8
9 0
How could I step through each int, but stop when I reach a new line? I'm currently using nextInt()
and I know that nextLine()
will detect the new line, but I'm not sure how to piece that together. Is it best to take the entire line, and parse the string into separate ints? Or is there a more fluid method of doing this?
For m开发者_运维百科y example, I would want the program to store 1 2 3 4
, 5 6 7 8
, 9 0
all in their own separate array.
For more clarification, I'm using the java.util.Scanner
and I'm reading a text file.
If you want to use Scanner
, read the entire line into a String, and then construct a Scanner on the String.
You can open the text file in read mode and read the entire line with readLine()
method.
Then you can split the line read with the space ( ' ' ) character which will automatically give you an array.
You can do this till the end of file.
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
delimiter = " ";
int myArr[];
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
myArr = strLine.split(delimiter);
// store this array into some global array or process it in the way you want.
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Hope this helps.
精彩评论