While loop: Need assistance - java

I can't find the problem that causes my while loop not to work.
When I run the program and press a radio button, I get this error code:
Syntax error, insert "while ( Expression ) ;" to complete DoStatement
Here is my loop:
int i = 1;
boolean x;
//for (i = 0; i < 6; i++) {
do{
warning.setText(" FEL!");
i++;
while(x == false);{
if(e.getSource() == buttonOK){
if(buttonDollar.isSelected() == false){
x = false;
}
if(buttonEuro.isSelected() == false){
x = false;
}
if(buttonPund.isSelected() == false){
x = false;
}
if(buttonKrona.isSelected() == false){
x = false;
}
break;
}
}
}

You are missing the syntax for "while" element
From the sun site (I am guessing that this is java)
do {
statement(s)
} while (expression);

I think you need a closing curly brace before the while
do{
warning.setText(" FEL!");
i++;
}while(x == false);

The whole structure is all wrong, you're looking to do something very simple:
if(e.getSource() == buttonOK)
{
if( !buttonDollar.isSelected() && !buttonEuro.isSelected()
&& !buttonPund.isSelected() && !buttonKrona.isSelected() )
{
warning.setText(" FEL!");
}
}
From a UI perspective, it's better to ensure that one radio button is always selected (as this is what your users will likely expect).

Related

Trying to find the index if the array is in range [duplicate]

public boolean Winner() {
for (int z = 0; z < 3; z++) {
if (board[z] != null && board[z] == board[z+3] && board[z] == board[z+6]
) {
return true;
}
}
for(int i=0; i<7;i+=3){
if (board[i] != null && board[i] == board[i+1] && board[i] == board[i+2]) {
return true;}
}
}
It returns me this error: this method must return a result of type boolean. What am I doing wrong?
Right now, the function isn't guaranteed to return a boolean, because it's possible that neither of the if statements will ever be entered.
You could fix it like this (but only do this if it's actually what your logic needs!):
public boolean Winner() {
for (int z = 0; z < 3; z++) {
if (board[z] != null && board[z] == board[z+3] && board[z] == board[z+6]
) {
return true;
}
}
for(int i=0; i<7;i+=3){
if (board[i] != null && board[i] == board[i+1] && board[i] == board[i+2]) {
return true;}
}
return false;
}
The Java compiler doesn't make assumptions that a for loop will have an iteration or that an if statement block will run.
There are execution paths where there is no return statement. What happens if the execution path doesn't execute any of the existing return statements and drops to the bottom? There isn't a return there.
Add a return at the bottom.
All possible ways that the method can exit need to return something. If your code makes it through both for loops without having an if condition evaluate to true, then you need a return at the end that specifies what gets returned.
The compiler is not aware that at least one of the loops will be executed. It takes into account all the possibilities of the execution and one of them is that neither of the loops will be executed and in that case there is no return statement. So insert a return statement out of the loops as well.
The answer to this question is easy. It happened to me too. The problem in your code is that you don't say to the computer what to do in case that the "if" statement is wrong, so you just have to add an "else {return false}" to every "if". Another tip is: please make your code cleaner and readable.
public boolean Winner() {
for (int z = 0; z < 3; z++) {
if (board[z] != null && board[z] == board[z+3] && board[z] == board[z+6]) {
return true;
} else {
return false;
}
}
for (int i=0; i<7; i+=3) {
if (board[i] != null && board[i] == board[i+1] && board[i] == board[i+2]) {
return true;
} else {
return false;
}
}
}

While loop boolean confusion

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
}

Why is my break statement being ignored?

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.

Tic Tac Toe, checking legal move

New to the site and have not been coding long. I am trying to find a way to check to see if the entered value is withing the array range as well as checking to see if the position is already occupied. I am running into trouble if the problems are not in order. I would like for it to catch the problem in any order and request them to enter another value, then recheck again. Thanks for any advice!
This is what I ended up doing. Any thoughts? Thanks again.
//in play game method
while(checkNotInBounds(move)){
System.out.println("Out of Bounds! Please try again...");
move = getMove(player);
}
while(!checkSpaceFree(move, boardValues)){
System.out.println("Space Taken! Please try again...");
move = getMove(player);
while(checkNotInBounds(move)){
System.out.println("Out of Bounds! Please try again...");
move = getMove(player);
}
//Method: checkInBounds
//Purpose: find out if move is in bounds
public static boolean checkNotInBounds(int[] move){
if(move[0] > 2 || move[0] < 0 || move[1] > 2 || move[1] < 0){
return true;}
return false;
}
//Method: checkFreeSpace
//Purpose: find if space is free
public static boolean checkSpaceFree(int[] move, char[][]boardValues){
if(boardValues[move[0]][move[1]] == ' '){
return true;}
return false;
}
Why not split it up into two methods instead of one as your trying to do two things there and switching isn't neccary then
do something like
public static boolean checkLegalMove(int[] move, char[][] boardValues){
if(move[0] > 2 || move[0] < 0 || move[1] > 2 || move[1] < 0){
return false;
}
if(boardValues[move[0]][move[1]] != ' '){
return false;
}
return true;
}
public void doSomething(boolean checkLegalMove(move,boardValues), char player){
boolean check = checkLegalMove(move,boardValues);
char temp = player;
if(check ==true ){
//do something to player
}else{
getMove(player);
}
}

Testing parentheses in a equation using stack java

I'm writing a program that will take in an equation and check if all the parentheses line up and it will output if it is good or not.
For Ex: (3+4) is good
((3*8) is NOT Good
I'm not allowed to use java's built in push() pop() methods ext..
I have to make my own which I think I got....I think!
The problem I'm having is in the Test() method.
First I'm not sure how to write the while loop like:
while(there are still characters)
Anyway the output I'm getting is: stack is empty -1
Any help is appreciated. I'm one of the slower program learners and I couldn't be trying any harder. Thanks.
Here's what I got:
public class Stacked {
int top;
char stack[];
int maxLen;
public Stacked(int max) {
top = -1;
maxLen = max;
stack = new char[maxLen];
}
public void push(char item) {
top++;
stack[top] = item;
}
public int pop() {
//x = stack[top];
//top = top - 1;
top--;
return stack[top];
}
public boolean isStackEmpty() {
if(top == -1) {
System.out.println("Stack is empty" + top);
return true;
} else
return false;
}
public void reset() {
top = -1;
}
public void showStack() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j = top; j > -1; j--){
System.out.println(stack[j]);
}
System.out.println(" ");
}
public void showStack0toTop() {
System.out.println(" ");
System.out.println("Stack Contents...");
for(int j=0; j>=top; j++){
System.out.println(stack[j]);
}
System.out.println(" ");
}
//}
public boolean test(String p ){
boolean balanced = false;
balanced = false;
//while ( )
for(char i = '('; i < p.length(); i++ ){
push('(');
}
for (char j = ')'; j < p.length(); j++){
pop();
}
if (isStackEmpty()) {
balanced = true;
//return balanced;
}
return balanced;
}
public static void main(String[] args) {
Stacked stacks = new Stacked(100);
String y = new String("(((1+2)*3)");
stacks.test(y);
//System.out.println(stacks.test(y));
}
}
Now I'm getting somewhere. I need to be pointed in the right direction again. Thanks everyone this helped big time. I still have a lot more to do but this is good for now. Eventually I need to create a two more methods: one "infix to postfix" and the other "evaluating postfix" and at the end I'll need to read in answers from a text file instead of putting my own into the main method. Thanks again much appreciated.
Unless you need to actually evaluate the equation, a stack is too complicated a solution here. You simply need a counter:
int openParentheses = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
openParentheses++;
} else if (p.charAt(i) == ')') {
openParentheses--;
}
//check if there are more closed than open
if (openParentheses < 0) {
return false;
}
}
if (openParentheses == 0) {
return true;
} else {
return false;
}
If you absolutely must use stacks, use this:
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
push('x'); //doesn't matter what character you push on to the stack
} else if (p.charAt(i) == ')') {
pop();
}
//check if there are more closed than open
if (stackIsEmpty()) {
return false;
}
}
if (isStackEmpty()) {
return true;
} else {
return false;
}
I agree with Griff except that you should include another check if you didn't have more closed parentheses than open. (x*y))( is not a valid entry.
int openParentheses = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '(') {
openParentheses++;
} else if (p.charAt(i) == ')') {
openParentheses--;
}
if(openParentheses<0)
return false;
}
if (openParentheses == 0) {
return true;
} else {
return false;
}
You may be required to use a stack, but this could be done with a simple counter. This will show you a how to iterate over the characters of a String:
boolean test(String p) {
int balance = 0;
for (int idx = 0; idx < p.length(); ++idx) {
char ch = p.charAt(idx);
if (ch == '(')
++balance;
else if (ch == ')')
--balance;
if (balance < 0)
return false;
}
return balance == 0;
}
Of course, you could replace the increment and decrement with pushes and pops, respectively, on a stack.
For parsing you can use a for loop over the index and address the character of the string at the certain index.
But you actually do not need a stack, an integer variable openBraces is sufficient:
initialize with 0
for '(' you increment the variable one
for ')' you decrement the variable one
if openBraces is <0, you immediately give an error
if at the end openBraces is not equal to 0, you give an error.
Since you should do your homework yourself, I did not post source code, only explanations ;)
I think you just need this --
for ( int i = 0 ; i < p.length(); i++ ) {
char c = p.charAt(i);
if ( c == '(' )
push('(');
else if ( c == ')' ) {
if ( isStackEmpty() ) {
// Return error here because of unbalanced close paranthesis
}
pop();
}
else {
// do nothing
}
}
You CAN use a stack if you must, but considering how simplistic this is, you just need a counter that you increment and decrement and check for 0 at the end.
If you do use a counter, you should check after every decrement if the value is less than 0. If so, throw an error.
Edited based on Ryan/Dave Ball's comments.
It could be done like this:
String equation = "(2+3))";
Integer counter = 0;
//while(equation)
for(int i=0; i<equation.length();i++)
{
if(equation.charAt(i)=='(')
{
counter++;
}
else
if(equation.charAt(i)==')')
{
counter--;
}
}
if(counter == 0)
{
System.out.println("Is good!!!");
}
else
{
System.out.println("Not good!!!");
}
}

Categories