Java Nonworking method? - java

Hey,
So Ive got this method to determine if a game I wrote is over and for some reason it isn't working. I'm getting the error "the left hand side of assignment must be a variable"
Here is the method:
public boolean isWinner() {//checks for game completion
int check = board[startX][startY];
for(int i=0; i<sizeX; i++){
for(int j=0; j<sizeY; j++){
if (board[i][j] != check)
return false;
}
}
return true;
}
Here is a piece of the code where it is used:
ColorFloodGame game = new ColorFloodGame (6,6);
while (game.isWinner() = false){
//code here
}

You have while (game.isWinner() = false), which is an assignment because you have a single = sign.
You want while (game.isWinner() == false) which is a comparison because it has two = signs.

You need to replace
while (game.isWinner() = false){
with
while (game.isWinner() == false){
or better yet:
while (!game.isWinner()){

while (game.isWinner() = false){
should be
while (game.isWinner() == false){
one '=' is an assignment, two '==' is a comparison

Ralf & Gabe have already answered it, but IMHO this is more readable:
while (!game.isWinner()){

The expression in the while statement is an assignment. The compiler can't evaluate the expression correctly. Change your code to the following and everything should work fine.
while (game.isWinner() == false) {
//code here
}
You could also write the code like this
while (!game.isWinner()) {
//code here
}
The style used is different for every programmer and you should find your own preference.
Hope it helps.

Related

JAVA Comparing two Strings isn't working

So here's a snippet of code I'm working on:
String direction = s.readLine();
System.out.println(direction);
if (direction.equals("up") != true && direction.equals("down") != true &&
direction.equals("left") != true && direction.equals("right") &&
direction.equals(null) != true) {
System.out.println("Invalid Solution file");
System.exit(0);
}
What it is supposed to do is read a line from a text file (using a BufferedReader) and then if the line isn't either a valid direction or blank then it should print "Invalid Solution" and exit.
The problem is that no matter what the direction string is the if statement still runs. I put in a println to check whether the direction was being read correctly but it seems absolutely fine. So why isn't the code working as intended?
Part of your problem is readability. Fix that and your problem is 90% solved:
private static List<String> DIRECTIONS = Arrays.asList("up", "down", "left", "right");
then
if (!DIRECTIONS.contains(direction)) {
System.out.println("Invalid Solution file");
System.exit(0);
}
The other 10% was how to check for null, which is direction == null, but if you use this code you don't need to, because contains(null) will conveniently return false.
You code is much more complex than it is needs to.
Consider this instead:
Set<String> validDirections = new HashSet<>(Arrays.asList("up", "down", ...
if (validDirections.contain(direction.toLowerCase()) {
// good ...
} else {
// bad ..
}
You can make validDirections a global constant for example; so it could be used in other places as well.
What I am trying to explain here is: your code is low-level. Low level code is hard to write, read, maintain and extend. Programming is always about creating good abstractions. Or vice versa: if you don't use abstractions, you end up with pretty abstract code, like the one you are showing here!
For example: if you need another direction, you have to put into your already way too complicated if condition. In my solution, you just put it into the statement that builds that Set.
Finally: your error message, is saying nothing. So, that string is bad; but why is it? Wouldn't it be better to at least print the string that caused the error?!
Here && direction.equals("right") I think you have done a mistake since it is on contradiction with the rest :
direction.equals("up") != true &&
direction.equals("down") != true &&
direction.equals("left") != true
You test the negation in the most of conditions but direction.equals("right") tests the affirmation.
Try it , it's the same thing but less verbose and more readable :
if (direction !=null && !direction.equals("up") &&
!direction.equals("down") &&
!direction.equals("left") &&
!direction.equals("right") ){
System.out.println("Invalid Solution file");
System.exit(0);
}
First, you should not use != true with a boolean statement, it is bad form. Rewrite like this:
direction !=null &&
!direction.equals("up") &&
!direction.equals("down") &&
!direction.equals("left") &&
!direction.equals("right")
Your error was that you did not include the != true part on one of your statements within the compound if. Replace with the above code to solve the issue.
I'm confused why you are using !=true when your .equals method already returns a boolean. Try this.
String direction = s.readLine();
System.out.println(direction);
if ( direction!=null && !direction.equals("up") && !direction.equals("down")&& !direction.equals("left")&& direction.equals("right")){
System.out.println("Invalid Solution file");
System.exit(0);
}
Try the following code:
boolean match = false;
if (direction.equals("up"))
{ match = true; }
if (direction.equals("down"))
{ match = true; }
if (direction.equals("left"))
{ match = true; }
if (direction.equals("right"))
{ match = true; }
if (direction.equals(null))
{ match = true; }
if (match == false){
System.out.println("Invalid Solution file");
System.exit(0);
}
You might also want to trim the direction string after reading from file.
The quals method returns a boolean so the result does not need to be compared with the true or false value. Also, I would start with null comparison - boolean expressions in Java are shortened so if this part will be fulfilled rest of the expression is not evaluated. The correct expression might look like this:
 
if (direction == null || (!direction.equals("up") && !direction.equals("down") && !direction.equals("left") && !direction.equals ("right "))) {
}
But this code is not readable. You could use enums or list of Strings like below
List<String> directions = Arrays.asList("up", "down", "left", "right");
String direction = "readValue"
if (!directions.contains(direction)) {
System.out.println("Invalid direction");
System.exit(0)
}

Java: Using my for statement

this is my first post so please bear with me. I am trying to produce a program that lets a user play black jack against the computer. the following code let the player take their turn:
//method for the players turn
public static void playersTurn()
{
String playersCard = dealSingleCard();
playerHand.add(playersCard);
String playersActualHand = cardRepresentation(playersCard);
System.out.println(playersActualHand);
//System.out.println(playerHand);
System.out.println(calculateHandValue(playerHand));
Scanner in = new Scanner(System.in);
System.out.println("Stick or Twist?");
String stickOrTwist = in.next();
String twist = "t";
String stick = "s";
//int total = 0;
//int playerTotal = calculateHandValue(playerHand) + total;
if (calculateHandValue(playerHand) < 21)
{
if (stickOrTwist .equalsIgnoreCase (twist));
{
dealSingleCard();
}
if (stickOrTwist .equalsIgnoreCase (stick))
{
calculateWinner();
}
}
}
I cant seem to get the "twist" if statement to work, the program just stops. The "stick if statement work fine. what am i doing wrong?
You have a little syntax error, since you put a semicolon after the if condition, here:
if (stickOrTwist .equalsIgnoreCase (twist));
Remove it and it should work fine.
Change the below code
if (calculateHandValue(playerHand) < 21)
{
if (stickOrTwist .equalsIgnoreCase (twist));
{
dealSingleCard();
}
if (stickOrTwist .equalsIgnoreCase (stick))
{
calculateWinner();
}
}
with
if (calculateHandValue(playerHand) < 21)
{
if (stickOrTwist .equalsIgnoreCase (twist))
{
dealSingleCard();
}
if (stickOrTwist .equalsIgnoreCase (stick))
{
calculateWinner();
}
}
The line terminator ';' should not be used with the if condition.
the only problem with your code is that you have placed ';' after the if statemt.So the compiler is not executing the body of if.Try removing the semicolon as:
if (stickOrTwist .equalsIgnoreCase (twist))
{
dealSingleCard();
}
I just assume from the way you used dealSingleCard() at the beginning of the methode, you want todo the following:
if(stickOrTwist.equalsIgnoreCase(twist)){
playerHand.add(dealSingleCard());
}
The rules of blackjack (or pontoon as it was called when I was growing up) are that a player can repeatedly twist until (s)he either decides to stick or her hand value exceeds 21. This repeated behaviour is absent from your code.
Instead of
if (calculateHandValue(playerHand) < 21)
you should have a loop
while (calculateHandValue(playerHand) < 21)
and inside the while loop, you ask if the player will stick or twist. Break out of the loop if the player sticks and then process the bust condition. You should only call the calculateWinner() method once all the players have played.

Validation is working too well

I have this validation to check that user input is not blank and is only letters. If it's blank, it catches it, and if if includes digits it also catches it. If I input the 2 characters it asks for, however, it doesn't go through. I'm not sure how to go about this.
private static boolean isValidSt(String aSt) {
boolean result = false;
try {
if (aSt.length() == 2) {
result = true;
} else if (aSt.length() != 2) {
result = false;
}
for (int i=0; i <aSt.length();){
if (!Character.isLetter(i));{
return false;
}
}
return true;
} catch (NumberFormatException nfex) {
if (aSt == null) System.exit(0);
} catch (Exception ex) {
if (aSt == null) System.exit(0);
}
return result;
}
One problem that I can see right of the bat is this:
if (!Character.isLetter(i));{
return false;
}
That semi-colon after your if does not belong there. After checking your conditional statement, if it was true, it will execute until the semi-colon. The return false; isn't part of the if and will ALWAYS be executed.
As David Wallice rightly pointed out, you also never increment the counter in your for-loop, so were it not the case that the program always returned with false in the first iteration, it would indeed get stuck in an eternal loop. A very commonly used syntax for for-loops would be:
for(int i = 0; i < string.length(); i++) { }
A third and final note from me, this time nothin that would give an error, just good form:
You use System.exit(0); to exit the program as result of an exception. The zero you pass as an argument is usually only used when the program shuts down normally. This is a crash as a result of an error, so I'd use 1 or something.
Well, you could use StringUtils methods, isBlank and isAlpha, for validate what you need

Checking if every char in a string belongs to the given set of chars or not (JAVA)

So I need to create a method isValidDNA which works like this:
public boolean isValidDNA()
Returns true if the DNA is valid, i.e, only contains the letters,
A,T,C,G (in uppercase) and at least one of these characters.
All I could think of was this, which apparently doesn't work:
public boolean isValidDNA(){
for (int i=0;i<dna.length();i++){
if (dna.charAt(i)=='A' || dna.charAt(i)=='T' || dna.charAt(i)=='C' || dna.charAt(i)=='G' ){
return true;
}
return false;
}
}
You can use this regular expression:- [ATCG]+ In code this could look like this:
public boolean isValidDNA(){
return dna.matches("^[ATCG]+$")
}
You make a return statement immediately, which will exit during the first iteration and only check the first character.
You need to store this information in a boolean and return it after you've checked the whole string:
public boolean isValidDNA(String dna){
Boolean result = true;
// Add an extra check for the "at least one character" thing.
for (int i=0; i<dna.length(); i++){
if (dna.charAt(i)!='A' && dna.charAt(i)!='T' && dna.charAt(i)!='C' && dna.charAt(i)!='G' ){
result = false;
}
}
return result;
}
However, you would be better off using regular expressions for these problems.
Try it this way:
public boolean isValidDNA(){
boolean res = true;
for (int i=0;i<dna.length();i++){
if ((dna.charAt(i) != 'A') && (dna.charAt(i)!='T') && (dna.charAt(i)!='C') && (dna.charAt(i)!='G') ){
res = false;
break;
}
}
return res;
}
if your startpoint is that the DNA is valid, it's much more easy to test if it's really so. You only have to test each char of your dna and can stop by the first entry that doesn't satisfy your if-statement.
Using your way, you've almost got it.
Right now, you return true if you find one that's OK, and only return false if all are wrong. You can negate your if condition, and return false as soon as you find one that's not OK, and only return true if all are fine.
I'll leave the coding part up to you.
As others pointed out, regex will be a cleaner solution here.
You can try this implementation.
First declare a constant:
private static final String bases = "ATCG";
And then use it in the method like this:
public boolean isValidDNA() {
boolean isValid = true;
for (char c : dna.toCharArray()) {
if (bases.indexOf(c) < 0) {
isValid = false;
break;
}
}
return isValid;
}
Scanner sc = new Scanner(System.in);
System.out.print("Enter a DNA sequence: ");
seq=sc.nextLine();
if(seq.matches(".*[^ATCG].*")){
System.out.println("Not a valid sequence.");
System.exit(0);
}
This regular expression works so that only sequences containg A,C,T or G with no other charcters, spaces, etc included will continue

My if statement ALWAYS returns true, no matter what

This just is't making sense to me at all.
This is my code:
boolean that = false;
if (that == true);
{
System.out.println("That is " + that);
}
And yet it will print the line even though my output is
That is false
I'm doing this in java and I'm using Eclipse galileo, so each time I compile/run my program it saves it so the compiler should be getting updated version of my program.
What's going on?
A common mistake. Remove the ; at the end of the if statement.
BTW I always write the following if I use brackets and I use the code formatter of the IDE.
if (that == true) {
System.out.println("That is " + that);
}
This means if you have a mis-placed ; or { it can be more obvious.
Remove the ;
boolean that = false;
if (that == true)
{
System.out.println("That is " + that);
}
otherwise the print is always executed.
It's because of the semicolon you have here:
if (that == true);
Remove that semicolon ! It causes the code to do nothing after checking the conditional (that == true) - technically it's an "empty statement" - i.e. we can have a loop like so:
for (int i = 0; ; i++){
System.out.println("Thanks" );
}
And it would go forever!
Try it like this:
boolean that = false;
if (that)
{
System.out.println("That is " + that);
}
Notice the extra semi-colon after the if in your code? That's why.
The logical test is closed by the semi-colon, then the next block is always executed.
If you remove the semi-colon it'll match your intuition.
if (that == true);
// ^ The extra colon you dont need

Categories

Resources