我正在尝试为我的项目编写一个简单的代码 如果用户输入
步行10
我需要在步行(距离)方法中使用“walk”命令作为距离= 10 我有类似的东西
while (!quit) {
Scanner in = new Scanner(System.in);
String input = in.nextLine();
// if (walk x is typed) {
walk(x);
}
}
我正在使用java.util.scanner 另一个问题是我的方法walk(int x)使用int 所以我需要将String输入转换为int
我在网上搜索了一段时间,但无法找到我正在寻找的东西(或者我不理解它)
所以无论如何,如果你能帮助我,我会很感激
非常感谢所有答案我的初步问题得到解决 但现在我有另一个问题 当我键入“walk”时,它会获得数组超出范围的异常 当然因为它试图将null转换为int(不可能) 我试过这个并在线查看
try {
Integer.parseInt(splitStrings[1]);
}
catch(NumberFormatException e) {
System.out.println("error: " + e);
}
仍然没有帮助(我对尝试/捕获不好) 所以如果用户类型走路没有距离我需要给出一个错误信息 非常感谢
好吧,我也明白了 只是用了一件简单的事情 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");
}
}
答案 0 :(得分:7)
您可以拆分空格,在这种情况下,数字将是结果数组的第二个元素(索引1),例如。
编辑Adam Liss的以下评论
Integer x = Integer.parseInt(input.split(" ")[1])
答案 1 :(得分:7)
尝试对字符串使用split()方法。它将返回一个字符串数组。例如
String s = 'walk 10';
String[] splitStrings = s.split(" ")
现在,要访问10,您可以这样做:
String distanceToWalk = splitStrings[1]
要将其转换为int,请使用Integer上的parseInt()方法
Integer.parseInt(distanceToWalk);
见
答案 2 :(得分:1)
您可以使用Integer.parseInt()
方法:
int distance = Integer.parseInt(input);
答案 3 :(得分:0)
尝试:
String s = 1;
int i = Integer.parseInt(s); // returns 1
答案 4 :(得分:0)
假设你从字符串中去掉整数部分,例如留下
的输入“步行10”和“10”,只需使用类似
的内容// say you've parsed the "number" portion into a variable "inputString"
int x;
x= Integer.parseInt(inputString);
答案 5 :(得分:0)
您可以使用:
// For read the input
InputStreamReader streamReader = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(streamReader);
String input = reader.readLine();
如果您更喜欢使用Scanner
,那么
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
然后:
StringTokenizer st = new StringTokenizer(input);
if (st.countTokens == 2) { // Only for two tokens "walk 100", "return 10"
String method = st.nextToken();
if (method.equals("walk") { // if you have more methods like "walk"
int distance = Integer.parseInt(st.nextToken());
walk(distance); // walk
}
}
如果你想阅读更多行
for(String input; sc.hasNextLine();) {
input = sc.nextLine();
// do something
}
或者
for(String input; (input = reader.readLine()) != null;) {
// do something
}