Michael Michael - 11 months ago 54
Java Question

Having trouble with charAt()

I'm trying to make a little text box that accepts an input, converts it to an int, then returning that index in the value of pi. Example if I input 6, I want back 9, because 3.14159 the sixth value is 9.

This is what I got so far, and it works but the outcome doesn't make any sense.

This is the only area of interest (Note: Input is an int):

_tfield.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent arg0) {
input = Integer.parseInt(_tfield.getText());
_tfield.setText("Input: "+ input+" Output: "+ output(input));

private int output(int input) {
String pi = Double.toString(Math.PI);
return pi.charAt(input+1);

The answer I get for the input "5" is 57, which doesn't make any sense because I'm asking it for 1 char value. Even stranger, is if I remove the +1 from the charAt arguments, (and still input 5) I get 53.

I don't know what's wrong, but I feel like its charAt because its always tricky to use. However, I could be wrong, any suggestions would be helpful. Thanks.


Because return type of your method private int output(int input); is int that's why it's returning ascii value of the character.

change your return type to char to get desired output.