Hi guys, I just need to know how to take two numbers at a time as input from text file as i have to assign these two numbers as i,j so that i can compare them with other values
my input file contains two numbers per line separated with " " i.e,1 2
2 3
4 5.............
i nearly have 1000 pairs as my input
This is my code so far:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class sample{
public static void main(String args[]) throws FileNotFoundException
{
FileInputStream file = new FileInputStream("clusters.txt");
Scanner inputFile = new Scanner(file);
while (inputFile.hasNextLine()) {
String line = inputFile.nextLine( );
System.out.println("line = '" + line + "'");
final String[] array = line.split("\\s");
System.out.println(Arrays.toString(array));
int i = Integer.parseInt( array[0] );
int j = Integer.parseInt( array[1] );
System.out.println("i="+i+"j="+j);
}
} }
My problem is i am able to print the i,j values but i am getting some errors during this like.I have edited the output and posted only error parts
run:
i=33j=101
i=33j=103
i=33j=104
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
i=34j=37
i=34j=45
i=34j=52
i=34j=57
i=34j=58
i=34j=64
i=34j=69
i=34j=70
at java.lang.NumberFormatException.forInputString(i=41j=54
NumberFormatException.java:65)
i=41j=56
i=41j=58
i=41j=66
i=41j=70
i=41j=71
i=41j=78
at java.lang.Integer.parseInt(i=41j=82
Integer.java:573i=41j=84
)
i=41j=85
i=41j=86
i=41j=87
i=41j=91
i=41j=92
i=41j=93
at java.lang.Integer.parseInt(i=41j=94
Integer.java:596
i=41j=96
i=41j=106
)
i=41j=107
i=41j=108
i=41j=109
i=42j=44
i=42j=45
at sample.main(sample.java:17)
解决方案
Before parsing do the following steps with each array elements :
1. First trim it.
2. check the length. if greater zero then do the parsing otherwise not
this is a sample code hope it helps
use nextInt()
Scanner sc=new Scanner(new File("file location"));
int a,b,c;
a=sc.nextInt();
b=sc.nextInt();
System.out.println("a :"+a+" b:"+b);
Reading from a text file, means that you must use a FileReader stream. I suggest that you use a StreamTokenizer, wich takes as argument the FileReader stream. And by using this StreamTokenizer, you can decide if there is a end of line( TT_EOF method for the tokenizer ) and a white space. Noticing the white space will grant you the posibillity of retrieving the numbers.
Also you can use the method nestToken() to find the next character in the file.
Best regards.