Reputation: 148
just doing an assignment and to sum it up: I need to get a users ID which is an int and make sure the first number is 4.
I have tried to do this by converting the id (int from the object in the main method) into the char array.
I print out the index[0] to console and it says 4, great right?
But i have made an if statement that then says if index[0]of the array is 4 then do something... it doesn't seem to acknowledge index 0 is 4 and proceeds to do whats in the else block.
public boolean checkID()
{
int convert = getId(); //get id is 44444
char[] idArray = String.valueOf(convert).toCharArray();
System.out.println(idArray[0]); // this returns a value of 4 in the console
boolean check = false;
if(idArray[0] == 4)
{
check = true;
System.out.println("Id starts with 4!");
}
else
{
check = false;
throw new IllegalArgumentException("Id does not start with 4");
}
return check;
}
}
Of course in the console i receive the illegal argument exception but also 4 printed out? Sorry if this is a silly problem i have been looking at it for so long and its abit blurry now haha! Possibly there is a better way? Thanks in advance!
Upvotes: 2
Views: 50
Reputation: 679
You are trying to compare an int
with a char
.
You have converted your int
to an array of char
, so the right way to see whether the first element in your array is equal 4 or not, you need to make it a char and put it inside single quotes like this:
if(idArray[0] == '4')
{
check = true;
System.out.println("Id starts with 4!");
}
Thanks!
Upvotes: 2