gpt4 book ai didi

java - 多个字符串输入,退出循环......没有数组

转载 作者:太空宇宙 更新时间:2023-11-04 09:52:23 29 4
gpt4 key购买 nike

所以我更新了我的代码,但它做了一件非常奇怪的事情。当输入两个输入时,它返回最长和最短的变量以及其余变量。但是,当输入两个以上时,它会返回最长的...很棒...但对于最短的,它只返回比最长的单词短的单词,而不是输入的最短字符串...发生了什么:(

import java.util.Scanner;
public class StringReporting
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
String word ="";
String words = "";
String result ="";
int count = 0;
int shortest = 1;
int longest = 1;
int sumOfLengths = 0;
double averageLength = 0;
String shortestWord = "";
String longestWord = "";
while (!word.equals("x"))
{
count ++;
System.out.println ("Please enter String " + count + ", enter x
to exit: ");
word = in.nextLine();
words += "String " + count + ": " + word + "\n";
sumOfLengths += word.length();
if (word.length()>longest)
{
longest= word.length();
longestWord = word;
}
else if(word.length()> shortest && word.length() < longest)
{
shortest = word.length();
shortestWord = word;
}


}


averageLength = (sumOfLengths-1) / (count-1);
System.out.println ("shortest string entered:
" + shortestWord + ", with a length of: " + shortest);
System.out.println ("longest string entered: "
+ longestWord + ", with a length of: " + longest);
System.out.println (" sum of all lengths: " +
(sumOfLengths-1));
System.out.println ("number of strings: " + count);
System.out.println ("average string length : " + averageLength);

最佳答案

这听起来像是学校练习,所以我会尽力帮助您,但不会明确给出答案。

您只需要一个循环,并且在输入所有单词后不应再次循环所有单词。输入“x”后,应该已经计算出要打印的结果(或者需要最少的整理,例如计算平均值)。您可以在末尾打印多个值,无需将其全部放入 1 个字符串中。

如果您需要更多帮助,请随时询问!

关于java - 多个字符串输入,退出循环......没有数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54555728/

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