Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The text file that I am saving in Java is coming out wrong

I am creating a program that saves the first X prime numbers but when I save the ArrayList to a text file the list is completely wrong. Here is my code:

import java.util.Scanner;
public class Class1
{
  // This method tests whether a given number is prime or not.
   public boolean isPrime ( int num )
 {
boolean prime = true;
int limit = (int) Math.sqrt ( num );  

for ( int i = 2; i <= limit; i++ )
{
  if ( num % i == 0 )
  {
    prime = false;
break;
  }
}

return prime;
}

public static void main ( String[] args )
 {
  Class1 ob1=new Class1();
System.out.println("Where do you want to stop?");
Scanner scan = new Scanner(System.in);
int y = scan.nextInt();
for ( int i = 2; i <= y; i++ )
{
  if ( ob1.isPrime ( i ) )
System.out.println ( i );
  }
 }
 }

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;


 public class Output {
    public static void main(String args[]) throws IOException {
 Class1 obj = new Class1();OutputStream outputstream = new FileOutputStream("write.txt");
 Writer writer1 = new OutputStreamWriter(outputstream);

 try{

 int max =100;
  List<Integer> record = new ArrayList<Integer>(max);


  // Going write in this file

  for ( int i = 2; i <= max; i++ )
  {
   if ( obj.isPrime ( i ) )
    System.out.println ( i );
    record.add(i);

    } 
   for(Integer str: record){
   writer1.write(str);
    }

    }catch(IOException e){

    }finally{writer1.close();}
    }

   }

And this is what the text file looks like:

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\
like image 1000
c0de_n00b Avatar asked Dec 11 '25 17:12

c0de_n00b


2 Answers

You are calling Writer.write(int), which interprets the integer as a Unicode code point. Use str.toString() to force the argument into a String. After you do that, you are probably going to wish for some newlines as well. I suggest wrapping everything in a PrintWriter and using println on it.

like image 53
Marko Topolnik Avatar answered Dec 14 '25 07:12

Marko Topolnik


There's two issues. One is the code point issue Marko points out above.

The other is

if ( obj.isPrime ( i ) )
    System.out.println ( i );
    record.add(i);

Your if statement only covers the system.out.println - it doesn't also cover the record.add since it has no brackets.

Consider this instead:

if ( obj.isPrime ( i ) ) { // notice the curly bracket
    System.out.println ( i );
    record.add(i);
} // notice the curly bracket
like image 32
corsiKa Avatar answered Dec 14 '25 07:12

corsiKa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!