除了“isEmpty”返回语句之外,它都打印正确。如何让它正确返回“-1”,以便主函数中的最后两个语句完成它们的工作 注意:我无法编辑主要功能
我的代码如下:
import java.util.*;
public class task7{
public static int find_minimum_length(ArrayList<String> A)
{
int position = 0;
int smallest = A.get(0).length();
for(int i = 0; i<A.size(); i++)
{
if(A.isEmpty())
{
return -1;
}
if(A.get(i).length()<smallest)
{
smallest = A.get(i).length();
int shortt = A.indexOf(A.get(i));
position = shortt;
}
}
return position;
}
public static ArrayList<String> remove_minimum_length(ArrayList<String> A)
{
if(A.isEmpty())
{
}
else
{
A.remove(find_minimum_length(A));
}
return A;
}
public static void main(String[] args)
{
ArrayList<String> a = new ArrayList<String>();
a.add("whale");
a.add("cat");
a.add("elephant");
a.add("donkey");
a.add("goat");
System.out.println(a);
int position = find_minimum_length(a);
System.out.printf("minimum position = %d\n\n", position);
remove_minimum_length(a);
System.out.println(a);
position = find_minimum_length(a);
System.out.printf("minimum position = %d\n\n", position);
remove_minimum_length(a);
System.out.println(a);
position = find_minimum_length(a);
System.out.printf("minimum position = %d\n\n", position);
remove_minimum_length(a);
System.out.println(a);
position = find_minimum_length(a);
System.out.printf("minimum position = %d\n\n", position);
remove_minimum_length(a);
System.out.println(a);
position = find_minimum_length(a);
System.out.printf("minimum position = %d\n\n", position);
remove_minimum_length(a);
System.out.println(a);
position = find_minimum_length(a);
System.out.printf("minimum position = %d\n\n", position);
}
}
答案 0 :(得分:4)
移动它:
if(A.isEmpty())
{
return -1;
}
出了你的块。仅当有要迭代的元素时才会执行for块,这意味着,如果列表不为空。
答案 1 :(得分:0)
您的问题是for
块将在阵列很大的情况下执行。因此,如果您的数组为空,则大小为0.因此for
未执行。
要解决您的问题,您必须将if
- 条款移出for
。
应用于您的代码,它应如下所示:
public static int find_minimum_length(ArrayList<String> A)
{
int position = 0;
int smallest = A.get(0).length();
if(!A.isEmpty())
{
for(int i = 0; i<A.size(); i++)
{
if(A.get(i).length()<smallest)
{
smallest = A.get(i).length();
int shortt = A.indexOf(A.get(i));
position = shortt;
}
return position;
}
else
{
return -1;
}
}
答案 2 :(得分:0)
我会对您的方法进行一些更改。首先,您应检查null
输入,如果找到则返回-1
。如果输入为空-1
,您也可以返回ArrayList
。
public static int find_minimum_length(List<String> a) {
if (a == null || a.size() == 0) {
return -1;
}
int position = 0;
int smallest = a.get(0).length();
// start iterating your for loop at 1, not 0
for (int i=1; i < a.size(); i++) {
if (a.get(i).length() < smallest) {
smallest = a.get(i).length();
position = i;
}
}
return position;
}
public static List<String> remove_minimum_length(List<String> a) {
int index = find_minimum_length(a);
if (index != -1) {
a.remove(index);
}
return a;
}
答案 3 :(得分:0)
将您的isEmpty()
电话放在for循环之外。
if(A.isEmpty()) return -1;
for(int i = 0; i<A.size(); i++)
{
if(A.get(i).length()<smallest)
{
smallest = A.get(i).length();
int shortt = A.indexOf(A.get(i));
position = shortt;
}
}