0

I'm trying to compare a 4 digit String using charAt(x) to an integer in order to find out how many of that integer there is in the string.

public static boolean tickets(int numbers) {

int a = (numbers/100000);
int b = (numbers/10000) - a*10;
int c = numbers - a*100000 - b*10000;
int x = 0;
int count = 0;
String s = String.valueOf(c);

if (numbers/100000 == 0 || numbers/100000 > 9 ) { 
  return false;                                  
}
if (numbers <= 0) {
  return false;
} 

while (x < 4) {
  if (s.charAt(x) == a ) {
    count = count + 1;
  }
  x = x + 1;
      }

if (count == b) {
  return true;
} else {
  return false;
}}

I'm not going to insult anyone's intelligence and say this isn't a homework problem: it is. The prompt is to input a number (if negative, or not 6 digits, return 'false'). To get a return of 'true' the number has to have the first digit the second digit's number of times in the last for digits (what?!). For example, 121001 would return true since 1 occers 2 times in the last 4 digits.

Anyway, my problem is that even though s.charAt(x) will have the same value as a, at least when I print them out and check (i.e. they'll both print 9's or something), my countvariable doesn't seem to budge. Do I have a datatype mismatch? What can I do to fix this? Or have I approached this problem the wrong way entirely?

Thanks in advance!

Rafael
  • 3,096
  • 1
  • 23
  • 61
  • 1
    You want to read a little bit about the difference of primitive types. `charAt()` obviously returns a char value ... which yes, can be compared to an int number, but what exactly makes you think that the character "1" for example is "equal" to 1? [ hint: it is not ... you want to checkout on stuff like ASCII, codepages, and all the like ] – GhostCat Oct 15 '15 at 23:45
  • side note `(if negative, or not 6 digits, return 'false')` just need `if (numbers<100000){return false;}` no need of that calculations – Jorge Campos Oct 15 '15 at 23:46

3 Answers3

0

You have the data type mismatch. Character '0' does not equal to integer 0. One quick fix could be:

if (s.charAt(x) == a + '0' ) {
    count = count + 1;
}
Harvey Pham
  • 623
  • 4
  • 17
0

Your if condition is always false, because the data types do not match...

Try and use this as your if statements condition:

 if(Integer.parseInt(s.charAt(x)+"") == a)
RamanSB
  • 1,162
  • 9
  • 26
0

I would recommend reading through this: Convert from Integer to String.

Basically, you could create a new String variable called aString and set it to Integer.toString(a).

Community
  • 1
  • 1