gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:15:50 24 4
gpt4 key购买 nike

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

最佳答案

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

如果不存储值,可以按如下方式完成:

I am just only not sure if average length will work properly, but looks like it should

(check the commented calculation in the code, it's not working this way, print at the end probably works)

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

关于java - 如何从字符串输入列表中查找最短和最长的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54689213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com