Home > front end >  The correlation between bufferedwrite and n characters
The correlation between bufferedwrite and n characters

Time:01-03

public class SieveOfEratosthenes_re {
    public static void main(String[] args) throws IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        int N = Integer.parseInt(br.readLine());
        int K = Integer.parseInt(br.readLine());
        int count = 0;

        boolean[] arr = new boolean[N 1];
        for(int i=2; i<=N; i  ){
            if(count==K){
                break;
            }
            for(int j=i; j<=N; j =i){
                if(arr[j]==false){
                    arr[j] = true;
                    count  ;
                }
                if(count==K){
                    bw.write(j   "\n"); // I don't know this part
                    break;
                }
            }
        }
        bw.flush();
        bw.close();
    }
}

If n is added to the bufferedwrite, it is output from the terminal, and if n is not added, it is not output. What's the reason?

CodePudding user response:

You apparently want to know what this line does:

  bw.write(j   "\n");

The first thing that happens is that j "\n" is evaluated. Since one of the operands is a string, that is a string concatenation (see JLS 15.18.1). The value of the other operand is converted to a String as if you called new String(int) on it (see JLS 5.1.1). That renders it in decimal format.

For example, if j was 42, the result of that will be a string equivalent to "42\n"; i.e. 3 characters.

Then Writer.write(String) is used to output the string which just writes the characters of the string (see javadoc


Your self answer says:

Bufferedwrite receives characters, so if you type int, it outputs an empty value.

It it hard to understand exactly what you mean, but if you are saying BufferedWriter.write(int) outputs an "empty value", that is incorrect. The Writer.write(int) method interprets the int as a Unicode codepoint and outputs that ... according to the encoding of the output stream you are writing to.

That is NEVER an empty value.

It might be a non-printing character (e.g. an ASCII control character), but even those are not empty. There will be something in the output stream.

CodePudding user response:

I solved it. Bufferedwrite receives characters, so if you type int, it outputs an empty value.

  •  Tags:  
  • java
  • Related