my problem ist that my while loop just runs one time when I run it. Here is my code. I would be very thankful if someone would check it and maybe look for other faults (i'm new at programming java!)
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Program {
boolean exit;
JFrame frame;
JPanel panel;
JTextField title;
JButton start;
JButton stop;
long x;
public Program() {
frame = new JFrame("Überlast your PC");
panel = new JPanel();
title = new JTextField("Überlast your PC v1.0");
start = new JButton("Start");
stop = new JButton("Stop");
x = 1;
exit = false;
stop.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
exit = true;
}});
start.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e) {
panel.remove(start);
panel.add(stop);
frame.repaint();
frame.revalidate();
start.setForeground(Color.red);
while(x <= 9223372036854775807L) {
System.out.println(x * x);
x++;
if (exit = true) {
break;
}
}
}});
frame.add(panel);
panel.add(title);
panel.add(start);
frame.setVisible(true);
frame.setSize(150,100);
title.setEditable(false);
start.setForeground(Color.green);
stop.setForeground(Color.red);
}
}
if(exit = true) {
break;
}
should be
if(exit == true) {
break;
}
Or even simpler, just use
if(exit){
break;
}
exit=true assigns true to exit, thus the if condition is true thus it breaks outta of the loop.
As #jlordo pointed, even after fixing the error its an infinite loop.
if(exit = true)
This is the first problem. The above if condition will always be true. You need to do comparison instead of assignment. In fact you should not do comparison for boolean variable. Just use: -
if (exit)
Secondly, you are not changing your exit anywhere in your while loop, so, it doesn't make sense for using it as a exit condition.
And you don't need to hard code the value of Long.MAX_VALUE. You already have that constant defined. Now, even if you get through that problem of if, you will face the problem of infinite loop. See below how: -
// Your below while loop is `infinite`
// every long value will satisfy this condition
while(x <= Long.MAX_VALUE) { // Don't hard code max long value
System.out.println(x * x);
x++;
// You are not changing `exit` anywhere, so this check is absurd.
if (exit) {
break;
}
}
What probably you want: -
Probably you want to run your loop infinitely, until your exit value if false. In that case, just use while (true). And change the value of exit somewhere in your loop.
In fact, if you are using exit as exit criteria, I would change your while loop to: -
while (exit) {
System.out.println(x * x);
if (someCondition) {
exit = false;
}
}
you are using
if(exit = true) {
instead of
if(exit == true) {
or even better
if (exit) {
But when you fix it, you will have an infinite loop, because all long values are smaller than 9223372036854775807, which is the the highest value long can have.
It is because of this line:
if(exit = true)
You are assigning true to exit here. Use == for comparing values:
if(exit == true)
And in the case of boolean values, you don't need to compare it to true at all. Write it like this:
if(exit)
if (exit = true) will set the value exit to true. You need to compare using ==
Related
I'm making an escape room through the console.
I'm trying to run an if statement, and I want to have the if statement code run once, and then run the else code forever afterward. My program is looped to go back to the same menu after it's finished with a choice the user chooses.
Here is my current code:
if (checkBedDraw = false) {
clear();
typePrint("You found a \u001b[34mpicklock\u001b[0m! you can only use this on a specific lock, because of its shape. This item has been added to your \u001b[31minventory\u001b[0m.", 50);
invArray[0] = "picklock";
checkBedDraw = true;
} else if (checkBedDraw = true) {
typePrint("You have already checked the drawers, and aqcuired a picklock.", 50);
}
typePrint() and clear() are methods I made.
= and ==
Be careful, in if statements you have to use == as = is used to assign a value to a variable.
Also, you are dealing with Boolean so you can just do something like this:
if (checkBedDraw) {
typePrint("You have already checked the drawers, and aqcuired a picklock.", 50);
} else {
clear();
typePrint("You found a \u001b[34mpicklock\u001b[0m! you can only use this on a specific lock, because of its shape. This item has been added to your \u001b[31minventory\u001b[0m.", 50);
invArray[0] = "picklock";
checkBedDraw = true;
}
Because of many boolean checks i am a little confused, let me introduce me to my next code.
} else {
//check whether the player starts again. the first time we lose the player
//will definitely get into this loop
if(!startAgain){
// we only do this to set a timer, we don't want to start a new game so we set this
// to false
newgame = false;
startAgain = true;
deadTime = System.nanoTime();
}
deadTimepassed = (System.nanoTime() - deadTime)/1000000;
if((deadTimepassed < 2000) && (newgame = false)){
newGame();
}
}
}
This else statement can be seen as the first time a player gets hit by an enemy missile. To make an explosion-animation. I need te screen to freeze for 2 seconds and then start the game over again. I don't see why the second if statement is never reached. Here are my ontouch methods and my new game method:
#Override
public boolean onTouchEvent(MotionEvent event) {
//What happens when the player touches the screen!
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// Boolean check for when player is playing, if he isn't the chopper does nothing.
// we see that the chopper only hangs still if all these booleans are true!
if ((!player.isPlaying()) && (newgame = true) && (startAgain = true)) {
player.setPlaying(true);
} if(player.isPlaying()) {
player.setUp(true);
startAgain = false;
}
return true;
}
if (event.getAction() == MotionEvent.ACTION_UP) {
player.setUp(false);
return true;
}
return super.onTouchEvent(event);
}
public void newGame(){
newgame = true;
missles.clear();
if(player.getScore()>best) {
best = player.getScore();
SharedPreferences.Editor editor = saveBest.edit();
editor.putInt("new best",best);
editor.commit();
}
player.resetScore();
player.setY(HEIGHT/2);
}
As one can see, the new game just resets the players position, the only thing i want to do is just freeze the screen for 2 seconds before that happens, this is supposed to happen in the second if statement but it never get reached...
Any suggestions?
ps: deadTimepassed is introduced as 'private long' just beneath the public class method.
For freeze your Thread (so, the program will be freeze, also your screen) during 2 seconds you can use Thread.sleep() function:
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
You have to put it inside a try-catch block because it can gives to you an InterruptedException.
I expect it will be helpful for you!
please see my attached code below and then my question at the end.
class events extends JFrame{
private JLabel label;
private JButton button;
public events() {
setLayout(new FlowLayout());
button = new JButton("Click for text");
add(button);
label = new JLabel("");
add(label);
event e = new event();
button.addActionListener(e);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
int x = 0;
if (x == 0) {
label.setText("the new label");
System.out
.println("setting x to 0 and label to display a label");
x = 1;
System.out.println(x);
} else {
label.setText("newerer label");
System.out.println("i reached the else segment");
x = 0;
System.out.println(x);
}
}
}
public static void main(String args[]) {
events gui = new events();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setTitle("Events Test");
gui.setSize(300, 100);
gui.setVisible(true);
}
}
Background: I am learning java and attempting to understand a concept. With this program I was attempting to create a small gui with a button that when clicked would assign a JLabel the String value of "the new label." I wanted to use that same button however to change the label to "newerer label" if clicked a second time and back again if clicked a third. I attempted to do this using an If/ Else statement with a variable x to hold essentially a state of 1 or 0. At the end of each portion of the If/Else i change the state of x to either 1 or 0 appropriately. When attempting to run the program in eclipse however, I have run into some kind of error. I assigned a system.out.println to each portion of the If/Else in an attempt to see how the program switches between the two states but it appears that my else statement is never reached.
Questions:
Is an If/Else statement appropriate to perform such a simple 2 state switch?
Is there a more appropriate way to do this? (i know about switch statements but opted for this as it was only a two state project).
What did I do wrong and why is my Else path never achieved when the state should be 1?
Thank you for your responses,
Pano
Your variable "x" must be declared as a class member.
public class event implements ActionListener{
private int x = 0;
public void actionPerformed(ActionEvent e){
if(x == 0){
label.setText("the new label");
System.out.println("setting x to 0 and label to display a label");
x = 1;
System.out.println(x);
}
else {
label.setText("newerer label");
System.out.println("i reached the else segment");
x = 0;
System.out.println(x);
}
}
}
You are initializing x every time the action listener gets called, so x is always 0. Move x somewhere else, possibly declare it as a class member.
Yes, I personally would use an if/else statement here, although if you are likely to add more states a switch statement may be appropriate, but I think given you have more than 1 line of code in the if/else blocks I would keep it as if/else as it has better readability in my experience.
I guess my answer to 1 covers this!
The reason your else block isn't being reached is that your x variable is only in scope (only exists) inside that method. As soon as you leave the method the value is no longer in scope so as far as your code in concerned it no longer exists. The code P Lalonde posted shows the correct way: having the variable as a member variable (object scope). Read more about member variable scope here: http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html
If you are just looking for a switch of state you could actually do something like:
if( label.getText().equals("the new label") ) {
label.setText("newerer label");
} else {
label.setText("the new label");
}
I am making a real time graph with values that come in via serial communication. I have the data coming in called my "Celsius" value. I am displaying that on the GUI in a JLabel, so the value constantly changes. The problem I am having is I want to have buttons that can change the value in the JLabel to Fahrenheit or back to Celsius. So right now, I have my actionPerformed calling the updateTemp() method so it will update the JLabel right away when the program beings. I have the code below for the 3 methods I think need to be changed around.
public void actionPerformed(final ActionEvent e) {
updateTempC();
final Double n = serial.x;
series.addOrUpdate(new Millisecond(), n);
Object source = e.getSource();
if (e.getSource() == buttonF){
degree.setText("degrees F");
updateTempF();
}
if (e.getSource() == buttonC){
degree.setText("degrees C");
updateTempC();
}
}
public void updateTempF(){
int step1;
int step2;
int step3;
String indata = serial.temp;
int temp = Integer.parseInt(indata);
step1 = temp*9;
step2 = step1/5;
step3 = step2 + 32;
String indata1 = Integer.toString(step3);
this.realtime.setText(indata1);
}
public void updateTempC(){
String indata = serial.temp;
this.realtime.setText(indata);
}
Right now when I press the JButton to change to Fahrenheit, it changes for a second but then goes right back to displaying Celsius because the graph is updated every second and the actionPerformed will go right back to calling the updateTempC(). I am wondering how, when I hit the button for Fahr. or Cels., it will change for the rest of the time. THanks
You should have a variable like boolean fahrenheitTemp. When buttonF is clicked, fahrenheitTemp will be set to true. When buttonC is clicked, fahrenheitTemp will be set to false. If fahrenheitTemp is true, call updateTempF(), else call updateTempC(). (Also, you have a Object source variable, but you never use it.)
Try modifying your actionPerformed(ActionEvent) to something like this:
boolean fahrenheitTemp = false;
public void actionPerformed(final ActionEvent e) {
if (fahrenheitTemp) {
updateTempF();
} else {
updateTempC();
}
final Double n = serial.x;
series.addOrUpdate(new Millisecond(), n);
Object source = e.getSource();
if (source == buttonF) {
degree.setText("degrees F");
fahrenheitTemp = true;
updateTempF();
} else if (source == buttonC) {
degree.setText("degrees C");
fahrenheitTemp = false;
updateTempC();
}
}
Okay, I've got this game loop which never terminates --
public void run() {
setup();
addMouseListeners();
int Turns = NTURNS;
int TotalBricks = NBRICKS_PER_ROW * NBRICK_ROWS;
while ((Turns>0) && (TotalBricks>0)) {
moveBall();
checkForCollision();
pause(DELAY);
}
System.exit(0);
}
-- even though I have this method decrementing the Turns value every time the ball is missed:
private void checkForCollision() {
GObject collider = getCollidingObject();
if (collider !=null) {
if (collider == Paddle) {
vy= -vy;
}
else {
vy= -vy;
remove(collider);
TotalBricks = TotalBricks - 1;
}
}
if((ball.getX()>=(WIDTH-BALL_RADIUS)) || (ball.getX()<=0)) {
vx = -vx;
}
if(ball.getY()<=0) {
vy = -vy;
}
if(ball.getY()>=HEIGHT) {
Turns = Turns -1;
remove(ball);
newBall();
}
}
plus this
private int Turns;
at the bottom to ensure that the variable is shared among both methods.
No matter how many times the ball is missed, the game never stops.
What am I missing?
Thx
You are declaring a new Turns variable in your run method which is what is getting used by that method since it has a more local scope. This is called variable shadowing. Use a decent Java IDE like Eclipse and it will warn you when you do this. It's almost always a mistake.
http://www.xyzws.com/Javafaq/what-is-variable-hiding-and-shadowing/15
You're declaring your Turns variable twice, once for the entire class and once for the the run() method. Since you are also checking the value of the Turns variable that you've declared in the run() method, it never decreases because the one being used in checkForCollision() isn't the one that's being checked in the while loop.
In run(), this:
int Turns = NTURNS;
needs to be:
Turns = NTURNS;