Ber*_*van 3 java string split input
i'm trying to write a simple code for my project if user types
walk 10
i need to use "walk" command in my walk(distance) method as distance = 10 i have something like that
while (!quit) {
Scanner in = new Scanner(System.in);
String input = in.nextLine();
// if (walk x is typed) {
walk(x);
}
}
Run Code Online (Sandbox Code Playgroud)
i'm using java.util.scanner and another problem is that my method walk(int x) uses int so i need to convert String input to int
i searched the web for a while but couldnt find what i'm looking for (or i didnt understand it)
so anyway i'd appreciate if you can help me thanks
非常感谢所有的答案我的最初的问题是修复但现在我有另一个问题, 当我键入只是"步行"它得到数组超出界限当然因为它试图将null转换为int(不可能)我试过这个并在线检查
try {
Integer.parseInt(splitStrings[1]);
}
catch(NumberFormatException e) {
System.out.println("error: " + e);
}
Run Code Online (Sandbox Code Playgroud)
仍然没有帮助(我对尝试/捕获不好)所以如果用户类型走路没有距离我需要给出一个错误消息再次感谢
好吧,我得到它也只是使用一个简单的事情
if ("walk".equals(splitStrings[0])) {
if (splitStrings.length == 2) {
int distance = Integer.parseInt(splitStrings[1]);
Robot.walk(distance);
}
if (splitStrings.length != 2) {
System.out.println("Entry must be like walk 10");
}
}
Run Code Online (Sandbox Code Playgroud)
您可以在空间上拆分,在这种情况下,数字将是结果数组的第二个元素(索引1),例如
编辑Adam Liss的以下评论
Integer x = Integer.parseInt(input.split(" ")[1])
Run Code Online (Sandbox Code Playgroud)
尝试对字符串使用split()方法.它将返回一个字符串数组.例如
String s = 'walk 10';
String[] splitStrings = s.split(" ")
Run Code Online (Sandbox Code Playgroud)
现在,要访问10,您可以这样做:
String distanceToWalk = splitStrings[1]
Run Code Online (Sandbox Code Playgroud)
要将其转换为int,请在Integer上使用parseInt()方法
Integer.parseInt(distanceToWalk);
Run Code Online (Sandbox Code Playgroud)
看到