Java,在Keyboardscanner未收到输入时创建循环

时间:2018-12-12 18:25:31

标签: java

我正在尝试在未收到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")
            }       
        }  

2 个答案:

答案 0 :(得分:1)

这将在其他线程中执行任务并接受输入,直到输入为empty。另外,请注意关闭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!");
    }
}

答案 1 :(得分:1)

// 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;
        }
    }
}