In my method under the if statement:
if (currentLocationX == 0 && currentLocationY == 4)
I have a break statement that should make the program exit out of the while loop and return true for 'answer' and for the method. Yet after some testing it seems that after returning true for 'answer', it goes back into the while loop giving the wrong results int the end. Why is my break statement not doing what it's supposed to? Thank you!
P.S. (this method calls on some other method that were not relevant to mention here)
public boolean solveMaze()
{
boolean answer = false;
int currentLocationX;
int currentLocationY;
//push starting location
pushX(2);
pushY(1);
while((isEmptyX() == false) && (isEmptyY() == false))
{
printMaze();
System.out.println();
currentLocationX = popX();
currentLocationY = popY();
//mark current location as visited
visited(currentLocationX, currentLocationY, maze);
System.out.println("Current Location: " + currentLocationX + ", " + currentLocationY);
if (currentLocationX == 0 && currentLocationY == 4)
{
answer = true;
break;
}
else
{
//push all unvisited OPEN neighbor locations into stack
if (checkEast(currentLocationX, currentLocationY) == 0)
{
pushX(eastX(currentLocationX));
pushY(eastY(currentLocationY));
}
else;
if (checkSouth(currentLocationX, currentLocationY)== 0)
{
pushX(southX(currentLocationX));
pushY(southY(currentLocationY));
}
else;
if (checkWest(currentLocationX, currentLocationY)== 0)
{
pushX(westX(currentLocationX));
pushY(westY(currentLocationY));
}
else;
if (checkNorth(currentLocationX, currentLocationY)== 0)
{
pushX (northX(currentLocationX));
pushY(northY(currentLocationY));
}
else;
}
}
return answer;
}
I wrote out the basic logic of your method as
public static boolean solveMaze() {
boolean answer = false;
int currentLocationX = 0;
int currentLocationY = 4;
while (true) {
if (currentLocationX == 0 && currentLocationY == 4) {
System.out.println("Hit the break");
break;
} else {
System.out.println("Missed the break");
}
}
return answer;
}
and if you execute it you get Hit the break. So your solveMaze() method is fine in terms of breaking out of the loop once it satisfies your if-statement. I would say that if you see your code subsequently going back into the while loop, it must be that solveMaze() was called a second time.
Related
I'm creating a battleship game where a ship occupies 3 cells and you have to guess which cell. Once they guess it you return "hit" and if not you return "miss". Once they hit all 3 you return "kill". I've written the code but it states I still haven't returned a string.
public class SimpleBattleShip{
int[] shipCoordinates;
int numOfHits;
String updateStatus(int guess){
for(int i=0;i<shipCoordinates.length;i++){
if(guess == shipCoordinates[i]){
numOfHits++;
if(numOfHits ==3){
return "kill";
}else{
return "hit";
}
}else{
return "miss";
}
}
}
}
Have you tried just separating the NumberofHits If statement from the for loop. The problem may be the for loop iterating the whole 'hit check' for each value of 'i' which may cause it to put up false values before tallying the full amount of hits.
I've tried throwing in an else if to maybe tighten the parameters. turn it back to else if you want (this is for hit & miss).
public class SimpleBattleShip {
int[] shipCoordinates;
int numOfHits;
String updateStatus(int guess) {
for (int i = 0; i < shipCoordinates.length; i++) {
if (guess == shipCoordinates[i]) {
numOfHits++;
}
}
if (numOfHits == 3) {
return "kill";
} else if (numOfHits < 3 && numOfHits >= 1) {
return "hit";
} else {
return "miss";
}
}
}
Why is my boolean t being set to false after the while loop. I have placed print statements and the "if" conditional within the while loop that sets t=false; never gets hit. Why when I print t out in between the for and while loop does t=false; ?
public void addStudents(Student student){
System.out.println("in addStudents");
boolean t = true;
int counter = 0;
while ( t = true && counter < students.length ){
// System.out.println("while");
if (students[counter].equals(student)) {
// System.out.println("ppppppppppppppppppppppp");
t = false;
counter ++;
// System.out.println("never");
} else {
counter++;
}
}
if (t == true) {
if (students[students.length - 1] != null){
// System.out.println("xxxxxxxxxxxx");
Student[] newstudentsarray = new Student[students.length + 1];
for (int i = 0; i < students.length; i++){
newstudentsarray[i] = students[i];
}
students = newstudentsarray;
students[students.length - 1] = student;
}
}
}
The problem is the Java Operator Precedence where the operator && has a higher precedence as =.
So the statement t = true && counter < students.length is complied into t = (true && counter < students.length) and t is alway set to false at the end of the loop.
You probably wanted to write t == true && counter < students.length but mistyped ==.
This is the reason why it's better to write just
boolean falsy = false;
if(falsy) {
System.out.println("This should never happen");
}
if(!falsy) {
System.out.println("This should always happen");
}
Instead of
boolean falsy = false;
if(falsy == true) {
System.out.println("This should never happen");
}
if(falsy == false) {
System.out.println("This should always happen");
}
When you mistyped you got
boolean falsy = false;
if(falsy = true) {
System.out.println("This should never happen."); // This happens
}
if(falsy = false) {
System.out.println("This should always happen"); // This didn't happens
}
So while I was typing this question, I found a workaround for a "missing return statement" error. But I still don't think this is the proper way of doing it. As you can see I have some nested if statements. I want both conditions to be met before returning anything, but I had to place the return statements outside of the nested if statements. If the last condition isn't met doubt this should cause much problem since an empty string will be returned, but I just feel as if this isn't the best way of going about doing things.
1st Edit: with my current update, i'm still missing a return statement. I could do the same fix i applied but I feel as if it is innapropriate.
public String findProtein(String dna) {
int start = dna.indexOf("atg");
int stop1 = dna.indexOf("tag", start + 3);
int stop2 = dna.indexOf("tga", start + 3);
int stop3 = dna.indexOf("taa", start + 3);
String subStr1 = dna.substring(start, stop1);
String subStr2 = dna.substring(start, stop2);
String subStr3 = dna.substring(start, stop3);
boolean geneFound = false;
if (subStr1.length() % 3 == 0) {
geneFound = true;
return subStr1;
}
if (geneFound == false) {
if (subStr2.length() % 3 == 0) {
geneFound = true;
}
return subStr2;
}
if (geneFound == false) {
if (subStr3.length() % 3 == 0) {
geneFound = true;
}
return subStr3;
}
if (geneFound == false) {
return "";
}
}
2nd Edit: additional code
private void stopCodon(String gene){
//This prints out the last 3 characters of the gene
String stopCodon = gene.substring(gene.length() - 3);
System.out.println(stopCodon);
}
public void testing() {
String a = "ataaactatgttttaaatgt";
String result = findProtein(a);
stopCodon(result);
}
If it were me, I would edit the following logic
if( subStr1.length() % 3 ==0 ){
geneFound = true;
return subStr1;
}
if(geneFound == false){
if(subStr2.length( )% 3 ==0 ){
geneFound = true;
}return subStr2;
}
if(geneFound == false){
if(subStr3.length( )% 3 ==0 ){
geneFound = true;
}
return subStr3;
}
if (geneFound == false){
return "";
}
To the following using else if statements:
if( subStr1.length() % 3 ==0 ){
return subStr1;
} else if (substr2.length()%3==0){
return substr2;
} else if (substr3.length()%3 == 0) {
return substr3;
} else {
return null;
}
I'm also not sure if String subStr1 = dna.substring(start,stop1); is something you want since an Exception will be thrown if the stop codon doesn't exist, but it would be hard to judge without you giving us additional information.
Added
Kind of saw this coming, but if you look at the description for indexOf
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(int)
the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.
If you want to check if the substring exists, you check if the index is -1
I'm only gonna go through an example for the first substring
int stop1 = dna.indexOf("tag", start + 3);
if(stop != -1) {
return dna.substring(start, stop1);
}
You should start by checking if the start codon exists at all and return null if it doesn't exist immediately, since locations of stop codons are useless without start codons.
Hopefully this helps
if( subStr1.length() % 3 ==0 ){
geneFound = true;
result = subStr1;
}else if(geneFound == false){
if(subStr2.length( )% 3 ==0 ){
geneFound = true;
}
result = subStr2;
}else if(geneFound == false)
if(subStr3.length( )% 3 ==0 ){
geneFound = true;
}
result = subStr3;
}
if (geneFound == false){
result = "";
}
return result;
result is of type String.
However any one of three if statements will return the value. If not fourth if statement will return the value.
You can assign the result to a variable and return it at the end
Why don't you return something like this ?
public String findProtein(String dna) {
String valueToBeReturned = "";
if(condition 1){
valueToBeReturned = "value1"
}
if(condition 2){
valueToBeReturned = "value2"
}
//Rest of the conditions
return valueToBeReturned; //Finally return the specific value
}
How about remove unnecessary block of code?
if (geneFound == false) {
return "";
}
Since you return a value and the boolean is a local variable, it doesn't really matter if you change the boolean value or not in this code. I really don't see a use for it at the time. I simplified the code following your logic!
public String findProtein(String dna) {
int start = dna.indexOf("atg");
int stop1 = dna.indexOf("tag", start+3);
int stop2 = dna.indexOf("tga",start+3);
int stop3 = dna.indexOf("taa",start+3);
String subStr1 = dna.substring(start,stop1);
String subStr2 = dna.substring(start,stop2);
String subStr3 = dna.substring(start,stop3);
if(subStr1.length() % 3 == 0 ) {
return subStr1;
}
if(subStr2.length() % 3 == 0 ){
return subStr2;
}
if(subStr3.length( )% 3 ==0 ){
return subStr3;
}
return "";
}
I'm trying to create a program which prints a datastructure from the input. The input and output looks like this: http://puu.sh/kDMc9/2d46462d4d.png. So for example, in the first test case: the first line indicates how many lines will follow in that case. Then if it's the number 1 as the first number on a line it means that you want to add elements to stack/queue/priority-queue and 2 means you want to take out an element, so the second number on a line is the value. Then the output prints if it's stack,queue, priority-queue, impossible or not sure(can be more than one)
This is the code I have now:
import java.util.PriorityQueue;
import java.util.Scanner;
public class DataStructure {
public static void main(String[] args)
{
while(calculate());
}
private static boolean calculate()
{
Scanner input = new Scanner(System.in);
int numberOfRowsPerCase = input.nextInt();
Stack<Integer> stack = new Stack<Integer>();
Queue<Integer> queue = new Queue<Integer>();
PriorityQueue<Integer> prioQueue = new PriorityQueue<Integer>();
boolean stackBool = true;
boolean queueBool = true;
boolean prioQueueBool = true;
int next;
for(int i = 0; i < numberOfRowsPerCase; i++)
{
next = input.nextInt();
if(next == 1)
{
next = input.nextInt();
stack.push(next);
queue.enqueue(next);
prioQueue.add(next);
}
else if(next == 2)
{
next = input.nextInt();
if(!stack.pop().equals(next))
{
stackBool = false;
}
else if(!queue.dequeue().equals(next))
{
queueBool = false;
}
else if(!prioQueue.poll().equals(next))
{
prioQueueBool = false;
}
}
if(stackBool == true)
{
System.out.println("stack");
}
else if(queueBool == true)
{
System.out.println("queue");
}
else if(prioQueueBool == true)
{
System.out.println("priority queue");
}
else if((stackBool == true && queueBool == true) || (queueBool == true && prioQueueBool == true) || (stackBool == true && prioQueueBool == true))
{
System.out.println("not sure");
}
else
{
System.out.println("impossible");
}
}
//Check EOF
String in;
in = input.nextLine();
in = input.nextLine();
if(in.equals(""))
{
return false;
}
return true;
}
}
But when I run the test-case on the picture above, my program prints this: https://ideone.com/mIO1bs which is wrong. I can't find why it does that, can anyone else here maybe see?
Assuming that your logic setting the boolean flags is correct then this part
if(stackBool == true)
{
System.out.println("stack");
}
...
else if((stackBool == true && queueBool == true) || (queueBool == true && prioQueueBool == true) || (stackBool == true && prioQueueBool == true))
{
System.out.println("not sure");
}
will never work as intended because parts of the second condition were already caught by the first condition.
The better suggestion is to come up with a clearer way of representing this. A suggestion that will still probably work is to put your more complicated if statements at the start of the if-else chain.
Disregarding above assumption:
if(!stack.pop().equals(next))
{
stackBool = false;
}
else if(!queue.dequeue().equals(next))
{
queueBool = false;
}
else if(!prioQueue.poll().equals(next))
{
prioQueueBool = false;
}
These should not be elses, they're all completely independent.
I recently had to code up an interpreter for Bitcoin's script language; part of this involved coming up with an algorithm to check that the control flow in a given script made sense (i.e. every OP_IF had a matching OP_ENDIF, every OP_ELSE and OP_ENDIF had a matching OP_IF, etc.).
This is what I came up with:
public class if_else_checker {
public static boolean search(String[] commands, String[] tracker, int if_index) {
boolean seenElse = false;
for (int i = if_index; i < commands.length; i++) {
if (commands[i].equals("OP_ELSE")) {
if (seenElse == true && tracker[i] == null) return false;
if (tracker[i] == null) {
tracker[i] = "OP_ELSE";
seenElse = true;
}
}
else if (commands[i].equals("OP_ENDIF")) {
if (tracker[i] != null && tracker[i].equals("OP_ENDIF"))
{
continue;
}
tracker[i] = "OP_ENDIF";
return true;
}
else if (commands[i].equals("OP_IF")) {
if (tracker[i] != null && tracker[i].equals("OP_IF")) {
continue;
}
tracker[i] = "OP_IF";
if (search(commands, tracker, i + 1) == false) return false;
}
}
return false;
}
public static boolean validate(String[] args)
{
String[] tracker = new String[args.length];
for (int i = 0; i < args.length; i++)
{
if (args[i].equals("OP_IF"))
{
if (tracker[i] == null || !tracker[i].equals("OP_IF"))
{
tracker[i] = "OP_IF";
if (search(args, tracker, i + 1) == false) return false;
}
else continue;
}
else if (args[i].equals("OP_ELSE"))
{
if (tracker[i] == null || !tracker[i].equals("OP_ELSE")) return false;
}
else if (args[i].equals("OP_ENDIF"))
{
if (tracker[i] == null || !tracker[i].equals("OP_ENDIF")) return false;
}
}
return true;
}
public static void main(String[] args)
{
System.out.println(validate(args));
}
}
It works, but I was wondering if there is a way to optimise it/if there is a standard way of doing this? (One optimisation is to have validate() return the index of the OP_ENDIF it finds, rather than a boolean; this would change runtime from quadratic-time to linear).
The best way of solving this is by using a Stack data structure. Every new opening instruction (e.g. OP_IF) is pushed into the stack. When you find a closing instruction (e.g. OP_ENDIF), you pop the top element of the stack and check if it is the corresponding opening instruction for that closing instruction. If so, then it's valid, and you proceed to the next step. In the end, if the stack is empty then the control flow you're checking is correct. Otherwise, it's not.