很简单的问题,但我老是出小问题,希望解答一下。题目如下:
配置文件恢复__牛客网
配置文件恢复
https://www.nowcoder.com/questionTerminal/ca6ac6ef9538419abf6f883f7d6f6ee5
我的代码:
import java.io.*;
import java.util.*;
public class Main {
public static ArrayList<String> keyList = new ArrayList<>();
public static ArrayList<String> valueList = new ArrayList<>();
public static void main(String[] args) throws IOException{
keyList.add("reset");
keyList.add("reset board");
keyList.add("board add");
keyList.add("board delete");
keyList.add("reboot backplane");
keyList.add("backplane abort");
valueList.add("reset what");
valueList.add("board fault");
valueList.add("where to add");
valueList.add("no board at all");
valueList.add("impossible");
valueList.add("install first");
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
String line = sc.nextLine();
String result = getResult(line);
System.out.println(result);
}
}
public static String getResult(String line){
if(line == null || line.length() == 0){
return null;
}
String[] strs = line.split(" ");
if(strs.length == 1){
String s = strs[0];
String res = getAnswer(s);
return res;
}else if(strs.length == 2){
String s1 = strs[0];
String s2 = strs[1];
String res = getAnswer(s1,s2);
return res;
}else{
return "unknown command";
}
}
public static String getAnswer(String s){
for(int i=0;i<keyList.size();i++){
String key = keyList.get(i);
if(key.split(" ").length >1){
continue;
}else if(key.startsWith(s)){
return valueList.get(i);
}
}
return "unkonwn command";
}
public static String getAnswer(String s1,String s2){
int count = 0;
int index = 0;
for(int i=0;i<keyList.size();i++){
if (keyList.get(i).split(" ").length != 2){
continue;
}
String key1 = keyList.get(i).split(" ")[0];
String key2 = keyList.get(i).split(" ")[1];
if(key1.startsWith(s1)){
if(key2.startsWith(s2)){
count++;
if(count == 1){
index = i;
}
}
}
}
if(count == 1){
return valueList.get(index);
}else{
return "unkonwn command";
}
}
}
想知道为什么输出结果与预期不一致?是我的输出格式有问题吗?