首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何通过用户输入将字符输入到数组中?

如何通过用户输入将字符输入到数组中?
EN

Stack Overflow用户
提问于 2015-04-24 04:42:33
回答 2查看 2.3K关注 0票数 0

这就是我所拥有的,一切都很好,但由于某种原因,我无法将字符输入到数组中。

如果你能向我解释一下为什么它不起作用的话,我们将不胜感激。这样做的目的是将一系列字符输入到数组中,并计算数组中“(间隙)”的数量。

黑体字部分是我目前有问题的地方。

代码语言:javascript
代码运行次数:0
运行
复制
import java.util.*;

public class Test4c{
  public static void main(String[] args){

    Scanner x = new Scanner(System.in);
    Scanner a = new Scanner(System.in);

    int size;

    System.out.println("Please input the size of the array.");
    size = x.nextInt();

    char[] test = new char[size];

    System.out.println("Please input " + size + " characters.");
  //ask user to input number of characters

    for(int i = 0; i<size; i++){
      **test[i] = a.next().toCharArray();**
    }

    int s;
    int e;


    System.out.println("Please input the starting value of the search.");
    s = x.nextInt();

    System.out.println("Please input the ending value of the search.");
    e = x.nextInt();


  }

  public static int spaceCount(char[]arr, int s, int e){
    int count = 0;

    if (s<= e) {
      count = spaceCount(arr,s+1, e);
      /*counter set up to cause an increase of "s" so
       * the array is traversed until point "e"*/

      if (arr[s] == ' ' ) {
        count++;
      }
    }

    return count;// return the number of spaces found
  }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-24 04:50:43

当您强制运行代码时,您将得到这样的错误堆栈。

线程“主”java.lang.RuntimeException中的异常:不可编译的源代码-不兼容类型: char[]不能转换为char at test4c.Test4c.main(Test4c.java:26) Java结果:1

很明显,你为什么会收到这样的信息?

尝试在char[] test索引中插入char数组,接受char,而不是char数组

这就是你所拥有的:

代码语言:javascript
代码运行次数:0
运行
复制
for(int i = 0; i<size; i++){
      test[i] = a.next().toCharArray();
    }

从您所拥有的情况来看,我认为您只想将a.next()转换为char数组,这是您已经定义的test

代码语言:javascript
代码运行次数:0
运行
复制
char[] test = new char[size];

你可以改变你必须改变的东西

代码语言:javascript
代码运行次数:0
运行
复制
test = a.next().toCharArray();
票数 0
EN

Stack Overflow用户

发布于 2015-04-24 04:48:32

问题是toCharArray返回一个数组,而不能将数组放入数组中。试试这个:

代码语言:javascript
代码运行次数:0
运行
复制
Char[] test = a.next().toCharArray();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29838868

复制
相关文章

相似问题

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