这就是我所拥有的,一切都很好,但由于某种原因,我无法将字符输入到数组中。
如果你能向我解释一下为什么它不起作用的话,我们将不胜感激。这样做的目的是将一系列字符输入到数组中,并计算数组中“(间隙)”的数量。
黑体字部分是我目前有问题的地方。
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
}
}
发布于 2015-04-23 20:50:43
当您强制运行代码时,您将得到这样的错误堆栈。
线程“主”java.lang.RuntimeException中的异常:不可编译的源代码-不兼容类型: char[]不能转换为char at test4c.Test4c.main(Test4c.java:26) Java结果:1
很明显,你为什么会收到这样的信息?
尝试在char[] test
索引中插入char数组,接受char,而不是char数组。
这就是你所拥有的:
for(int i = 0; i<size; i++){
test[i] = a.next().toCharArray();
}
从您所拥有的情况来看,我认为您只想将a.next()
转换为char数组,这是您已经定义的test
。
char[] test = new char[size];
你可以改变你必须改变的东西
test = a.next().toCharArray();
发布于 2015-04-23 20:48:32
问题是toCharArray
返回一个数组,而不能将数组放入数组中。试试这个:
Char[] test = a.next().toCharArray();
https://stackoverflow.com/questions/29838868
复制相似问题