0

我正在编写一个代码,它从一个文件中读取输入并在经过一些处理后写入另一个文件。现在,我的输入文件是,

4
0 1
0 2
0
0 3
3
0
0
0
E

我需要做的是将左侧的元素复制到第一列的数组,将右侧的元素复制到第二列。我使用了扫描仪,但它无法识别行尾。帮我!!!!这就是我尝试过的。我尝试复制行然后修改它。

for (i = 0; i < size; i++) {
    if (!f1.hasNext(endPage)) {
        String temp1 = f1.next();

        String temp2 = f1.next();

        int a[] = new int[4];
        a[0] = (int) temp1.charAt(temp1.length() - 1);
        a[1] = (int) temp2.charAt(temp1.length() - 1);
        a[2] = (int) temp1.charAt(temp1.length() - 2);
        a[3] = (int) temp1.charAt(temp1.length() - 2);
        scales[i].weightOnLeft = a[0];
        scales[i].weightOnRight = a[1];
        scales[i].left = scales[a[2]];
        scales[i].right = scales[a[3]];

    }
}
4

3 回答 3

0

尝试如下:- 在您的第一列中,它将存储在数组 [0] 中,第二列值将存储在数组 [1] 中。同样对于第二列,您需要检查如下所示的条件。请关注:-

    File file=new File("/Users/home/Desktop/a.txt");
    String[] aa=new String[2];
    try {
        Scanner sc=new Scanner(file);

        while (sc.hasNextLine()) 
        {
            String ss=sc.nextLine();
            aa=ss.split("\\s");
//it will store left column value in this index
            System.out.println("aa[0]"+aa[0]);
            if(aa.length>1) 
            {
//it will store right column value in this index
            System.out.println("aa[1]"+aa[1]);
            }

        }
    }
于 2013-10-10T14:52:44.990 回答
0

试试这个方法:

Scanner input = new Scanner(new File("..."));
while(input.hasNextLine())
{
   String data = input.nextLine();
}
于 2013-10-08T09:41:04.077 回答
0

尝试使用扫描仪逐行读取,然后拆分(在空间上,在您的情况下)您的行以获取令牌。

Scanner f1 = new Scanner(new File("yourFileName.extn"));
while(input.hasNextLine()) {
   String line = f1.nextLine();
   String[] tokens = line.split(" "); // Splitting on space
   // Do what you want with your tokens
   // Since not all lines have equal no. of tokens, you need to handle that accordingly
}
于 2013-10-08T09:42:56.713 回答