Break an infinite loop - java

i have an infinite loop something like that:
while(true) {
//do something
}
I would like to be able to break the loop using a key for exaple escape key. I think it could be done using events but as i am new to java i cant do that.
Can anyone help me? Thank you in advance!
In the while loop the program reads a value from usb and then send it over the network using sockets. My program is the server and sends bytes to a client. I want to be able to stop that server with a key!
In the while loop the program reads a value from usb and then send it over the network using sockets. My program is the server and sends bytes to a client. I want to be able to stop that server with a key!

Pure java, by itself, does not have a notion of a key input. You usually get them from a specific IO module (e.g., console based, AWT based, Swing based, etc.).
You would then check for the condition or break.
If your notification of a press is asynchronous, you would probably set some flag (e.g., breakRequested), and check for this flag and break if it has changed.
For Console access, take a look at http://download.oracle.com/javase/6/docs/api/java/io/Console.html
but pay attention to the many questions about this facility here on Stackoverflow.

Use the break keyword. For example:
try {
Console console = new Console();
while(true)
{
String input = console.readLine();
if("quit".equals(input))
{
break;
}
// otherwise do stuff with input
}
catch(IOException e)
{
// handle e
}
Many programmers think the following would be more readable:
try
{
Console console = new Console();
for(String input = console.readLine(); !"quit".equals(input); input = console.readLine())
{
// do stuff with input
}
}
catch(IOException e)
{
// handle e
}

change while(true) to something like while(!isStopped()){...}

Keep in mind, while your application is in that block, and is spinning, no other portion of your application will be able to process instructions. That is unless you spin off your worker process into a new thread and share a variable/flag between the two. That way, when a key is pressed, through whatever means you have in capturing it, you can modify a boolean variable which will carry over to your thread. So you can set your loop up like the following:
while(_flag)
{
//Spin
}

I have created this program that terminates an infinite loop if a specific key is pressed:
class terminator {
public static void main(String args[]) throws java.io.IOException {
char press, clear;
for(;;) {
System.out.print("Press any key to get display, otherwise press t to terminate: ");
press = (char)System.in.read();
System.out.println("You Pressed: "+ press);
do {
clear = (char)System.in.read();
} while(clear != '\n');
System.out.println("\n");
if (press=='t'|press=='T') {
System.out.println("Terminating Program......Program Terminated!");
break;
}
}
}
}

To break infinite loop with a condition.
public class WhileInf {
public static void main(String[] args) {
int i = 0;
while (true) {
if (i == 10) {
break;
}
System.out.println("Hello");
i++;
}
}
}

You can force quit the console if you are in infinite loops.
Window = Ctrl + Shift + Esc
Mac = Option + Command + Esc

while(true)
{
if( )
{
break;
}
else if()
{
break;
}
else
{
do something;
break;
}
}

Related

Im trying to make a text based game that looks like a PC terminal, i cant find a way to tell the user if they use a wrong sentence

//Code up
if (userinput.contains(help)) {
//Go on with the game
}
else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
I tried almost everything a beginner would know and nothing , do while loops not working in my case (maybe you can find a way) , if i let the if like that the game closes if you get the wrong answer (something out of conttext) , some help would be great! Thx :D
You could use a 'Recursive' function (a function that calls itself).
So in this case, you could do something like:
public void getAndParseInput(){
String userInput = getUserInput() // Use whatever you're using to get input
if(userInput.contains(help)){
// If the user input contains whatever the help is (note: if you're looking for the specific word help, it needs to be in speech marks - "help").
continueWithGame...
}else{
System.out.println("Im sorry , couldnt understand that");
this.getAndParseInput();
}
}
You need to put that code inside a while loop and establish an exit condition.
boolean endGame = false;
/* Here read userinput */
While(!endGame) {
if (userinput.contains(help)) {
//Go on with the game
} else if(userinput.contains("quit"){
endGame = true;
} else {
System.out.println("Im sorry , couldnt understand that"); //here is where i want to go back up and
repeat the command
}
/* Here read userinput */
}
The Below code is similar to your code,reuse the code with appropriate changes as you required.
The code works as below.
1. Scans the input from the console
2. Compares the scanned input with the String "help"
3. If scanned input matches with help, then continue with the execution
4. Otherwise, if the user wants to continue then he can press the
letter 'C' and continues with the execution.
5. If user doesn't press 'C', then the control breaks the while loop
and comes out of the execution
public void executeGame() {
Scanner scanner = new Scanner(System.in);
String help = "help";
while(true) {
System.out.println("Enter the input for execution");
String input = scanner.nextLine();
if (input.contains(help)){
System.out.println("Continue execution");
} else {
System.out.println("Sorry Wrong input.. Would you like to continue press C");
input = scanner.nextLine();
if (input.equals("C")){
continue;
} else {
System.out.println("Sorry wrong input :"+input);
System.out.println("Hence Existing....");
System.exit(0);
}
}
}
}

Returning back to the beginning of a loop using "continue" on Java

public void talk() {
String[] prompts = {"Describe to me in a sentence why this is a cool program.",
"Describe to me in a sentence how your day was.",
"Describe to me in a sentence what programming means to you.",
"Describe to me in a sentence why food is neccessary for humans."};
iramInLoop = true;
while(iramInLoop)
{
int i = new Random().nextInt(prompts.length);
System.out.println(prompts[i]);
String input = Raybot.getInput();
if(!checkPunc(input) && !checkCaps(input)){
System.out.println("Check your capitalization and your punctuation!");
}
else{
System.out.println("Great grammar keep it up! Do you want to try again?");
if(input.equals("yes")) continue;
else
{
iramInLoop = false;
Raybot.talkForever();//this exits the loop
}
}
}
}
I am having extreme trouble trying to restart my loop. So at the end of my code when the loop is done running I put a string which asks if the user wants to try again and if the user says yes I want it to go back to the beginning of the loop and do what the loop does again. However, every time I run it it goes to the end of the loop and doesn't even ask for an input.
I think you should be breaking out of the loop if the person guessed right, but then decided not to continue. In this case, your logic should be something like this:
while (true) {
int i = new Random().nextInt(prompts.length);
System.out.println(prompts[i]);
String input = Raybot.getInput();
if (!checkPunc(input) && !checkCaps(input)) {
System.out.println("Check your capitalization and your punctuation!");
}
else {
System.out.println("Great grammar keep it up! Do you want to try again?");
input = Raybot.getInput();
if (input.equals("no")) {
break;
}
}
}
// whatever this does, you intended for it happen after the loop terminates, so do it here
Raybot.talkForever();
You are missing to actually accept any input
maybe
System.out.println("Great grammar keep it up! Do you want to try again?");
input = Raybot.getInput();
change if(input.equals("yes")) continue;
to if(Raybot.getInput().equals("yes")) continue;

Stopping a java program from cmd line with two strings input from user?

Hello and thank you in advance for your time. I'm working on a homework assignment that require an input from the user in command line. If the user input the "Exit" or "Quit" My program should quit. I'm able to do one one work but not sure how to do two. ALso the my loop is not looping all time. Can someone shine some light please.
import java.io.Console;
public class Echo2{
public static void main(String [] args){
String userText = System.console().readLine("Enter some text:");
//System.out.println("*** " + userText + " ***" );
if (userText.equals("Exit")){
return;
}
else{
System.out.println("*** " + userText + " ***" );
}
}
}
As of the loop you can simply do this:
while(true) {
if (userText.equals("Exit") || userText.equals("Quit")) {
break;
}
}
Or if you want to go a little fancy here you can do this
while(true) {
if ("exit".equals(userText.toLowerString()) || "quit".equals(userText.toLowerString()) {
break;
}
}
the 2nd approach is a little more flexi here, as regardless of the what the user types (this being quit, qUit, EXIT, exIT) the program will convert this to lower case and match within the condition specified
Just use the || operator if you want to do more than one check in an if statement:
if (userText.equals("Exit") || userText.equals("Quit")) { ... }
As far as your loop "not looping all the time"; I don't see any loop. Have you failed to include it in your post?

Is there an easy way to exit Java while loop without re-writing much of the code? [duplicate]

This question already has answers here:
How do I exit a while loop in Java?
(10 answers)
Closed 5 years ago.
I am new to Java and programming in general. I've encountered not exactly a problem, but more like a wall of my ignorance. On my QA Automation courses I was asked to write a simple calculator program in Java, I kept it very basic - you needed to launch the program over again every time you preformed a calculation. I learned about while loops and it seemed the while loop was a good solution to keep the program running. But now I am at another extreme - the loop is infinite. My question is: is there any simple way to exit the program without re-writing the code and the way I've structured my calculator? I don't know how to do it but it would be nice if program would end when user presses [Esc] or prints "Exit". Is there a simple way that I (beginner) would understand and could implement?
import java.io.IOException;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
int first, second, answer;
String operator;
Scanner s = new Scanner(System.in);
try {
while (true) {
log("Please enter a math equation using +, -, * or /");
first = s.nextInt(); //User enters first number
operator = s.next(); //User enters operator
second = s.nextInt(); //User enters second number
if (operator.contains("+")) {
answer = first + second;
log("" + answer);
}
if (operator.contains("-")) {
answer = first - second;
log("" + answer);
}
if (operator.contains("*")) {
answer = first * second;
log("" + answer);
}
if (operator.contains("/")) {
if (second == 0) {
log("You can't divide by 0");
} else {
answer = first / second;
log("" + answer);
}
}
}
} catch (java.util.InputMismatchException error) {
log("Incorrect input");
}
}
public static void log(String s) {
System.out.println(s);
}
}
Thank you, if you can help me!
P.S. I don't know if it is a correct way to handle exceptions or a very ugly one. I'd appreciate if you could comment on that too.
Yes, use break:
if(endingCondition)
break;
This will break out of the innermost loop.
In order to follow your example and not deviate from it focusing on other code improvements, you should have to change the way you read the parameters, because the way you do it now, you could never read the exit word to get out. In order to do this you can use the following approach:
This will add a new string parameter to read the exit or the first operand (in string format). Then, it will transform it into an int:
int first, second, answer = 0;
String operator, firstParam = "";
Scanner s = new Scanner(System.in);
try {
while (true) {
System.out.println("Please enter a math equation using +, -, * or /, or exit if you want to stop the program");
firstParam = s.next(); //User enters first number or exit
// This first param is read as a String so that we are able to read the word exit
if(firstParam.equals("exit"))
break;
first = Integer.valueOf(firstParam); // This will transform the first parameter to integer, because if it reaches this point, firstParam won't be "exit"
//[... Rest of your program...]
}
} catch (java.util.InputMismatchException error) { ... }
TIPS FOR ERROR HANDLING
1: You don't have to specify the complete reference of the InputMismatchException while in catch block because you have already imported the java.util package
catch (InputMismatchException e)
{
//handle exception here
}
2: In case you are unsure about the type of Exception that can thrown, just catch the object of class Exception. Since Exception is the super class for all the Exceptions, it can handle all exceptions.. This would work perfectly for beginners.
catch (Exception e)
{
//handle exception
}
3: You can handle multiple exceptions for the same try block, each catch handling a particular type of exception. Give it a try.
FOR EXITING THE LOOP
if (s1.contains("EXIT"))
break;
Here s1 is the string, and if the string contains the word EXIT (ALL CAPS ONLY), the loop will terminate.

How can I exit a Scanner Class to perform the rest of the loop?

I am accessing a Scanner that helps retrieve RFID Tags from an RFID Reader. I tried using a loop around my Scanner.next(); but that wouldn't do anything. I think that once my Scanner accesses the RFID Reader's method, that it just permanently stays in there. Is there any way to exit the method for the RFID and then perform the rest of my loop?
//The beginning of the loop
while (!doneYet) {
//Just a set boolean variable that I try to use later
Inter = false;
//A question class that I created, obtains and displays a random question
Test = Work.randomQuestion();
Test.display();
//This is where my problems seem to start, this is the RFID Readers Method.
rfid.addTagGainListener(new TagGainListener() {
public void tagGained(TagGainEvent oe) {
Temp = oe.getValue();
if (Test.getRFIDTag().equals(Temp)) {
System.out.println("You are Correct");
count++;
System.out.println(count);
Inter = true;
System.out.println("out");
/*
* try { System.in.close(); } catch (IOException e) {
* TODO Auto-generated catch block e.printStackTrace();
* }
*/
} else if (!Test.getRFIDTag().equals(Temp)) {
System.out.println("Sorry, you are wrong");
}
return;
}
});
// Before the RFID Opens though, this code is initiated
rfid.openAny();
rfid.waitForAttachment(1000);
sc = new Scanner(System.in);
//This is where I attempted to control the RFID Reader, but this doesn't work
if(!Inter){
sc.next();
}
//How I attempt to end the initial while loop
if(count>10){
doneYet = true;
}
}
Thanks in advance for all of the help.
Your scanner doesn't actually do anything. sc.next() just skips initial whitespace, and returns the first string of non-whitespace characters; but it just discards that string, never (for example) passing it to rfid. As far as I can see, nothing ever triggers rfid's TagGainListener. (And why do you add a new TagGainListener for each pass through the loop, anyway? Surely you only need one listener?)

Categories

Resources