I'm very new to Java and am having some difficulty wrapping my head around when to do what and so forth. My current assignment is to input a number and have it reversed. I believe that I have the correct code but my out put does not want to place spaces between the entry and the result. I've researched what may be the issue and I believe it has to do with the printf format and adding in ""+ between the text, entry and result but that does not seem to be working. Hence, I'm probably not correct. I thought that "" would add in spaces so that my output would read correctly. Here is my code and result. Any help would be appreciated.
Enter the number to be reversed : 456
The reverse of456is654
Brian Halpin wrote:I thought that "" would add in spaces so that my output would read correctly.
How would a simple string concatenation know what you had in mind for spacing "correctly"? All it can do is to concatenate the strings it's given. Inserting spaces you didn't ask for would be a bad idea. (It would be even harder for the printf method to examine the string, intuit where you wanted spaces to appear, and insert those spaces.)
However it's very simple for you to put in the spaces yourself, because you know where you want them to go. Try this change:
You'll find it still doesn't insert all of the spaces you want, but you should be able to fix it now.
Welcome to the Ranch Please look here about how the code button works; since you are new I have corrected your tags and doesn't the ode look better
Here is what is should look like:
Sinve entry and result are ints, I would use %d, and I would add a %n at the end, otherwise you stay on the same line:-Beware: the technique using % can be unpredictable for negative numbers. I think that using 10 * will give you a correct output for negative numbers, but I am not certain.
Like I said, using concatenation with printf() is NOT the way to do it. That's kind of like trying to cut wood with a power saw by swinging it back and forth without turning it on. Or using an electric toothbrush like you would a regular toothbrush. You're basically doing all the work the method was designed to do for you.
The overall mission is to change the world. When you've done that, then you can read this tiny ad: