[英]Input Strings into Array and then Splitting the Strings into a Single Char Array
我正在用Java编写一个程序,该程序允许用户输入n
并将其字符串放入数组中。 然后,程序将这些字符串分割成单个char字符,并将这些字符放入新的char数组中。
我正在尝试做的一个例子如下:
n
:3 "Cat", "Dog", "Mouse"
[Cat][Dog][Mouse]
[C][a][t][D][o][g][M][o][u][s][e]
运行代码时,我的代码会出现一些问题:
exp[i] = input.nextLine();
我不确定我的代码有什么问题,但是我感觉至少我输入字符串的那部分应该可以正常工作。 我意识到我还没有任何输出代码,因为我只是想立即使输入部分正常工作。 任何建议,将不胜感激!
public class Strings {
Scanner input = new Scanner(System.in);
int n; //number of strings
String[] exp = new String[n]; //input strings
char[] tokens = new char[n]; //individual char characters
//Gather data
public void SetNumberStrings(){
n = input.nextInt();
}
public void SetExpressions(){
for (int i = 0; i < n; i++){
exp[i] = input.nextLine();
}
}
public void SplitExpressions(){
for (int i = 0; i < n; i++){
tokens[i] = exp.split(" ");
}
}
public static void main(String[] args) {
Strings exp1 = new Strings();
exp1.SetNumberStrings();
exp1.SetExpressions();
exp1.SplitExpressions();
}
}
您的代码存在多个问题:
int n; //number of strings
int n; //number of strings
作为类字段int n; //number of strings
,表示它将用0初始化,从而导致数组的长度为0。要解决此问题,可以在将值赋给n
之后声明数组。 tokens[i] = exp.split(" ");
确实存在编译错误,因为您试图在exp数组上调用split方法,但是split方法来自String类。 因此,您需要调用exp[i].split
split
方法未按照您认为的去做。 我认为您正在寻找toCharArray()
方法。 tokens
数组应具有您扫描的所有字符串的长度。 您的程序存在几个问题。 类成员变量的初始化似乎是错误的(考虑您的要求)。 要将呼叫SetExpressions
在main
不会改变成员n
, exp
和tokens
,你期待。 n
的值默认情况下为0,并且在时间exp
和tokens
初始化之前一直保持不变。 因此,当您尝试将输入字符串分配给exp
的元素时,将得到java.lang.ArrayIndexOutOfBoundsException
。
此外,您尝试在String[]
对象( exp
)上调用split
方法,这是错误的( String
具有split()
方法而不是String[]
)。
如果您只是尝试获取一串单词并将其全部转换为char[]
,则可以将所有单词简单地连接到单个String
对象中,然后toCharArray()
对象执行toCharArray()
。 希望这可以帮助。
import java.util.Scanner;
public class Strings {
Scanner input = new Scanner(System.in);
int n; //number of strings
String[] exp; //Fix...This line was causing exception in your program We should not initialize array here because at this point we don't have the length from user
char[] tokens; //Fix...We are not confirmed of the length of token array at this point
//Gather data
public void SetNumberStrings(){
n = input.nextInt();
}
public void SetExpressions(){
exp= new String[n];
for (int i = 0; i <n; i++){
exp[i] = input.next();//.next() function should be used.
}
}
public void SplitExpressions(){
int length=0;
int l=0;
for(int i=0; i<exp.length; i++) {
length+= exp[i].length();
}//this loop will calculate the required length for character array
tokens =new char[length];//Giving length of array here
for(int i=0; i<exp.length; i++) {
for(int j=0; j<exp[i].length(); j++) {
tokens[l]=exp[i].charAt(j);//
l++;
}
}
}
public static void main(String[] args) {
Strings exp1 = new Strings();
exp1.SetNumberStrings();
exp1.SetExpressions();
exp1.SplitExpressions();
}
}
我已经清除了代码中的所有问题。 如注释中所述。您已经初始化了类中的所有类变量,这不是一个好的编程习惯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.