I want to make an infinite loop of a message and stops it if a user inputs a character for example "x". But its getting an error on the if statement saying that it is an unreachable code. Can someone help me.
import java.util.Scanner;
public class Loop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char y;
while (true) {
System.out.println("Good Morning!!!");
}
y = input.next().charAt(0);
if (y == 'y') {
break;
}
}
}
CodePudding user response:
Your if
statement is not inside the while
loop:
import java.util.Scanner;
public class Loop {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char y;
while (true) {
System.out.println("Good Morning!!!");
y = input.next().charAt(0);
if (y == 'y') {
break;
}
}
}
}
CodePudding user response:
Acknowledgement
A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). Read more about threads here
Solutions
Because both input & loop blocks the thread, you have to put them in seperate thread. Just like this :-
public class Demo {
volatile static char input;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
new Thread(new Runnable() {
@Override
public void run() {
while (input != 'y'){
System.out.println("Good morning !");
}
}
}).start();
input = scanner.next().charAt(0);
}
}
This will print "Good morning !" until the input != 'y'
. On the other hand, we are reading the input from user. As user enteres 'y', the condition get false and loop stops.
CodePudding user response:
Try this.
public static void main(String[] args) throws IOException {
InputStream input = System.in;
while (true) {
System.out.println("Good Morning!!!");
if (input.available() > 0 && input.read() == 'y')
break;
}
}