如何从字符串输入列表中找到最短和最长的字符串

时间:2019-02-14 11:20:23

标签: java

我首先需要从用户处接收未知数量的字符串输入,并创建一个循环,该循环将在输入“ x”时终止 我需要跟踪输入了多少输入 我需要测试输入以获取最长和最短的字符串及其长度 我需要找到字符串长度的总和 我需要找到平均字符串长度 我需要找到输入的字符串数量(不包括“ x”

2 个答案:

答案 0 :(得分:1)

首先让我强调一下,您应该真正尝试首先自己实现它,因为否则您将永远无法正确理解逻辑/语法,..

不存储值的操作可以如下:

  

我只是不确定平均长度是否可以正常工作,但看起来应该可以

     

(检查代码中的注释计算,这种方式不起作用,最后打印可能有效)

public static void getStringsAndGetDetails() {
    //https://stackoverflow.com/questions/54689213/i-would-like-to-find-out-how-to-find-the-shortest-and-longest-strings-from-a-lis
    System.out.println("Put 'x' or 'X' for exit");
    String input ="";
    Scanner sc = new Scanner(System.in);

    String shortestStr = null;
    String longestStr = null;

    int counter = 0;
    //int averageLength = 0;

    //load till x or X is entered 
    do{
        //read
        System.out.print("please, enter input: ");
        input = sc.nextLine();

        //avoid to process when escape is entered
        if(!input.toLowerCase().equals("x")) {
            counter++;

            //get to temp variable, can be reused with avoid repeating reading
            int inputLength = input.length();

            //if input is shorter then its new shortest, null check for first input
            if(shortestStr == null || inputLength < shortestStr.length()) {
                shortestStr = input;
            }

            //similar with longest string
            if(longestStr == null || inputLength > longestStr.length()) {
                longestStr = input;
            }

            //!! calculate average length is NOT possible like that, see bellow in printing
            /*
            averageLength = (averageLength + inputLength) / counter;
            System.out.println();
            */
        }
    }while(!input.toLowerCase().equals("x"));
    //not mandatory, but best practice (closing the streams), scanner in this case
    sc.close();


    System.out.println("Entered " + counter + " values");
    System.out.println("Longest: "+ longestStr);
    System.out.println("Shortest: "+ shortestStr);

    //be sure data are available (in case you enter x in first iteration, will fail otherwise)
    if(shortestStr != null && longestStr != null) {
    //seems to work
        int averageLength= (shortestStr.length() + longestStr.length()) / 2;  
        System.out.println("Average length: "+ averageLength);  
    }

}

输出:

Put 'x' or 'X' for exit
please, enter input: kakaka
please, enter input: ka
please, enter input: kaka
please, enter input: x
Entered 3 values
Longest: kakaka
Shortest: ka
Average length: 4

答案 1 :(得分:0)

看看下面的代码。它包含一些您希望在程序中实现的良好实践。注意测试是如何在main方法中编写的吗?我从这些开始,所以我可以在编写实际方法之前仔细考虑解决方案。在测试中,我尝试捕获尽可能多的边缘情况。如果我在代码中发现错误,则可以编写一个新的单元测试以使其失败,然后修复代码。 免责声明:此代码需要将JUnit 5添加到您的类路径中。

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class StringsInfo {

  public static void main(String[] args) {
    StringsInfo sInfo = new StringsInfo();

    sInfo.test(new String[] {}, null, null, 0, 0.0D, 0);
    sInfo.test(new String[] {null}, null, null, 0, 0.0D, 0);
    sInfo.test(new String[] {"one"}, "one", "one", 1, 3.0D, 3);
    sInfo.test(new String[] {"one", "two"}, "one", "one", 2, 3.0D, 6);
    sInfo.test(new String[] {"one", "two", "three"}, "one", "three", 3, (11/3), 11);
    sInfo.test(new String[] {"one", "two", "three", "x", "five"}, "one", "three", 3, (11/3), 11);
  }

  /**
   * Helper to test the class
   * @param input
   * @param shortest
   * @param longest
   * @param count
   * @param average
   * @param sumLength
   */
  private void test(String[] input, String shortest, String longest, long count,
      double average, long sumLength) {
    Result result = processString(input);
    assertEquals(shortest, result.shortest);
    assertEquals(longest, result.longest);
    assertEquals(count, result.count);
    assertTrue(average == result.average);
    assertEquals(sumLength, result.sumLength);
  }

  private Result processString(String[] input) {
    Result result = new Result();
    int shortestLength = Integer.MAX_VALUE;
    int longestLength = Integer.MIN_VALUE;
    for (String s : input) {
      if (s == null) { // Ignore null Strings
        continue;
      }
      if ("x".equals(s)) { // found the end
        break;
      }
      result.count++;
      int wordLength = s.length();
      result.sumLength += wordLength;
      if (wordLength < shortestLength) {
        result.shortest = s;
        shortestLength = wordLength;
      }
      if (wordLength > longestLength) {
        result.longest = s;
        longestLength = wordLength;
      }
    }
    if (result.count > 0) { // avoid division by zero
      result.average = result.sumLength / result.count;
    }
    return result;
  }

}

/**
 * Helper class to store the result
 */
class Result {
  String shortest;
  String longest;
  long count;
  double average;
  long sumLength;
}