Search code examples
javaarraysfilewriter

Can't write number with FileWriter


This is my code and I want b[i] will be write to the file name test.txt but it is not working. It's just write something like symbols. Thanks for helping.

public class btl {
public static boolean IsPrime(int n) {

    if (n < 2) {
        return false;
    }

    int squareRoot = (int) Math.sqrt(n);
    for (int i = 2; i <= squareRoot; i++) {
        if (n % i == 0) {
            return false;
        }
    }
    return true;
}




public static void main(String args[]) {
    Scanner scanIn = new Scanner(System.in);
    int first = 0;
    int second = 0;
    try {
        System.out.println("Input First Number");
     first = scanIn.nextInt();
        System.out.println("Input Second Number");
        second= scanIn.nextInt();
    }
    catch(Exception e) {
        System.out.println("Something wrong!");
    }
    int x = first;
    int y = second;
    int a;
    int[] b = new int[y];

    Thread threadA = new Thread(new Runnable() {
        @Override
        public void run() {     
            int c=0;
            for(int i=x; i<y; i++) {   
                if(IsPrime(i)) {
                    b[c] = i;
                    System.out.println(b[c]);
                    c++;
               }
         }


        }
    });
    threadA.start();


    try(FileWriter fw = new FileWriter("test.txt")){

            for(int i =0; i<y; i++)
            {
             fw.write(b[i]);
            }
        }
    catch(IOException exc) {
        System.out.println("EROR! " + exc);
    }

}

}

This is my display console

And this is file "test.txt"

I don't know why FileWriter writes symbols in file text.txt. I want it's number of array b[i].


Solution

  • FileWriter.write(int) writes a single character. You likely want FileWriter.write(String)as in:

        fw.write(Integer.toString(b[i]));