我试图找到indexOf数组中最长的字符串,它由字符串longString表示。我一直收到“无法找到符号”的错误,并且不知道如何解决这个问题
public class Final21 {
public static String getLongString(String[] array) {
int x=0;
int maxLength = 0;
String longString = null;
for (String s : array) {
if (s.length() > maxLength) {
maxLength = s.length();
longString = s;
}
}
return longString;
}
public static String getShortString(String[] array) {
int minLength = 0;
String shortString = null;
for (String t : array) {
if (t.length() > minLength) {
minLength = t.length();
shortString = t;
}
}
return shortString;
}
public static void main(String[] args) {
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
String longString = getLongString(names);
System.out.println("The Longest String is: " + longString + " With The Index Of" + names.indexOf(longString));
String shortString = getShortString(names);
System.out.println("The Longest String is: " + shortString + " With The Index Of" );
}
}
答案 0 :(得分:3)
问题在于<myapp>.trafficmanager.net
。因为names.indexOf(longString)
的类型为names
,所以它是一个数组。此类型String[]
不具有名为String[]
的方法定义。作为替代方案,您可以尝试java.util.Arrays.asList(theArray).indexOf(o)
因此,要纠正您的代码片段,您可以像
一样重写它indexOf
阅读java.util.Arrays
的JavaDoc,了解如何使用Java API处理java中的数组。
此外,您可以通过修改代码的语义来实现相同的目的。 This answer由Elliott Frisch为您完成了这项工作。请阅读它..
答案 1 :(得分:3)
数组中没有indexOf
函数,而不是您当前的方法 - 我会从index
和getLongString
方法返回getShortString
;首先假设它是第一个元素。如果任何元素更长(或更短),请更新返回值。像,
public static int getLongString(String[] array) {
int max = 0;
for (int i = 1; i < array.length; i++) {
if (array[i].length() > array[max].length()) {
max = i;
}
}
return max;
}
public static int getShortString(String[] array) {
int min = 0;
for (int i = 1; i < array.length; i++) {
if (array[i].length() < array[min].length()) {
min = i;
}
}
return min;
}
然后您可以将其称为
public static void main(String[] args) {
String[] names = { "bob", "maxwell", "charley", "tomtomjack" };
int longString = getLongString(names);
System.out.println("The Longest String is: " + names[longString] + " With The Index Of " + longString);
int shortString = getShortString(names);
System.out.println("The Longest String is: " + names[shortString] + " With The Index Of " + shortString);
}
哪个输出
The Longest String is: tomtomjack With The Index Of 3
The Longest String is: bob With The Index Of 0
答案 2 :(得分:2)
indexOf()的语法是:
public int indexOf(char ch);
如果字符未出现,则返回指定字符第一次出现的字符串中的索引或-1。
获取所需的输出。
您可以尝试使用以下内容更改代码;
public static String getLongString(String[] array) {
int x=0, maxLength = 0, index = 0;
String longString = null;
for (String s : array) {
if (s.length() > maxLength)
{
maxLength = s.length();
index++;
longString = s;
}
}
return "The Longest String is: "+ longString + " With The Index Of :" + index;
}
public static void main(String[] args) {
String[] names = {"bob", "maxwell", "charley", "tomtomjack"};
String longString = getLongString(names);
System.out.println(longString);
}