0

n.txt在格式的文本文件中有整数,2 列整数,各列用空格分隔。

我想读取这些整数并转义它们之间的空格并将这两个整数输入到 2 个单独的整数中。下面的代码用于解析String获得的。我想知道是否有任何String方法可以将它们拆分String为单独的数组并使用空白空间作为分隔符?

String URL="C:\\User\\Nimit\\Desktop\\n.txt";
File f = new File(URL);
FileReader inputF = new FileReader(f);
BufferedReader in = new BufferedReader(inputF);

int[] a= new int [1000];
int[] b= new int [1000];

String s =in.readLine();

while(s!=null)
{
    int i = 0;
    a[i] = Integer.parseInt(s,b[i]); //this is line 19

    //*not important*// System.out.println(a[i]);
    s = in.readLine(); 
}

in.close();

System.out.println("the output of the file is " +f);
4

4 回答 4

4

我建议你使用Scanner

Scanner s = new Scanner(new File(fileName));

int[] a = new int[1000];
int[] b = new int[1000];

int count = 0;
while (s.hasNextInt()) {
    a[count] = s.nextInt();
    b[count] = s.nextInt();
    count++;
}

s.close();
于 2012-06-08T10:52:31.823 回答
0

类的用户split()方法StringString arr[]="A B C".split(" ");

PS:既然你说这是一个新手提示。首先使用谷歌,大多数时候你会比在这里发布问题时更快地找到答案!并阅读 Java-doc,因为您可以在那里找到大部分答案。只需在谷歌搜索之前浏览一下,然后来这里或任何其他论坛提问。

于 2012-06-08T10:41:38.973 回答
0
int i=0;
s = in.readLine(); 
while(s!=null && i<1000) // your arrays can only hold 1000 ints
{
   String pair[] = s.split(" ");
   a[i] = Integer.parseInt(pair[0]);
   b[i] = Integer.parseInt(pair[1]);
   i++; // don't forget to increment
   s = in.readLine(); 
}

像这样的东西。

于 2012-06-08T10:50:35.910 回答