Reputation: 11
I´m trying to make a loop while keyboardscanner.nextline() is not received.I am stuck in here because i cant find a solution, i dont even know if it is possible... here is what im trying to do in code...
public String messagingread(String username) throws RemoteException {
Scanner keyboardScanner = new Scanner(System.in);
try {
while (keyboardScanner.nextLine().isEmpty) {
System.out.println("cant get in here");
//i can only get in here if the scann is only an enter(isempty), but i //want to get in here if i dont scan anything...i dont want isempty i want not //defined and i dont know how to do it ....
}
System.out.println("pls help")
}
}
Upvotes: 0
Views: 45
Reputation: 994
this will execute a task in other thread and accept inputs till the input is empty
. Also, be aware of closing Scanner
class Task implements Runnable {
private boolean shouldRun = true;
public void stop() {
this.shouldRun = false;
}
@Override
public void run() {
while (this.shouldRun) {
try {
Thread.sleep(1000);
System.out.println("Doing some work every 1 second ...");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Task have been stopped, Bye!");
Thread.currentThread().interrupt();
}
}
public final class Example {
public static void main(String[] args) {
Scanner keyboardScanner = new Scanner(System.in);
try {
Task task = new Task();
// run the task on new Thread
Thread newThread = new Thread(task);
newThread.start();
/*
read lines while it is not empty:
(line = keyboardScanner.nextLine()) -> assign the input to line
!(line ...).isEmpty() -> checks that line is not empty
*/
System.out.println("Give me inputs");
String line;
while (!(line = keyboardScanner.nextLine()).isEmpty()) {
System.out.println("new line read :" + line);
}
// when you give an empty line the while will stop then we stop
// the task
task.stop();
} finally {
// after the piece of code inside the try statement have finished
keyboardScanner.close();
}
System.out.println("Empty line read. Bye!");
}
}
Upvotes: 1
Reputation: 18255
// retrieve not empty line
public static String messagingread(String username) {
try (Scanner scan = new Scanner(System.in)) {
while (true) {
String line = scan.nextLine();
// do it while line is empty
if (!line.isEmpty())
return line;
}
}
}
Upvotes: 1