java - 用户对字符数组的输入
问题描述
我正在尝试创建一个程序,该程序将用户的答案用于测试并将其放入 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();
}
}
解决方案
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");
我没有贬低,只是想帮忙。
推荐阅读
- python - 拟合 ColumnTransformer 时出现 ValueError
- python - 讨论 Leetcode 问题作业计划最小难度的更好方法
- javascript - 如何在 Web 组件 java 脚本中将数字转换为其各自的字母
- javascript - 崇高文本中jsx的语法高亮错误
- java - Java Apache FTPClient 大多数下载的文件为空或丢失
- vhdl - VHDL:这两个是等价的吗?
- php - 如何从 curl 响应中读取文件数据?
- python - 如何在 Pycharm 内存错误中增加 Python 程序可用的内存
- python - 如何在 python 中包含带有 bdist_wheel 的外部 shell 脚本?
- php - 带有占位符的 Symfony 翻译不起作用