I was wondering if I could make it so a loop can end with typing in a command like end or -1. What I have now is
while ( gradeCounter <= 10 ) // loop 10 times
I would like to know how to have it loop infinitely till I end it.
I was wondering if I could make it so a loop can end with typing in a command like end or -1. What I have now is
while ( gradeCounter <= 10 ) // loop 10 times
I would like to know how to have it loop infinitely till I end it.
Simply create a while loop and a condition to break it
while(true){
String inputString = //Get user input here
if(inputString.equals("Your Termination Text"))
break;
}
If you want to know how to get console input here is one method Java: How to get input from System.console()
double grades = 0;
int entries = 0;
while(true){
String inputString = //Get user input here
if(inputString.equals("Your Termination Text"))
break;
else{
grades += Double.parseDouble(inputString);
entries++;
}
}
double averageGrade = grades / entries;
Please keep in mind that this does not account for text that is not a number and also not your termination text. From the question it sounds like a low level CIS class and I don't think this will be an issue. If it is however you need to learn how to do try catch and some more input validation.
While(true) {}
creates an infinite loop. A break
command inside the loop breaks out of it. You'll have to detect whatever sort of event will occur inside the loop to determine if you should break.
I don't know what you're doing on a larger scale, but it could be a better idea to use Threads which don't loop infinitely and suck up processing power.
Yes, it is possible. Just make sure, there is a different thread that can handle some kind of input...
public class MyBreakableInfiniteLoop
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
new Thread(r).start();
System.out.println("Press Enter to stop thread");
new Scanner(System.in).readLine();
r.stop = true;
}
public static class MyRunnable extends Runnable {
public volatile boolean stop = false;
public void run() {
while(!stop) {
//do nothing, preferably in a meaningful way
}
}
}
}
(aLso, I didn't take into count kill -9
as "input that breaks the infinite loop"...)