3

I am trying to write the instructions to notice when circle is about to be 12 and then add 1 to square.

The code below works fine for me

   int x = Integer.parseInt(circle.getText()); 
   x = x + 1;
   String z = Integer.toString(x);
   circle.setText(z);

However, I am having trouble with these new instructions I am trying to write. How can I get square, convert to integer, add 1 and then put the value back?

   int q = Integer.parseInt(square.getText());
   x = q + 1;
   square.setText(x);
3
  • setText(x) takes String as argument. Your x is int. Commented Nov 9, 2014 at 12:17
  • 2
    The answer is in the first snippet: convert the int to a String. Commented Nov 9, 2014 at 12:17
  • In the first snippet you do Integer.toString(x). In the second you do not. Why do you think it's not required. Commented Nov 9, 2014 at 12:19

4 Answers 4

8

You can convert to String using Integer.toString() :

square.setText(Integer.toString(x));
Sign up to request clarification or add additional context in comments.

Comments

2
square.setText(x+"")

Will work

Comments

0

Why would an int be convertible to a String (unless an implicit conversion exists, which is not the case, there is not a lot of implicit things with the Java compiler, primitive wrappers and string concatenation apart) ?

Use one of these two options :

square.setText(String.valueOf(x));
square.setText(x + "");

2 Comments

honestly... I'm kind of new to Java as well and didn't understand (and really I still don't) why something that can be printed to the screen doesn't have an implicit conversion. I know you said Java omits a lot of conversions that happen implicitly in other languages, but why do they? It doesn't seem like you lose any data... Could you possibly update your answer to shed some light on this?
Printing things out and concatenating strings is a special case where the compiler will automatically add string conversions, but that's the only place. Everywhere else, you have to use types rigorously.
-1

Using your own code String z = Integer.toString(x); square.setText(z);

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.