Mike
Mike

Reputation: 2313

Adding commas to output

This is what it does:

2,
4,
6,
8,
10

I would like for it to be horizontal: 2, 4, 6, 8, 10

        try    { 
            PrintWriter fout = new PrintWriter(new BufferedWriter(new FileWriter("numbers.dat"))); 
            for(int i = start; i <= 100; i = i + 2)    { 
                fout.println(i+","); 
            } 

Upvotes: 0

Views: 7743

Answers (5)

Buhake Sindi
Buhake Sindi

Reputation: 89169

In the write() method:

 for(int i = start; i <= 100; i = i + 2)    { 
    if (i > start) {
        fout.print(",");
    }

    fout.println(i); 
}

Then when you call output(), it will display as comma separated list. And for screen display

while((outputline = fin.readLine()) != null) { 
    System.out.print(outputline + " "); 
}
System.out.println();

Alternatively, skip saving the comma in the file and displaying will be as follows

int count = 0;
while((outputline = fin.readLine()) != null) { 
    if (count > 0)
        System.out.print(", ");

    System.out.print(outputline); 
    count++;
}
System.out.println();

Upvotes: 1

Jeremy
Jeremy

Reputation: 22415

Here is a very basic example of what you could do:

int max=11;
for(int i = 0; i < max; i += 2){
    System.out.print(i);
    if(i < max-2){
        System.out.print(", ");
    }
}

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

Another attempt

for(int i = start; i <= 100; i += 2) 
    System.out.print(i + (i > 98 ? "\n" : ", "));

Upvotes: 2

justkt
justkt

Reputation: 14766

If you mean to do it on printing to your .dat file:

 for(int i = start; i <= 100; i = i + 2) { 
     fout.print(i);
     if(i < 100) {
         fout.print(", ");
     } else {
         fout.println();
     }
  } 

If it is when printing to the system output after reading your file, try this:

      try    { 
        BufferedReader fin = new BufferedReader(new FileReader("numbers.dat")); 

            String outputline = ""; 
            StringBuilder result = new StringBuilder();
            while((outputline = fin.readLine()) != null)    { 
            result.append(outputline).append(", "); 
            } 
            int length = result.length();
            result.delete(length - 2, length);
            System.out.println(result);
            fin.close(); 
        } 

This uses a StringBuilder to build up your result and then removes the last , when it is done.

Upvotes: 1

blong824
blong824

Reputation: 4030

fout.println(i + ", ");  

System.out.println(outputline + ", ");  

This will give you commas after all the numbers but it looks like you don't need one after the final number.

You will have to remove the last comma either by using indexOf or checking for the last iteration of your loop.

Upvotes: 0

Related Questions