验证来自添加到阵列的扫描仪的用户输入

时间:2018-10-17 02:25:56

标签: java arrays arraylist java.util.scanner

我正在创建一个考试程序,测试答案存储在一个数组中,而用户答案存储在一个单独的数组中。

我正在尝试编写程序,以便在每个问题之后将用户的答案加载到数组中,除非他们输入的内容不是“ A”,“ B”,“ {{1 }}”或“ C”。如果他们没有输入这些值之一,那么将再次询问该问题。我很困。

这是我的代码:

D

我尝试创建一个数组列表,然后使用if循环再次询问Q。事情是我对ArrayList不太熟悉。

String[] testAnswers = {"B","D","A","A","C","A","B","A","C","D"};
int uT = testAnswers.length; 
String[] userAnswers = new String[uT];

for (int i=0; i<uT;i++) {
System.out.print("Question #"+(i+1)+": ");

userAnswers[i] = in.nextLine();
userAnswers[i] = userAnswers[i].toUpperCase();

}

我尝试过的另一件事是使用布尔变量和/或使用do / while循环,但是我似乎无法弄清楚该怎么做。我认为这是我将for (int i=0; i<uT;i++) { System.out.print("Question #"+(i+1)+": "); userAnswers[i] = in.nextLine(); userAnswers[i] = userAnswers[i].toUpperCase(); List<String> list = Arrays.asList(userAnswers); while (!list.contains("A") || !list.contains("B") || !list.contains("C") || !list.contains("D")) { System.out.println("Invalid Input. "); System.out.print("Question #"+(i+1)+": "); userAnswers[i] = in.nextLine(); userAnswers[i] = userAnswers[i].toUpperCase(); } } 直接放入破坏代码的数组中的事实。

userInput

2 个答案:

答案 0 :(得分:2)

使用while循环,仅在输入正确的情况下递增

String[] testAnswers = {"B","D","A","A","C","A","B","A","C","D"};
int uT = testAnswers.length; 
String[] userAnswers = new String[uT];

int i = 0;
while(i<uT) {
    System.out.print("Question #"+(i+1)+": ");

    String input = in.nextLine();
    input = input.toUpperCase();
    if (input.equals ("A") || input.equals ("B") ...) {
        userAnswers[i] = input;
        i++;
    }
    else {
        System.out.println ("Enter again");
    }

}

答案 1 :(得分:2)

我会选择这样的东西:

for (int i=0; i<uT;i++) {
    System.out.print("Question #"+(i+1)+": ");
    String userCurrentAnswer = in.nextLine();

    while (!userCurrentAnswer.matches("(?i)[A|B|C|D]")) {
        System.out.println("Invalid Input. ");
        System.out.print("Question #"+(i+1)+": ");
        userCurrentAnswer = in.nextLine();
    }
    userAnswers[i] = userCurrentAnswer.ToUpperCase();
}

userCurrentAnswer.matches("(?i)[A|B|C|D]")用于匹配任何不区分大小写的字符