我正在尝试从可能具有不同字数的文本文件中读取命令。我正在尝试使用 IF 语句,以免数组越界异常。谁能告诉我我做错了什么?谢谢你。这是它发生的代码部分。
read = new Scanner(new File("Phone.txt"));
//this will loop thru file until end of file
while (read.hasNext())
{
whole = read.nextLine().trim();
String[] tokens = whole.split(" ");//array to split up line
command = tokens[0].toLowerCase();//all lines will have at least one word
if (tokens.length > 0)//if more than one word, 2nd will be name
{
name1st.setFirst(tokens[1]);
}
if (tokens.length > 1)//if more than one word, 3rd will be phone #
{
phone = tokens[2];
}
switch (command)
{
case "add":
nameList.add(name1st, phone);
break;
case "locate":
nameList.getValue(name1st);
break;
case "remove":
nameList.remove(name1st);
break;
case "print":
nameList.display();
}//end switch
}//end while