Java 在System.out.write()语句中使用char和int

Java 在System.out.write()语句中使用char和int,java,system.out,Java,System.out,我想为下面的节目提出两个问题 class WriteDemo{ public static void main(String args[]){ int b; b = 'x'; System.out.write(b); System.out.write('\n'); } } 如何将字符'x'用于整数变量b 屏幕上显示的程序结果为x。如果我删除最后一行System.out.write('\n')屏幕上不显示任何内容。 为什么会这样 按相反的顺序

我想为下面的节目提出两个问题

class WriteDemo{
    public static void main(String args[]){

    int b;

    b = 'x';

    System.out.write(b);
    System.out.write('\n');
   }
}
  • 如何将字符
    'x'
    用于整数变量b
  • 屏幕上显示的程序结果为x。如果我删除最后一行
    System.out.write('\n')屏幕上不显示任何内容。
    为什么会这样
  • 按相反的顺序

    屏幕上显示的程序结果为x。如果我删除了最后一行System.out.write('\n');屏幕上没有显示任何内容。 为什么会这样

    因为“\n”刷新输出缓冲区。你也可以用

    System.out.write(b);
    System.out.flush();
    
    你的第一个问题,

    变量b是一个整数,我们如何使用字符“x”来表示它

    为扩阔-

    19基元类型的特定转换称为扩展基元转换:

    char
    int
    long
    float
    ,或
    double

    按相反的顺序

    屏幕上显示的程序结果为x。如果我删除了最后一行System.out.write('\n');屏幕上没有显示任何内容。 为什么会这样

    因为“\n”刷新输出缓冲区。你也可以用

    System.out.write(b);
    System.out.flush();
    
    你的第一个问题,

    变量b是一个整数,我们如何使用字符“x”来表示它

    为扩阔-

    19基元类型的特定转换称为扩展基元转换:

    char
    int
    long
    float
    ,或
    double

    当你跑的时候

    System.out.write(b);
    
    您实际上是在PrintStream类中调用此方法

    /**
     * Writes the specified byte to this stream.  If the byte is a newline and
     * automatic flushing is enabled then the <code>flush</code> method will be
     * invoked.
     *
     * <p> Note that the byte is written as given; to write a character that
     * will be translated according to the platform's default character
     * encoding, use the <code>print(char)</code> or <code>println(char)</code>
     * methods.
     *
     * @param  b  The byte to be written
     * @see #print(char)
     * @see #println(char)
     */
    public void write(int b) {(...)
    
    因此,如果您显式刷新打印机(或打印换行符,如javadoc中所述),您将看到“x”

    关于使用“x”作为整数,我假设您讨论的是x代表什么整数以及如何打印它

    注意,如果你这样做了

    System.out.println(b);
    
    它将显示120,因为println将在运行时调用String.valueOf(b)

    System.out.write(b);
    
    您实际上是在PrintStream类中调用此方法

    /**
     * Writes the specified byte to this stream.  If the byte is a newline and
     * automatic flushing is enabled then the <code>flush</code> method will be
     * invoked.
     *
     * <p> Note that the byte is written as given; to write a character that
     * will be translated according to the platform's default character
     * encoding, use the <code>print(char)</code> or <code>println(char)</code>
     * methods.
     *
     * @param  b  The byte to be written
     * @see #print(char)
     * @see #println(char)
     */
    public void write(int b) {(...)
    
    因此,如果您显式刷新打印机(或打印换行符,如javadoc中所述),您将看到“x”

    关于使用“x”作为整数,我假设您讨论的是x代表什么整数以及如何打印它

    注意,如果你这样做了

    System.out.println(b);
    
    它将显示120,因为println最终将调用String.valueOf(b)

    的可能重复