Click here to Skip to main content
15,892,575 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:
Java
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)
Posted
v5

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
 
Share this answer
 
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);
 
Share this answer
 
v3
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900