用户输入到字符数组

时间:2018-10-15 18:47:29

标签: java

我正在尝试创建一个程序,该程序将用户的答案用于测试,并将其放入char数组中,然后将其与具有答案的数组进行比较。 我将用户的Answers输入到char数组中时遇到问题。我不断收到EE,说in.nextLine(); -没有找到任何行,并且没有引发此类元素异常。

import java.util.Scanner;
public class driverExam {
public static void main(String[] args) {
    System.out.println("Driver's Test. Input your answers for the following 
10 Q's. ");
    System.out.println();

    char[] testAnswers = {'B','D','A','A','C','A','B','A','C','D'};
    int uA =9;
    String userInput;


    for (int i =0; i<uA;i++) {
            Scanner in = new Scanner(System.in);
            System.out.print("Question #"+(i+1)+": ");
            userInput = in.nextLine();
            in.close();

            int len = userInput.length();
            char[] userAnswers = new char [len];
            for(int x =0;x<len;x++) {
            userAnswers[i] = userInput.toUpperCase().charAt(i);
            }
            System.out.println(userAnswers);
        }
    System.out.println("Your answers have been recorded.");
    System.out.println();
    }
}

1 个答案:

答案 0 :(得分:1)

userAnswers数组的大小是否应为10? 据我说,您的程序有很多多余和不必要的步骤。因此,我对其进行了修改以满足您的需求。 无需将“ Scanner in ....”放入循环中。

此循环充满错误。不劝阻,只是说。

     for (int i =0; i<uA;i++) 
     {
        Scanner in = new Scanner(System.in);//scanner inside loop
        System.out.print("Question #"+(i+1)+": ");
        userInput = in.nextLine();
        in.close();//already mentioned by someone in the comment
        int len = userInput.length();
        char[] userAnswers = new char [len];//no need to declare array inside loop
        for(int x =0;x<len;x++) 
        {
           userAnswers[i] = userInput.toUpperCase().charAt(i);
        }
  }

    System.out.println(userAnswers);//this will not print the array,it will print 
    //something like [I@8428 ,[ denotes 1D array,I integer,and the rest of it has 
     //some meaning too

现在这是完成工作的代码

char[] testAnswers = {'B','D','A','A','C','A','B','A','C','D'};
int uA =testAnswers.length;//to find the length of testAnswers array i.e. 10
char[] userAnswers = new char [uA]; 
char userInput;
int i;
Scanner in = new Scanner(System.in);
for (i =0; i<uA;i++) 
 {           
        System.out.print("Question #"+(i+1)+": ");
        userInput = Character.toUpperCase(in.next().charAt(0));
 }

  for(i=0;i<ua;i++) 
  {
       System.out.println(userAnswers[i]);
  }
  System.out.println("Data has been recorded");

我并没有贬低,只是想提供帮助。