简体   繁体   English

在cmd使用Java扫描器

[英]Use java scanner at cmd

How to read data from cmd using 如何使用以下命令从cmd读取数据

i used this method and it works fine until it arrive to user input and the debugger get into hasnext and hang 我使用了这种方法,直到到达用户输入并且调试器进入hasnext并挂起为止,它都可以正常工作

public String readCMD() {
    try {
        Scanner sc =new Scanner(in);
        StringBuilder sb = new StringBuilder();
        String ch ;
        while (sc.hasNext()) {
            ch = sc.next();
            System.out.print(ch);
            sb.append(ch);

        }
        return sb.toString();
    } catch (Exception e) {
        System.out.println(e.getCause());
    }
    return null;
}

Try this 尝试这个

public String readCMD() {
    try {
        Scanner sc = new Scanner(System.in);
        StringBuilder sb = new StringBuilder();
        String ch;
        while (sc.hasNext()) {
            ch = sc.next();
            System.out.print(ch);
            sb.append(ch);

        }
        return sb.toString();
    } catch (Exception e) {
        System.out.println(e.getCause());
    }
    return null;
}

Try using nextLine() : 尝试使用nextLine()

while (!(ch = sc.nextLine()).equals("")) {
     System.out.print(ch);
     sb.append(ch);
}

This way you read in a loop until you read an empty string... 这样,您可以循环读取,直到读取空字符串为止。

You need to break out the loop using some condition, here below if user enter "exit" as input then it will break out: 您需要使用某种条件来中断循环,在下面,如果用户输入“ exit”作为输入,则它将中断:

public String readCMD() {
    try {
        Scanner sc =new Scanner(in);
        StringBuilder sb = new StringBuilder();
        String ch ;
        while (sc.hasNext()) {
            ch = sc.next();
            System.out.print(ch);
            sb.append(ch);
            if(ch.equals("exit")) {
              break;
            }

        }
        return sb.toString();
    } catch (Exception e) {
        System.out.println(e.getCause());
    }
    return null;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM