无限循环混乱中的Java分裂方法
我正在开始一个Java项目,用户进入一家宠物店,可以送一只宠物,查看所有宠物的列表,领养一只,或者离开宠物店。由于在一个命令输入中需要多条信息,因此用户给出的每个命令都按空格分割。我认为这会创建一个字符串数组,其中输入中的每个单词都是一个单独的元素
import java.util.*;
public class Main {
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
while(true) {
System.out.println("Welcome to James' Pet Shop.");
System.out.println("Commands:\n give [type (Str)] [name (Str)] [age (in months, int)]\n list\n adopt [type (Str)] [name (Str)] [age (in months, int)]");
String input = s.next();
String[] inputs = input.split(" ");
if (inputs[0].equals("give")) {
} else if (inputs[0].equals("list")) {
} else if (inputs[0].equals("adopt")) {
} else if (inputs[0].equals("bye")) {
System.out.println("Thank you for stopping bye!");
break;
} else {
System.out.println("Error: please enter an appropriate command to continue");
}
}
}
public static void list() {
}
public static void adopt() {
}
}
然而,当我运行代码并输入多个单词(用空格分隔)时,它能够测试元素0是否是某个命令并遵循该条件(即,如果第一个单词是“give”、“list”等,它将遵循该路径,然后循环并重新开始,直到用户说“bye”),但是,如果要打印出作为输入键入的数组中的第二个单词index 1,它会给出错误:线程“main”java中的异常。lang.ArrayIndexOutofBounds异常:1在Main。main(main.java:30)。我发现一件奇怪的事情是,如果我绕过这个错误,再次打印第一个单词索引0,然后输入多个单词,它会将输入中的每个元素都视为元素0,并且循环循环次数与输入中给定的元素/键入的单词数相同。我很困惑
例1
String input = s.next();
String[] inputs = input.split(" ");
if (inputs[0].equals("give")) {
//if you type give and another word
//instead of printing out the latter, it gives an error
System.out.println(input[1]);
} else if (inputs[0].equals("list")) {
例2
String input = s.next();
String[] inputs = input.split(" ");
if (inputs[0].equals("give")) {
//instead of printing the first element and then taking more input
//if the first word is give, and
//overwriting the String array inputs, it instead prints out
//your first word, then cycles back through and treats the
//subsequent words as input 0.
//if you type "give giver", it will first print the beginning instructions,
//then print give because it satisfies that conditional,
//and then cycle back through the instructions and print
//Error: please enter an appropriate command to continue
System.out.println(input[0]);
} else if (inputs[0].equals("list")) {
# 1 楼答案
这是因为您正在使用函数s.next();在这里,它只返回单词,直到遇到空格。因此,只输入第一个命令
要解决此问题,请使用以下代码:-
这会管用的。请记住,next()用于输入一个单词,而nextLine()用于输入多个单词