你如何找到存储在数组中的最短项?这是我到目前为止所做的,但我对下一步做什么感到很遗憾。我试过几种没有运气的循环。我觉得有一种更简单的方法可以做到这一点。
这是我想做的事情,我不是在找你做作业,只是为了指导我。
对于此作业,您将编写一个应用程序,确定用户输入的所有字符串中的哪一个是最短的。应用程序将以欢迎消息开始,然后是在完成输入字符串后使用“。”字符的说明。只要未输入“。”,应用程序将继续提示用户输入字符串。每次输入字符串时,应用程序都会将其存储在ArrayList对象中。当用户输入完字符串后,ArrayList对象将被传递给名为printShortestString的方法。此方法将确定用户输入的所有字符串中的哪一个是最短的,并打印该字符串及其长度。最后,应用程序存在再见消息。
package hartman;
import java.util.ArrayList;
import java.util.Scanner;
public class ShortestString {
public static void main(String[] args) {
System.out.printf("WELCOME TO SHORTEST STRING\n\n");
System.out.printf("Type \".\" when done entering data.\n\n");
ArrayList<String> myArray = new ArrayList<>();
Scanner keyboard = new Scanner(System.in);
boolean keepAsking = true;
while (keepAsking) {
System.out.printf("Enter string: ");
String userInput = keyboard.nextLine();
if (userInput.equals(".")) {
keepAsking = false;
} else {
myArray.add(userInput);
}
}
printShortestString(myArray);
System.out.printf("\n\nGOODBYE!\n");
keyboard.close();
}
public static void printShortestString(ArrayList<String> myArray) {
int count;
int index = 0;
boolean endLoop = false;
while (endLoop = !true) {
for (count = 0; count < myArray.get(index).length(); count++) {
if (count == myArray.get(index).length()) {
System.out.printf("\nShortest string is %s with length %d",
myArray.get(index).toString(), myArray.get(index)
.length());
endLoop = true;
} else
index++;
}
}
}
}
答案 0 :(得分:1)
嗯,要做到这一点非常简单,我会对数组进行迭代,保持变量中找到的最短答案......就像这样:
if (!arrayWithAllValues.isEmpty()) {
String shortestValue = arrayWithAllValues.get(0);
for ( String current : arrayWithAllValues ) {
if ( current.length() < shortestValue.length() ) {
shortestValue = current;
}
}
}
这不是最好的方式,也不是最快的方式,但在我看来,这是最简单的方法。
答案 1 :(得分:0)
一种简单(但不是最有效)的方法是按长度对数组进行排序,然后输出最短的第一项;
public static void printShortestString(ArrayList<String> myArray) {
if(myArray.size() == 0)
return; // No output on empty array
Collections.sort(myArray, new Comparator<String>() {
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
});
System.out.printf("\nShortest string is %s with length %d",
myArray.get(0), myArray.get(0).length());
}
答案 2 :(得分:0)
我就是这样做的。这很容易理解。只需打印返回的String。此外,在使用的上下文中,永远不会传递null。
private static String getShortestString(ArrayList<String> stringArrayList)
{
int shortestIndex = 0;
int index = 0;
for (String currentString : stringArrayList)
{
if (currentString.length() < stringArrayList.get(shortestIndex).length())
{
shortestIndex = index;
}
index++;
}
return stringArrayList.get(shortestIndex);
}