java 一次读取文件,如何从java中的文本文件中一次读取两个数字

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值