• Post Reply Bookmark Topic Watch Topic
  • New Topic

I am trying to scan in 123456789 but rather than seeing it as such have 123 456 789 show  RSS feed

 
Peter Snowy Mack
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know very little aboout coding and less of Java
Logic says I should be able to do something like this:


Howsoever methinks my logic and ability do not sync
Any assistance would be greatly appreciated
TYIA
 
Campbell Ritchie
Marshal
Posts: 56587
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I have added code tags to your post. Always use them, and doesn't it look better.

I don't think the compiler will like that code. You cannot change the contents of a String object, least of all by using = like that. What happens is that you are getting the ith char in the String, which starts with 0x0031 (you think it is '1', but it isn't; it is a number 0x0031, which you can look up in this Unicode pdf). Now you have the number 0x0031, but you cannot assign anything to that without the compiler having a fit. You could have said that i is 0x0031, but if you try to assign to i, you don't affect the String.

If you cannot change Strings, you need to find something which you can change. Java® provides counterparts of some immutable classes, like String. You can find String's mutable counterpart here. I think you might do well simply to insert spaces in one of them. Remember that all the index numbers to the right or an insertion change. Remember the first index is 0, like a String, not 1.
 
Barry Burd
Author
Ranch Hand
Posts: 133
10
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java's StringBuffer class has a constructor to create a StringBuffer from a String. Once you have a StringBuffer, you can use one of the StringBuffer class's insert methods to insert single characters into the middle of the StringBuffer. Finally, if you want to get a String back from the StringBuffer, you can use one of the String class's constructors to create a String from your (newly created) StringBuffer.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Barry Burd wrote:Finally, if you want to get a String back from the StringBuffer, you can use one of the String class's constructors to create a String from your (newly created) StringBuffer.

Or you could just call the StringBuffer's toString method.

 
Campbell Ritchie
Marshal
Posts: 56587
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would use StringBuilder in preference to StringBuffer; they both work very similarly to each other. I would get a string from a builder with its toString method, as Joanne N has already said.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!