Reputation: 606
I want to know if there is something similar to (input==(letters[i]-'c')) that i can use. I know what i type doesn't make sense but i'm trying to create something similar to that. If the user's input is anything in the array but c, then it displays the first message, else if it is c, then it displays the second message. I just want to somehow temporarily exclude c from the array and have the program check all other elements...
char []letters={'a','b','c','d'};
//input is user input
for(int i=0;i<letters.length<;i++)
if(input==(letters[i]-'c'))
{
system.out.print("input might be a,b,d but not c");
}
else if(input=='c')
{
system.out.print("input is c");
break;
}
Upvotes: 0
Views: 299
Reputation: 11065
String str=Arrays.toString(letters).replaceAll("\\s*\\[*,*\\]*", "");
if(input=='c') {
system.out.println("input is c");
}
else if(str.contains(""+input)) {
system.out.print("input might be a,b,d but not c");
}
Upvotes: 0
Reputation: 15552
You could convert it to a list and then use the contains method
This will return true or false. You can use this in your if statement.
eg
if (Arrays.asList('a', 'b', 'c').contains('c')) {
System.out.print("input might be a,b,d but not c");
}
else {
System.out.print("input is c");
}
(btw your code sample does not compile. System
should have a capital letter)
Upvotes: -1
Reputation: 14243
Try the following:
Arrays.sort(letters);
if (Arrays.binarySearch(letters, 'c') >= 0) {
// contains 'c'
} else {
// doesn't contain 'c'
}
Please note that the call to binarySearch
requires the array to be sorted first, hence sort
.
Upvotes: 4
Reputation: 533790
Normally what you would do is use a String for text.
//input is user input
String letters = "abcd";
if (letters.contains("c"))
System.out.print("input contains c");
else
System.out.print("input doesn't contain c");
Upvotes: 0