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 (ie they'll both print 9's or something), my count
variable 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!
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;
}
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)
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)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.