How to read data from cmd using
i used this method and it works fine until it arrive to user input and the debugger get into hasnext and hang
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()
:
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:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.