[英]Use java scanner at cmd
如何使用以下命令从cmd读取数据
我使用了这种方法,直到到达用户输入并且调试器进入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;
}
尝试这个
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;
}
尝试使用nextLine()
:
while (!(ch = sc.nextLine()).equals("")) {
System.out.print(ch);
sb.append(ch);
}
这样,您可以循环读取,直到读取空字符串为止。
您需要使用某种条件来中断循环,在下面,如果用户输入“ 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.