Question:
In Java Programming, I've declared three string variables n1, n2, n3. When I try to System.out.print(n1 + n2 + n3); I get an error. Why?
Brandon
2015-02-17 19:52:57 UTC
I'm trying to compare these variables. I don't understand why I keep on getting an error. The three variables are declared using the Scanner input class so whatever the user inputs will be what is contained within n1, n2, and n3. Again, when I try to output these variables using System.out.print(n1 /n + n2 /n + n3 /n); I get multiple errors...
Four answers:
?
2015-02-17 20:41:53 UTC
You want

System.out.print(n1 + "\n" + n2 + "\n" + n3 + "\n");



n1, n2, and n3 are Strings. So in order to put in a line break, you need to concatenate "\n" to them.



In your original code, you have:

n1 /n + n2 /n + n3 /n



First of all, /n is not correct. You're basically telling the compiler you want to compute n1 / n (a division operation), n2 / n, and n3 / n, and then add the results together. If the variable n doesn't exist, well, that's one error right there. Furthermore, even if you did have a variable called n, n1, n2, and n3 are Strings, and naturally it doesn't make sense to divide Strings by a number. Type mismatch.



So by doing

n1 + "\n"

you're taking the String stored in n1, concatenating it with "\n" (the character for line break, not "/n"), and then printing the result. Same goes for n2 and n3.
husoski
2015-02-17 20:37:49 UTC
Why not just use three System.out.println() calls? That way, Java doesn't have to concatenate them into a combined string variable just to get them all output in one call. Method calls are not cheap, but five string concatenations are more expensive than two extra method calls.



System.out.println(n1); // the easy, obvious way

System.out.println(n2);

System.out.println(n3);



If you want to concatenate, no1home2day & Sbm showed you how.



Another option is to use the printf() method:



System.out.printf("%s\n%s\n%s\n", n1, n2, n3);



...but that's probably more expensive than concatenation, due to parsing the format string.
no1home2day
2015-02-17 19:58:14 UTC
These are string variables?



Just something to think about: what happens in Java when you add strings (n1 + n2), and is that the correct method of concatenation for Java? (Maybe it is, but I thought it was something else, similar to string concatenation in C# ???)



Also, can you just put /n between one variable and the next? I mean, you have "n1 /n + n2 /n ... " Shouldn't that rather be (assuming + is correct), "n1 + '/n' + n2 + '/n' + ... " ?



Just a few things to consider. Maybe something here will help.
Sbm
2015-02-17 19:57:11 UTC
Try

System.out.print(n1 + "\n" + n2 + "\n" + n3 + "\n");


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...