我正在尝试创建一个程序,该程序接受用户的答案并将其放入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();
}
}
发布于 2018-10-16 03:25:32
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");
我不是在贬低你,我只是想帮忙。
https://stackoverflow.com/questions/52822985
复制相似问题