问题:我需要将 lengthCount[j] 的值存储到范围之外的数组中。\
我尝试过的:在for循环中添加一个return语句,并将代码变成一个方法。
什么是变量:
长度计数 = [I@78db81f3
j = 在 for 循环中分配
下面的代码将正确的结果返回到控制台,但我无法将正确的数据存储到数组中以供在范围之外使用。
我想做的:要获取一个字符串,计算每个单词的字母,然后找出每个长度的单词有多少个。例如。 3个单词3个字母,1个单词1个字母。
我当前的输出:
String length: 0 count: 0
String length: 1 count: 2
String length: 2 count: 2
String length: 3 count: 4
String length: 4 count: 4
String length: 5 count: 1
String length: 6 count: 1
所以你可以看到代码输出了正确的数据,我如何将其存储到 int 数组中?
for(int j=0; j<lengthCount.length;j++){
System.out.println("String length: "+j+" count: "+lengthCount[j]);
}
如果您需要更多信息,请发表评论,我会快速添加!
提前致谢!
完整代码
public class lengthCountReturn {
public static void main(String[] args) {
String userInput = "I do not like green eggs and ham I do not like them Sam-I-Am";
userInput = userInput.replaceAll("\\p{P}", "");
String str[] = userInput.split(" "); // split the strings: "I", "am", "going", etc
int maxLength = 0;
for(String s: str) // finding the word with maximum size and take its length
if(maxLength < s.length())
maxLength = s.length();
int lengthCount[] = new int[maxLength+1];
for(String s1: str)
{
lengthCount[s1.length()]++; // count each length's occurance
}
System.out.println(lengthCount);
for(int j=0; j<lengthCount.length;j++)
{
System.out.println("String length: "+j+" count: "+lengthCount[j]);
}
}
}
最佳答案
使用 apache commons,你有一个单行解决方案,但仅适用于基本类型及其等效对象(int 和 Integer、byte 和 Byte 等):
假设你有;
import org.apache.commons.lang;
String[] source = {"hello", "world", "foo", "bar"};
就这样做:
String[] clone = ArrayUtils.subarray(source, 0, source.length);
关于java - 将一个数组存储到另一个数组中以供在范围之外使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22176170/