我仍然是编程的新手,我正在尝试这个小程序,我编写一个静态方法,它接受一个字符串数组并返回一个整数。从那里我必须找到最小/最短字符串的索引位置并返回该索引值。我完全迷失了,并为此苦苦挣扎。我可以得到一些帮助吗?
我的代码到目前为止......
public class test
{
public static void main(String [] args)
{
String [] Month = {"July", "August", "September", "October"};
smallest(Month);
System.out.println("The shortest word is " + smallest(Month));
}
public static String smallest(String Month[])
{
String first = Month[0];
for (int i = 1 ; i < Month.length ; i++)
{
if (Month[i].length()<first.length())
{
first = Month[i];
}
}
return first;
}
}
检查下面的代码,
public class Test {
public static void main(String [] args)
{
String [] month = {"July", "August", "September", "October"};
// smallest(Month);
System.out.println("The shortest word index position is " + smallest(month));
}
public static int smallest(String Month[])
{
String first = Month[0];
int position=0;
for (int i = 1 ; i < Month.length ; i++)
{
if (Month[i].length()<first.length())
{
first = Month[i];
position=i;
}
}
return position;
}
}
你的代码实际上非常接近,但是 - 如果我理解你的任务正确 - 而不是实际的最小元素,你应该只跟踪索引,因为这是你想要返回的结果。
public static int smallest(String[] months) {
int first = 0;
for (int i = 1; i < months.length; i++) {
if (months[i].length() < months[first].length()) {
first = i;
}
}
return first;
}
专注于smallest
方法。
public static void smallest(String[] month) {
// since we have no knowledge about the array yet, lets
// say that the currently known shortest string has
// size = largest possible int value java can store
int min_length = Integer.MAX_INT, min_length_idx = -1;
for (int i = 0; i < month.length; i++) {
// is this current string a candidate for a new minimum?
if (month[i].length() < min_length) {
// if so, lets keep track of the length so that future
// indices can be compared against it
min_length = month[i].length();
min_length_idx = i;
}
}
return min_length_idx;
}
然后,该方法还将涵盖数组中没有任何字符串的情况,即空数组。
public static int smallest(String month[]) {
int smallest = 0;
for ( int i=0; i<month.length; i++ {
if (...) {
smallest = i;
}
}
return smallest;
}
注意:使用标准约定,其中变量名称以小写字母开头。