本文介绍了如何从java中的文本文件中一次读取两个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我只需要知道如何一次取两个数字作为文本文件的输入,因为我必须将这两个数字分配为i,j,以便我可以将它们与其他值进行比较

我的输入文件每行包含两个数字,用分隔,即

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几乎有1000双作为我的输入

这是到目前为止我的代码:



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);
	}
} }



我的问题是我能够打印i,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)

推荐答案


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);



这篇关于如何从java中的文本文件中一次读取两个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 02:34