Jas*_*wal 3 java arrays string methods
我已经搜索了几个SOF线程,但似乎无法找到我正在寻找的答案.他们中的大多数提供的代码答案超出了我迄今为止学到的范围.
我已经尝试了很多不同的东西,无法按照我需要的方式工作.
该程序应该采用给定的数组,读取它,找到给定的toRemove项,并在没有toRemove项的情况下重新打印数组.
我相信我的问题在removeFromArray方法中
public static void main(String[] args)
{
String[] test = {"this", "is", "the", "example", "of", "the", "call"};
String[] result = removeFromArray(test, "the");
System.out.println(Arrays.toString(result));
}
public static String[] removeFromArray(String[] arr, String toRemove)
{
int newLength = 0;
for(int i = 0; i < arr.length; i++)
{
if(arr[i].contains(toRemove))
{
newLength++;
}
}
String[] result = new String[arr.length-newLength];
for(int i = 0; i < (result.length); i++)
{
if(arr[i].contains(toRemove))
{
}
else
{
result[i] = arr[i];
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
这是我的java课程中的一项任务,我们还没有学习列表(我在谷歌搜索中偶然发现的答案之一),但这对我来说不是一个选择.
就像现在一样,它应该输出: [this,is,example,of,call]
目前正在输出:[this,is,null,example of of]
任何和所有的帮助将不胜感激!
在第二个循环中需要2个索引,因为您正在迭代两个具有不同长度的数组(输入数组和输出数组).
此外,newLength
是一个令人困惑的名称,因为它不包含新的长度.它包含输入数组长度和输出数组长度之间的差异.您可以更改其值以匹配其名称.
int newLength = arr.length;
for(int i = 0; i < arr.length; i++)
{
if(arr[i].contains(toRemove))
{
newLength--;
}
}
String[] result = new String[newLength];
int count = 0; // count tracks the current index of the output array
for(int i = 0; i < arr.length; i++) // i tracks the current index of the input array
{
if(!arr[i].contains(toRemove)) {
result[count] = arr[i];
count++;
}
}
return result;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2452 次 |
最近记录: |