gpt4 book ai didi

java,在键盘扫描仪未接收输入时创建循环

转载 作者:行者123 更新时间:2023-12-02 01:45:19 24 4
gpt4 key购买 nike

我试图在未收到 Keyboardscanner.nextline() 的情况下进行循环。我被困在这里,因为我找不到解决方案,我什至不知道是否可能......这就是我想要的在代码中执行...

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")
}
}

最佳答案

这将在其他线程中执行任务并接受输入,直到输入为空。另外,请注意关闭扫描仪

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!");
}
}

关于java,在键盘扫描仪未接收输入时创建循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53749172/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com