I need this program to keep on asking for cardChosen1, until the user gives an answer of something between 'a' and 'h'. I know I could just put
while (cardChosen1 == 'a' && cardChosen1 == 'b' && cardChosen1 == 'c' &&...
Etc. But I would prefer there to be a more concise way. I want it not only block letters, but also symbols and numbers
I've tried the following:
while (cardChosen1 > 'a' && cardChosen1 < 'h')
{
System.out.println ("Hey");
cardChosen1 = e.getKeyChar ();
}
But it doesn't work.
You're almost there. The problem is that you loop while you do get an answer between 'a' and 'h', and you wanted to loop as long as you don't get such an answer. Just slap on a negation operator (!), and you should be fine:
while (!(cardChosen1 > 'a' && cardChosen1 < 'h')) {
Better yet, you can simplify this statement with some boolean algebra:
while (cardChosen1 <= 'a' || cardChosen1 > 'h')) {
this condition is universally false
while (cardChosen1 == 'a' && cardChosen1 == 'b' && cardChosen1 == 'c' &&...
this condition will work but I would prefer you to create a Set<Character> and look up if it exists in Set by contains()
while (cardChosen1 > 'a' && cardChosen1 < 'h')
First of all, the right form of what you typed above as the suggested answer has to be like this:
while (cardChosen1 == 'a' || cardChosen1 == 'b' || cardChosen1 == 'c' || ... || cardChosen1 == 'h')
because you need a character to be "a" or "b" or "c" ... but what you entered wants the character to be all of characters from 'a' to 'h' which is impossible.
Now for your concise way. You are close to the answer and with some minor changes it will work. But it's more readable (in Java) to use Explicit Type Cast (of course it's optional). Like this:
while ((int) cardChosen1 >= (int) 'a' || (int) cardChosen1 <= (int) 'h')
Also notice about >= and <= signs as you accept the answer if it's 'a' or 'h' itself.
And finally you must convert && to || as I explained above.
You should check for ASCII codes.
for example if you want to check a to h range try
(int)cardChosen1 > 97 || (int)cardChosen1 < 122
Related
So my counter is supposed to not count +1 for the string ":DD" that's why I wrote that only if the length of my string is 2 the counter should add +1. But it adds +1 although the string length is 3. Why is that?
P.S.: I've put length() <=3 in the first if statement, for another else if that comes after the 2nd if statement.
int counter = 0;
String tgt = ":DD";
for (int i = 0; i < a.size(); i++) {
if (tgt.length() <= 3 && tgt.charAt(0) == ':' || tgt.charAt(0) == ';') {
if (tgt.length() == 2 &&
tgt.charAt(1) == ')' || tgt.charAt(1) == 'D') {
counter += 1;
}
}
}
The && operator has higher precedence than ||, messing up your intended logic.
The Java operators page lists Java operators in order of precedence.
Because of this, it's as if parentheses are around the two && operands:
if ((tgt.length() <= 3 && tgt.charAt(0) == ':') || tgt.charAt(0) == ';')
{
if ((tgt.length() == 2 && tgt.charAt(1) == ')') || tgt.charAt(1) == 'D')
In the second if condition, the && may return false, but the second (index 1) character is 'D', so the whole condition is true and your counter gets updated.
Place explicit parentheses around your || operands, which is what I think you intended.
if (tgt.length() <= 3 && (tgt.charAt(0) == ':' || tgt.charAt(0) == ';'))
{
if (tgt.length() == 2 && (tgt.charAt(1) == ')' || tgt.charAt(1) == 'D'))
This is a case operator precedence (source: oracle.com) not matching with the expectations we as developers might have. The &&-operator has a higher precedence than ||. This means that
tgt.length() <= 3 && tgt.charAt(0) == ':' || tgt.charAt(0) == ';'
evaluates to the same value as
(tgt.length() <= 3 && tgt.charAt(0) == ':') || tgt.charAt(0) == ';'
(Notice the parentheses around (... && ...))
If we want that the ||-operator is evaluated first, we have to add explicit parentheses:
tgt.length() <= 3 && (tgt.charAt(0) == ':' || tgt.charAt(0) == ';')
(Notice the parentheses around (... || ...))
(likewise with the 2nd if-condition)
Ideone demo
The problem seems to be that your second if isn't correctly set.
If I understand correctly you want to check if the second letter is a ")" or a "D" unless the length is of two.
what your checking is if it's length = 2 and 2nd letter ")" OR that the second letter is simply equal to a "D"
you would fix it by changing the if to if ((&& tgt.charAt(1) == ')'|| tgt.charAt(1) == 'D') && tgt.length() != 2) {
I am new to Recursions. I am not able to solve the below problem.
Problem: Print the consonants in the string using Recursion. I don't know how the program is printing all alphabets even after giving if condition.
public static void countCons(String str, int index) {
if (index >= str.length()) {
return;
}
char x = str.charAt(index);
if (x != 'a' || x != 'e' || x != 'i' || x != 'o' || x != 'u') {
System.out.println(x);
}
index = index + 1;
countCons(str, index);
}
You should have use && operator instead of || operator
Replace
if(x!='a'||x!='e'||x!='i'||x!='o'||x!='u')
with
if (!(x == 'a' || x == 'e' || x == 'i' || x == 'o' || x == 'u'))
or with
if (x != 'a' && x != 'e' && x != 'i' && x != 'o' && x != 'u')
Let's find the problem with your approach:
Let's assume str is "aka".
When index is 0, x = 'a', and therefore x!='a'||x!='e'||x!='i'||x!='o'||x!='u' is being evaluated as
'a'!='a'||'a'!='e'||'a'!='i'||'a'!='o'||'a'!='u' => false || true || 'a'!='i'||'a'!='o'||'a'!='u' => true
When index becomes 1, x = 'k', and therefore x!='a'||x!='e'||x!='i'||x!='o'||x!='u' is being evaluated as
'k'!='a'||'k'!='e'||'k'!='i'||'k'!='o'||'k'!='u' => true || 'k'!='e'||'k'!='i'||'k'!='o'||'k'!='u' => true
Note that as soon as multiple conditions are connected with ||, the evaluation stops as soon as the first true condition is found, and the result is concluded as true. The result is concluded as false only when none of the conditions evaluates to true.
On the other hand, when multiple conditions are connected with &&, the evaluation stops as soon as the first false condition is found, and the result is concluded as false. The result is concluded as true only when all the conditions evaluates to true.
So I'm trying to write this in a short way:
char letter;
while ( letter!='A' && letter!='B' && letter!= 'C... letter!= 'a'
&& letter !='b' && letter!=c)
Basically if the user does not input a letter between A and C, a while loop will run until A,B,C,a,b,c is inputted.
It should be in the form of
while(letter<'a' && letter > 'c')
but it didn't work apparently because if I inputted F, is it greater than 'C', but it is less than 'c', since char uses ACSII.
There are many ways to do this check.
char letter;
while (!(letter >= 'A' && letter <= 'C') && !(letter >= 'a' && letter <= 'c'))
Or you can use Character.toUpperCase or toLowerCase on the letter first, to remove half of the conditions.
Or, if the range of letters is small or non-contiguous, you could do:
char letter;
while ("ABCabc".indexOf(letter) == -1)
There are more ways of course.
Set letter to lower case and then check:
letter = Character.toLowerCase(letter);
while (letter < 'a' && letter > 'c') {
// ...
}
This way, even if the user enters an upper case letter, the check will work.
You need two conditions and a bit of de Morgan:
while(!((letter >= 'A' && letter <= 'C') || (letter >= 'a' && letter <= 'c')))
or good old regex
char input = 'B';
Pattern p = Pattern.compile("a|b|c", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("" + input);
if (m.find())
{
System.out.println("found");
}
You can check with ASCII code of characters such as 65 for 'A' and 97 for 'a'. So you could do if (letter > 65) to check if letter greater than 'A'. Hope this helps.
Updates :
For checking if letter is only either of A,B,C,a,b,c, use this check : if (letter >= 65 && letter <= 67) || (letter >= 97 && letter <= 99) .
Please mark as answer if this helps.
I have this code:
int i;
for (i = 0; i < 13; ++i) {
if (hand[i].charAt(0) == 'A' || 'B' && hand[i].charAt(1) == 'C')
System.out.println(hand[i]);
}
Basically what I want this to do is if the character at index 0 in each array element is either A or B, AND the character at the second index in each array element is C, I want those elements to be printed. It works with one character, but when I put the or in the first part, it gives me this error: "bad operand types for binary operator '&&'". How do I fix this problem?
Thank you.
You cannot write
hand[i].charAt(0) == 'A' || 'B'
perhaps you meant to write
hand[i].charAt(0) == 'A' || hand[i].charAt(0) == 'B'
BTW You can write
"AB".indexOf(hand[i].charAt(0)) >= 0
This way you can add many more letters if you like.
However the clearest way to write the whole thing might be
if (hand[i].startsWith("AC") || hand[i].startsWith("BC"))
Your problem is:
hand[i].charAt(0) == 'A' || 'B'
Logical OR does not work the way you think it does. Use:
hand[i].charAt(0) == 'A' || hand[i].charAt(0) == 'B'
Syntax. Each boolean operator (||, &&, etc.) works only with boolean values. No ints (like in C) and definetely no chars.
if (hand[i].charAt(0) == 'A' || 'B' && hand[i].charAt(1) == 'C')
should be
if ((hand[i].charAt(0) == 'A' || hand[i].charAt(0) == 'B') && hand[i].charAt(1) == 'C')
The || operator (and &&) only works with boolean values, not char values. What this means is that you need to explicitly write each comparison with each character.
Change:
hand[i].charAt(0) == 'A' || 'B'
to
(hand[i].charAt(0) == 'A' || hand[i].charAt(0) == 'B')
The "or" condition is enclosed in parentheses so it's evaluated before the &&, which is what I believe you intended.
Because it is used to compare booleans, you are passing a char instead of a boolean.
if (hand[i].charAt(0) == 'A' || hand[i].charAt(0) == 'B' && hand[i].charAt(1) == 'C')
System.out.println(hand[i]);
}
I've got a simple java assignment. I need to determine if a string starts with the letter A through I. I know i have to use string.startsWith(); but I don't want to write, if(string.startsWith("a")); all the way to I, it seems in efficient. Should I be using a loop of some sort?
You don't need regular expressions for this.
Try this, assuming you want uppercase only:
char c = string.charAt(0);
if (c >= 'A' && c <= 'I') { ... }
If you do want a regex solution however, you can use this (ideone):
if (string.matches("^[A-I].*$")) { ... }
if ( string.charAt(0) >= 'A' && string.charAt(0) <= 'I' )
{
}
should do it
How about this for brevity?
if (0 <= "ABCDEFGHI".indexOf(string.charAt(0))) {
// string starts with a character between 'A' and 'I' inclusive
}
Try
string.charAt(0) >= 'a' && string.charAt(0) <= 'j'
char c=string.toLowerCase().charAt(0);
if( c >= 'a' && c <= 'i' )
...
This makes it easy to extract it as a method:
public static boolean startsBetween(String s, char lowest, char highest) {
char c=s.charAt(0);
c=Character.toLowerCase(c); //thx refp
return c >= lowest && c <= highest;
}
which is HIGHLY preferred to any inline solution. For the win, tag it as final so java inlines it for you and gives you better performance than a coded-inline solution as well.
if ( string.toUpperCase().charAt(0) >= 'A' && string.toUpperCase().charAt(0) <= 'I' )
should be the easiest version...