The Money Way
The Money Way

Reputation: 1

Java - Help needed with file reading and delimiter

I have a file with the contents :

I need to write a code using the java Scanner class to read and output the code in this order :

However, I cannot seem to get my code to work for the life of me and I can't figure out what I'm not understanding. I have gotten very close with my results but I have tried so many solution at this point I just gave up. This is the current code I have. Which is almost the best result I've gotten.

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

Which give me the output

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

Upvotes: 0

Views: 70

Answers (3)

Brian
Brian

Reputation: 21

You can use the replaceAll method to remove the commas.

Scores.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

Code:

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

Output:

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

Upvotes: 0

pavan kumar
pavan kumar

Reputation: 823

small changes in code, please find them below,

            while (scan2.hasNextLine()){
            line = scan2.nextLine();
            System.out.println(line);
            scan3 = new Scanner(line);
            scan3.useDelimiter(","); 
            while (scan3.hasNext()){
                System.out.print(scan3.next());
            }
        }

Upvotes: 0

Ash
Ash

Reputation: 473

You can use replace method to get the required results. See below snippet for your reference.

String line = "87,88,89,90,91";
System.out.println(line);
System.out.println(line.replace(',',' '));

Upvotes: 1

Related Questions