0

我有一个包含内容的文件:

  • 85,70,95,82,75
  • 70,78,85,62,47,53,32
  • 99,88,75,85,69,72
  • 79,84,86,91,84,89,78,82,70,75,82
  • 56,68,0,56
  • 96,82,91,90,88

我需要使用 java Scanner 类编写代码以按以下顺序读取和输出代码:

  • 85,70,95,82,75
  • 85 70 95 82 75
  • 70,78,85,62,47,53,32
  • 70 78 85 62 47 53 32
  • 99,88,75,85,69,72
  • 99 88 75 85 69 72 等...

但是,我似乎无法让我的代码为我的一生工作,我无法弄清楚我不理解什么。我已经非常接近我的结果,但我已经尝试了很多解决方案,我只是放弃了。这是我拥有的当前代码。这几乎是我得到的最好结果。

import java.io.*;
import java.util.*;
public class FileIO
{
    public static void main(String[] args) throws IOException 
    {
        File fileObj2 = new File("Scores.txt");
        Scanner scan2 = new Scanner(fileObj2);
        String line = "";
        String x = "";      

        Scanner scan3 = null;
        scan3 = new Scanner(fileObj2);  
        scan3.useDelimiter(",");

        System.out.println();
        System.out.println("Second Files data below \n ------------- 
        ---------");
        while (scan2.hasNextLine()){
            line = scan2.nextLine();
            System.out.println(line);
            while (scan3.hasNext()){
                line2 = scan3.next();
                System.out.print(line2 + " " );
            }
        }
    }
}

这给了我输出

85,70,95,82,75
85 70 95 82 75
70 78 85 62 47 53 32
99 88 75 85 69 72
79 84 86 91 84 89 78 82 70 75 82
56 68 0 56
96 82 91 90 88 70,78,85,62,47,53,32
99,88,75,85,69,72
79,84,86,91,84,89,78,82,70,75,82
56,68,0,56
96,82,91,90,88
4

3 回答 3

1

您可以使用replace方法来获得所需的结果。请参阅下面的代码段供您参考。

String line = "87,88,89,90,91";
System.out.println(line);
System.out.println(line.replace(',',' '));
于 2019-11-17T06:11:50.487 回答
0

代码中的小改动,请在下面找到它们,

            while (scan2.hasNextLine()){
            line = scan2.nextLine();
            System.out.println(line);
            scan3 = new Scanner(line);
            scan3.useDelimiter(","); 
            while (scan3.hasNext()){
                System.out.print(scan3.next());
            }
        }
于 2019-11-17T06:33:06.490 回答
0

您可以使用该replaceAll方法删除逗号。

分数.txt:

85,70,95,82,75
70,78,85,62,47,53,32
99,88,75,85,69,72
79,84,86,91,84,89,78,82,70,75,82
56,68,0,56
96,82,91,90,88

代码:

Scanner in = new Scanner(new File("Scores.txt"));
while(in.hasNextLine()) {
        String line = in.nextLine();
        String out = line.replaceAll(","," ");
        System.out.println(line);
        System.out.println(out);
}

输出:

70,78,85,62,47,53,32
70 78 85 62 47 53 32
99,88,75,85,69,72
99 88 75 85 69 72
79,84,86,91,84,89,78,82,70,75,82
79 84 86 91 84 89 78 82 70 75 82
56,68,0,56
56 68 0 56
96,82,91,90,88
96 82 91 90 88
于 2019-11-17T16:47:46.770 回答