Jump to content

A simple and wierd (?) string problem

- - - - -

  • Please log in to reply
5 replies to this topic

#1
skypower

skypower

    Learning Programmer

  • Members
  • PipPipPip
  • 31 posts
I have
String in // taken from a single readline() input
then I have a check
 if (Character.isDigit(in.charAt(i)))
which is, let's say, true and then
for (int j = 1; j <=  (in.charAt(i)); j++) {
             System.out.println(""int "+ (int) in.charAt(i)+ "-"+in.charAt(i)); // for testing purposes 
        }
the i is standard in this example, say 5 and the charAt(i) is obviously a number since we passed the check, say 3

the program is supposed to get in the j loop 3 times, but instead it goes around 49-53 times (I changed the program and input and got various results)

What's wrong? :crying:

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Characters are very closely related to integers.
Check Ascii Table - ASCII character codes and html, octal, hex and decimal chart conversion
There are 2 important columns there 'DEC' and 'CHAR'
When you have char '3' in there, look in 'DEC' and there is the amount of times it will loop (51 for '3')

That is because you can't simply use a char as if it was an integer. You have to parse it by doing:
int number = Integer.parseInt(c + "");
Where c is a char variable. I do + "" to turn the char in a String.

#3
skypower

skypower

    Learning Programmer

  • Members
  • PipPipPip
  • 31 posts
Thank you Wim, I didn't know that. So in the code you showed you basicaly convert a char in a string in the parentheses and then convert that string in an int?

By the way, I found another solution before I saw your response.
in.charAt(i) -'0'
in the j loop

#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Or you can do "-48" aswell ;)

#5
skypower

skypower

    Learning Programmer

  • Members
  • PipPipPip
  • 31 posts

wim DC said:

Or you can do "-48" aswell ;)
I guess you mean - "48" but the compiler won't let me do that, besides I am already confused with - '0' and this trick :P I will have to spend some time to learn those thingies.

#6
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
No, I really mean -48, as you see in the ascii table '0' is equal to 48.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users