首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Char数组的用户输入

Char数组的用户输入
EN

Stack Overflow用户
提问于 2018-10-16 02:47:29
回答 1查看 163关注 0票数 -1

我正在尝试创建一个程序,该程序接受用户的答案并将其放入char数组中,然后将其与具有答案的数组进行比较。我在将用户的答案输入char数组时遇到了问题。我一直收到一个EE,说in.nextLine();-没有找到任何行,它抛出一个没有这样的元素异常。

代码语言:javascript
复制
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();
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-16 03:25:32

userAnswers数组的大小不应该是10吗?在我看来,你的程序有很多多余和不必要的步骤。因此,我对其进行了修改,以满足您的需求。不需要把“扫描仪放入...”在循环中。

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

代码语言:javascript
复制
     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

下面是完成这项工作的代码

代码语言:javascript
复制
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");

我不是在贬低你,我只是想帮忙。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52822985

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档