0

I have this code here I want to use. I basically want to use string and variable together but save it in a variable

Int a = 27;
Int b = 22;
String question = System.out.println("what is " + a + "+" + b);

System.out.println(question);
property website
  • 41
  • 1
  • 1
  • 3
  • 11
    `String question = "what is " + a + "+" + b + "\n";` – Eran Nov 28 '18 at 11:18
  • `String question = "what is " + a + "+" + b;` – Farvardin Nov 28 '18 at 11:18
  • 1
    println() method return type is void. In your code you are expecting return value from it eg: "String question = System.out.println("what is " + a + "+" + b);" cause of this conpile time error. try this String question = "what is " + a + "+" + b + "\n"; –  Nov 28 '18 at 11:19
  • Unless you want to do something fancier, in which case you can use [`String::format`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#format(java.lang.String,java.lang.Object...)) – Federico klez Culloca Nov 28 '18 at 11:19
  • Or String.format("What is %d + %d", a, b); – Joakim Danielson Nov 28 '18 at 11:19
  • Or, `MessageFormat#format()` as: `String question = MessageFormat.format("What is {0} + {1}, a, b)` – Prashant Nov 28 '18 at 11:21
  • This is what you're Looking for: [Redirect-stdout-to-a-string-in-java](https://stackoverflow.com/questions/4183408/redirect-stdout-to-a-string-in-java) – comrad Nov 28 '18 at 11:21

4 Answers4

2

You can easily concat strings for a variable like you do it in System.out.println.

So

String question ="what is " + a + "+" + b;

would do the job.

TheWildHealer
  • 1,546
  • 1
  • 15
  • 26
SAM
  • 742
  • 10
  • 24
2

You are trying to assign the return value of System.out.println("what is " + a + "+" + b); to your variable question, however, System.out.println does not return anything. You have to first creat your variable, and then print it, like so :

Int a = 27;
Int b = 22;
String question = "what is " + a + "+" + b;

System.out.println(question);
TheWildHealer
  • 1,546
  • 1
  • 15
  • 26
1

Remove the System.out.println() from the string variable question. So, String question = "what is " + a + "+" + b; When u want toask the question print the variable question with System.out.println()

1

Try this instead, Use String concatenation:

Int a = 27;
Int b = 22;
String questionStr = "what is " + a + " + " + b;
System.out.println(questionStr);