首页 > 解决方案 > 用户对字符数组的输入

问题描述

我正在尝试创建一个程序,该程序将用户的答案用于测试并将其放入 char 数组中,然后将其与带有答案的数组进行比较。我在将用户的答案输入 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();
    }
}

标签: java

解决方案


userAnswers 数组的大小不应该是 10 吗?据我说,你的程序有很多多余和不必要的步骤。所以我已经修改它以满足您的需要。无需将“扫描仪放入....”循环中。

这个循环充满了错误。不气馁,只是说。

     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");

我没有贬低,只是想帮忙。


推荐阅读