我有这个问题编写一个静态方法,它接受一个字符串的ArrayList和一个整数,并且破坏性地更改ArrayList以删除长度小于整数参数的所有字符串。我有这个代码到目前为止,有人可以解释我哪里出错。它编译但它不会从数组列表中删除任何字符串。
import java.util.*;
public class q4
// Shows adding a string after all occurrences of a string
// constructively in an ArrayList
{
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
ArrayList<String> a = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<words.length;j++)
{
String b =a.get(j);
if(b.length()<len)
{
a.remove(j);
}
}
System.out.println("The ArrayList is "+a);
}
}
答案 0 :(得分:1)
删除ArrayList的项目时,请务必减少“j”。此外,尽管不常见,但将for-condition设置为j < a.size()
。否则,创建一个单独的变量来在循环之前存储大小,然后再减小它。
以下代码应该可以使用。
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
ArrayList<String> a = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<a.size(); j++)
{
String b =a.get(j);
if(b.length()<len)
{
a.remove(j);
j--;
}
}
System.out.println("The ArrayList is "+a);
}
答案 1 :(得分:0)
您从左到右遍历列表并随时删除项目。这会在删除多个项目时出现问题,因为索引不再匹配。
通过遍历从开始到结束的列表,而不是从开始到结束,可以很容易地修复这个问题。
因为现在,如果您删除某个项目,这不会影响以后要删除的项目:
for (int j = words.length - 1; j >= 0; j--)
答案 2 :(得分:0)
import java.util.*;
public class q4
// Shows adding a string after all occurrences of a string
// constructively in an ArrayList
{
public static ArrayList<String> a;
public static ArrayList<String> presenter;
public static void main(String[] args) throws Exception
{
Scanner input = new Scanner(System.in);
System.out.println("Enter some words (all on one line, separated by spaces):");
String line = input.nextLine();
String[] words = line.split(" +");
a = new ArrayList<String>();
presenter = new ArrayList<String>();
for(int i=0; i<words.length; i++)
{
a.add(words[i]);
}
System.out.println("The words are stored in an ArrayList");
System.out.println("The ArrayList is "+a);
System.out.print("\nEnter a number");
int len = input.nextInt();
for(int j=0;j<words.length;j++)
{
String b =a.get(j);
if((b.length()<len))
{
//do nothing
}
else
{
presenter.add(a.get(j));
}
}
System.out.print("The ArrayList is " + presenter);
}
}
这是一个替代方案,因为你说其他代码不起作用,我只是将“好”数据转移到另一个arraylist并打印出那个。