¿Cómo escribir π (pi) en Java?

Is there a character within the Math API that allows for representing the character π?

preguntado el 01 de febrero de 12 a las 01:02

Oh sorry, in a JOptionPane.showMessageDialog(null, String) with the pi character in the string. But Louis below has answered it. :) -

The correct character for representing π is of course π itself. Don’t use ugly escapes that confuse people. Just use UTF-8 for your source. -

3 Respuestas

You don't even need to use the Math API. In Java source code, this:

\u03C0

es equivalente a esto:

π

and you can even use it in an identifier; these two are equivalent:

final String \u03C0 = "\u03C0";
final String π = "π";

(As the spec puts it:

A Unicode escape of the form \uxxxx, Donde xxxx is a hexadecimal value, represents the UTF-16 code unit whose encoding is xxxx. This translation step allows any program to be expressed using only ASCII characters.

Consulte nuestra página http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#3.2.)

Respondido 01 Feb 12, 05:02

I didn't know you can use Unicode chars for variables. Ha, that would be a nice way to annoy my coworkers - Luciano

Just enter it in real UTF-8. You have to compile with -encoding UTF-8, but so it goes. At least now it can be read. - tchrist

Indeed. People seem not to realize that (e.g.) "a" is a Unicode character. - user10762593

If you want to write this to a file you can achieve it through Unicodes, below is an example of how,

import java.io.*;
public class Test {

    public static void main(String[] args) throws Exception{
        BufferedWriter out = 
                    new BufferedWriter(new OutputStreamWriter(
                          new FileOutputStream("out.txt"),"UTF8"));     

    out.write("alpha = \u03B1, beta = \u03B2 ,pi = \u03C0");
    out.flush();
    out.close();
}
}

out put : alpha = α, beta = β ,pi = π

Respondido 01 Feb 12, 05:02

out.write("alpha = α, beta = β, pi = π") seems more straightforward. - user10762593

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.