Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Noobie problem  RSS feed

 
Pat Gareau
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I was writing a basic program to add 2 different numbers and display the result. I want it to give me the answer saying your answer is 15 on the same line. My program looks like this

class numbers
{
public static void main (String args[])
{
Num1 = 5;
Num2 = 10;
Num3 = Num1 + Num2;

System.out.println('' your answer is Num3'')
}
}

This might be slightly different but my program compiled after I added another system.out.print line to get one line saying this is your answer and another line underneath showing the result. How can I get it to give me the result on the same line ?
 
Aline Galea
Greenhorn
Posts: 22
2
IntelliJ IDE Java Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A question I can answer
You can create a string by adding a string literal ("You answer is ") and the value of a variable (num3) together. This is called concatenation. Look it up and try it out.
I like to advertise for this course, because it's completely free and taught me a lot about java. Going through week1 content will teach you everything you need to know about how to achieve what you want. When you're done you'll even be able to ask the user to input which two numbers they want to add up.

Have fun learning java.
 
Aline Galea
Greenhorn
Posts: 22
2
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aline Galea wrote:You can create a string by adding a string literal ("You answer is ") and the value of a variable (num3) together. This is called concatenation.

Actually this formulation is misleading. This isn't the definition of concatenation, it's just one of the things you can achieve with concatenation. Concatenation means joining two strings together.
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java® Language Specification =JLS answers that question: the + operator is overloaded. When it is applied to a String (left operand or right operand) and something else, the “something else” is converted to a String and then concatenated. If num3 is 15, it is converted to "15" which you do not see, and that is concatenated, which you can see with println.
Beware: the JLS can be difficult to read. You may wish to ignore the small writing in that link.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!