I'm suppose to create a code that recognizes if my hand has the same card faces
public static boolean sameFace(String hand) {
hand = "s9s7s2sQsK";
char f = hand.charAt(0);
if( hand.charAt(0)==hand.charAt(2) && hand.charAt(0)==hand.charAt(4)
&& hand.charAt(0)==hand.charAt(6) && hand.charAt(0)==hand.charAt(8));
return (hand.charAt(0) == hand.charAt(2) && hand.charAt(0) == hand.charAt(4)
&& hand.charAt(0) == hand.charAt(6) && hand.charAt(0) == hand.charAt(8));
sameface = hand;
if (hand==true;)
return (hand==true;) ;
}
As can be seen above, if all positions are the same characters, it comes true(False, if even one isn't the same.) How can I then use the result of that "return" to let my program recognize it has the same faces or not? If that is even possible.
From what i know, based on my code, it's saying "Yes, positions x=y=z are the same" how can I then tell it "Since they are the same, they have the same card faces."
I tried to put this at the end
sameface = hand;
if (hand==true;)
return (hand==true;) ;
Basically I'm trying to say that when the "hand" return statement is true, then samefaces is true. Meaning that the faces are the same. And if it's false it'll return false.
Basically I'm trying to say that when the "hand" return statement is true, then samefaces is true. Meaning that the faces are the same. And if it's false it'll return false.
You do that simply by returning the result of the expression:
public static boolean sameFace(String hand) {
char f = hand.charAt(0);
return f == hand.charAt(2) &&
f == hand.charAt(4) &&
f == hand.charAt(6) &&
f == hand.charAt(8);
}
Or if you want to be friendly to a different number of cards, use a loop:
public static boolean sameFace(String hand) {
char f = hand.charAt(0);
for (int i = 2, len = hand.length(); i < len; i += 2) {
if (f != hand.charAt(i)) {
// Not a match
return false;
}
}
// All matched
return true;
}
Related
For a project at University, I have to create a game of Tic Tac Toe.
I have this for loop with if statements to search through the 2D array of 3x3 size, and return if it's either X or O (enum). That results in showing which side has won the game.
However, the problem I have is that if the 2D array is not complete, as in if all the 9 boxes are not filled with X or O, the method shows a NullPointerException.
Edit: I have to add that I require the empty grid to be null as few other unit tests assume grid[][] is initialized as null.
Error:
Exception in thread "main" java.lang.NullPointerException
at TicTacToeImplementation.whoHasWon(TicTacToeImplementation.java:80)
at ApplicationRunner.main(ApplicationRunner.java:24)
Code:
public enum Symbol {
X, O
}
private Symbol winner;
public Symbol whoHasWon() {
for (Symbol xORo : Symbol.values()) {
if ((grid[0][0].equals(xORo) &&
grid[0][1].equals(xORo) &&
grid[0][2].equals(xORo))) {
winner = xORo;
isGameOver = true;
break;
} else if ((grid[1][0].equals(xORo) &&
grid[1][1].equals(xORo) &&
grid[1][2].equals(xORo))) {
winner = xORo;
isGameOver = true;
break;}
else if { //Code carries on to account for all 8 different ways of winning
} else {
isGameOver = true;
}
}
return winner;
}
You can use multiple ways to ignore the "null" exception with an empty array.
The 1st way is to fill it with a different default symbol such as E. So when you initialize your arry at the beginning, instead of making it all empty and null, you can fill it with E's
for(int i=0;i<=2;i++){
for(int k=0;k<=2;k++){
grid[i][k] = "E";
}
}
Add this to beginning to fill it with E's first instead of nulls.
Another method is to find how to ignore the nulls using try or the following methods that can be found in this linkhttps://www.javacodegeeks.com/2012/06/avoid-null-pointer-exception-in-java.html:
I won't be going into it because I believe the 1st method is easier to use and implement. However, depending on your requirements for your assignment, I would look at both just to be sure.
Hope this helps, Good luck!
You can change the comparasion of String.The code may be like this ;
public Symbol whoHasWon() {
for (Symbol xORo : Symbol.values()) {
if ((grid[0][0] == xORo.name() &&
grid[0][1] == xORo.name() &&
grid[0][2] == xORo.name())) {
winner = xORo;
isGameOver = true;
break;
} else if ((grid[1][0] == xORo.name() &&
grid[1][1] == xORo.name() &&
grid[1][2] == xORo.name())) {
winner = xORo;
isGameOver = true;
break;}
else if { //Code carries on to account for all 8 different ways of winning
} else {
isGameOver = true;
}
}
return winner;
}
Enum like your's implemented
public enum Symbol{
X, O
}
}
As stated in this post, you can use either equals() or == to compare enums but using == is null safe while equals() isn't.
So basically, just write your checks like this:
if (grid[0][0] == xORo &&
grid[0][1] == xORo &&
// etc.
However, if you want to use the equals() method, you could just write a method that checks for null then compares the two values and returns the result:
public boolean isEqual(Symbol s1, Symbol s2) {
if (s1 != null && s1.equals(s2)) {
return true;
}
return false;
}
You could then call the isEqual() method like this:
if (isEqual(grid[0][0], xORo) &&
isEqual(grid[0][1], xORo) &&
// etc.
public static boolean isValidReferenceCode(String rc) {
boolean validCode = true;
if (rc.length() != 6 ) {
validCode = false;
} else if ( !Character.isLetter(rc.charAt(0)) ||
!Character.isLetter(rc.charAt(1)) ||
!Character.isDigit(rc.charAt(2)) ||
!Character.isDigit(rc.charAt(3)) ||
!Character.isDigit(rc.charAt(4)) ||
!Character.isLetter(rc.charAt(5))) {
validCode = false;
} else if ( (!rc.substring(5).matches("B")) || (!rc.substring(5).matches("N")) ) {
validCode = false;
}
return validCode;
}
This is my validation method inside a big program, I need a validation that requires the user to input at least 6 characters, first two being letters, next three being digits, and the last character either a "B" or "N" right now it's not doing that. After some trial and error, the first two IF statements seem to be correct and work when I delete the 3rd if statement about substrings, am I using the correct Syntax here? Would really appreciate help!
Find below logic , it will work . Better to use regular expressions .
public static boolean isValidReferenceCode(String rc) {
boolean validCode = true;
String pattern= "^[a-zA-Z]{2}[0-9]{3}[BN]}$";
if (rc.length() != 6) {
validCode = false;
}
validCode = rc.matches(pattern);
return validCode;
}
Another way to solve it is to use the original code with:
} else if ( (rc.charAt(5) != 'B') && (rc.charAt(5) != 'N') ) {
You need both to be misses (i.e., use an && instead of an ||).
Instead of a cascade of ifs and negative logic, you can do the entire test more clearly in a single positive-logic expression:
public static boolean isValidReferenceCode(String rc) {
return
rc.length() == 6 &&
Character.isLetter(rc.charAt(0)) &&
Character.isLetter(rc.charAt(1)) &&
Character.isDigit(rc.charAt(2)) &&
Character.isDigit(rc.charAt(3)) &&
Character.isDigit(rc.charAt(4)) &&
(rc.charAt(5) == 'B' || rc.charAt(5) == 'N');
I am wondering what return str.substring(1,4).equals("bad"); is doing here in the else if(len>=4). I think the if statement is a guard clause but I am not 100%. Can I have an explanation of what exactly is going on here? How is this read to output "false"?
Given a string, return true if "bad" appears starting at index 0 or 1 in the string, such as with "badxxx" or "xbadxx" but not "xxbadxx". The string may be any length, including 0. Note: use .equals() to compare 2 strings.
hasBad("badxx") → true
hasBad("xbadxx") → true
hasBad("xxbadxx") → false
public boolean hasBad(String str)
{
int len = str.length();
if(len == 3 && str.equals("bad"))
return true;
else if(len >= 4)
{
if(str.substring(0, 3).equals("bad"))
return true;
return str.substring(1, 4).equals("bad");
}
else
return false;
}
if(str.substring(0, 3).equals("bad")) is the easy part. "Return true if 'bad' is the beginning of the String.'
return str.substring(1, 4).equals("bad") essentially means, "Return true if 'bad' occurs after the first character, and false otherwise". This is basically a shortcut of
if(str.substring(1, 4).equals("bad")) return true;
else return false;
Because the if already evaluates a boolean (what goes inside of an if results in a boolean value), there's no reason to tell it to return "true if true, else false", you can just return the boolean value directly.
you can try it in other way too, like below one
public static boolean hasBad(String str) {
for (int i = 0; i < str.length() - 1; i++) {
if (str.length()>=3 && str.charAt(0) == 'b' || str.charAt(1) == 'b' ) {
if (str.substring(i).contains("bad")) {
return true;
}
}
}
return false;
}
Compare three boolean values and display the first one that is true.
Hey guys, I am trying to write a program that compares three boolean values and displays the first true one. I am comparing three words for their length, and it will display the longest. The error that I am getting is that my else tags aren't working. Take a look at the code.
//Check which word is bigger
if (len1 > len2)
word1bt2 = true;
if (len2 > len3)
word2bt3 = true;
if (len1 > len3)
word1bt3 = true;
//Check which word is the longest
if (word1bt2 == true && word1bt3 == true);
System.out.println(wor1);
else if (word2bt3 == true);
System.out.println(wor2);
else System.out.println(wor3);
I have set boolean values for word1bt2, word2bt3 and word1bt3. In eclipse, I am getting a syntax error under the elses in my code above. Any help would be great!
if (word1bt2 == true && word1bt3 == true);
Is wrong, you need to remove the semicolon:
if (word1bt2 == true && word1bt3 == true)
Same for the elses
else (word2bt3 == true);
Is wrong too, it should be
else if (word2bt3 == true)
Side note: boolean values can be used as condition, so your if statements should be
if (word1bt2 && word1bt3) // The same as if (word1bt2 == true && word1bt3 == true)
How to compare three boolean values?
Dont!
If you find yourself needing to compare three variable you may as well cater for any number of variables immediately - there's no point hanging around - do it properly straight away.
public String longest(Iterator<String> i) {
// Walk the iterator.
String longest = i.hasNext() ? i.next() : null;
while (i.hasNext()) {
String next = i.next();
if (next.length() > longest.length()) {
longest = next;
}
}
return longest;
}
public String longest(Iterable<String> i) {
// Walk the iterator.
return longest(i.iterator());
}
public String longest(String... ss) {
// An array is iterable.
return longest(ss);
}
Remove the ; and change it with brackets {}.
if (word1bt2 && word1bt3) {
System.out.println(wor1);
} else if (word2bt3) {
System.out.println(wor2);
} else {
System.out.println(wor3);
}
Issue with the else blocks: use {} insteaad of () to enclose instructions...
Remove the ; at the first if!!!!! - Quite common mistake, with very puzzling results!
//Check which word is the longest
if (word1bt2 == true && word1bt3 == true) { //leave ; and always add bracket!
System.out.println(wor1);
}
else if(word2bt3 == true)
{
System.out.println(wor2);
}
else {
System.out.println(wor3);
}
if you need a condition in an else branch, you have to use if again - plain else won't have such a feature...
ALWAYS use brackets for bodies of if statements, loops, etc!!!
Be extremely careful NOT to use ; in the lines that don't behave well with it:
if statements
for loops
while() {...} loops' while statement
try this, if lenght are equal then s1 is considered as Bigger. Also i have not added null check
public class Test {
public static void main(String[] args) {
String word1 = "hi";
String word2 = "Hello";
String word3 = "Hell";
String Bigger = null;
if(word1.length() >= word2.length() && word1.length() >= word3.length() ){
Bigger = word1;
}else if(word2.length() >= word1.length() && word2.length() >= word3.length()){
Bigger = word2;
}else if(word3.length() >= word2.length() && word3.length() >= word1.length()){
Bigger = word3;
}
System.out.println(Bigger);
}
}
I'm just learning java, and I have an assignment where I have to write a program that checks the validity of expressions about sets. Valid expressions are capital letters, an expression with a tilde in front, and can be combined using + and x as well as with parentheses. I've written a program that almost works, but I can't figure out how to get the binary operators to work with the parentheses.
It may also be that I have approached the problem in the wrong way (trying to validate from left to right, ignoring everything to the left once it's been validated). I can use any help I can get about writing recursive programs for this sort of problem; that is, if you have any pointers for a better way of approaching the problem, that would be incredibly helpful.
For reference, here is the code that I have:
public static boolean check(String expr) {
char spot;
int close=0;
expr = expr.trim();
//base case
if (expr.length() == 1 && expr.charAt(0)>= 'A' && expr.charAt(0) <= 'Z')
return true;
if (expr.charAt(0) == '~') {
if (expr.charAt(1) == 'x' || expr.charAt(1) == '+' || expr.charAt(1) == ')')
return false;
return check(expr.substring(1));
}
if (expr.indexOf('x') > 0 && expr.indexOf('x') > expr.indexOf(')')) {
int x = expr.indexOf('x');
if (check(expr.substring(0, x)) && check(expr.substring(x)))
return true;
}
if (expr.indexOf('+') > 0 && expr.indexOf('+') > expr.indexOf(')')) {
int plus = expr.indexOf('+');
if (check(expr.substring(0, plus)) && check(expr.substring(plus+1)))
return true;
}
if (expr.charAt(0) == '(') {
close = findEnd(expr.substring(1));
if (close < 0)
return false;
if (check(expr.substring(1,close)) && check(expr.substring(close+1)))
return true;
}
return false;
}
I'm not sure why your code is that complex. Recursion for this is pretty simple overall; here's what I'd do:
public static boolean check(String str) {
if(str.equals("")) return true;
if(str.charAt(0).isAlphaNumeric() || str.charAt(0) == '(' || str.charAt(0) == ')') return check(str.substring(1));
return false;
}
Your edge cases are if the string is empty; if this is the case, then the string is valid. If the character doesn't match what you're looking for, return false. Otherwise, check the next character.