gpt4 book ai didi

java - Java 句子中最短和最长的单词

转载 作者:行者123 更新时间:2023-12-01 18:28:11 25 4
gpt4 key购买 nike

我是 Java 编程新手!因此试图解决一个问题,找到句子中最短和最长的单词。我的程序如下所示。我希望你们能为我的项目指明正确的方向 -

public class StringProblems {
void shortAndLongWord(String str) {
String sw = "", lw = "";
int s = str.length(), l = 0;
String words[] = str.split(" ");

for(String word:words) {
if(word.length()<s)
sw = word;
else if(word.length()>l)
lw = word;
}

System.out.println("LONGEST WORD : "+lw);
System.out.println("SHORTEST WORD : "+sw);
}

public static void main(String[] args) {
Scanner scr = new Scanner(System.in);

StringProblems obj = new StringProblems();
System.out.printf("Enter a line to get shortest and longest word:");
String str = scr.nextLine();
str += " ";
obj.shortAndLongWord(str);
}
}

该程序的输出是:*输入一行以获得最短和最简单的单词:This is Sentence

最长的单词:最短的单词:句子**

我不知道我的逻辑哪里出了问题!请帮我解决!

最佳答案

你必须不断更新当前最短和最长单词的长度:

public class StringProblems {
void shortAndLongWord(String str)
{
if (str == null)
return;
String sw="",lw="";
int s=str.length(),l=0;
String words[]=str.split(" ");
for(String word:words)
{
if(word.length()<s)
{
sw=word;
s = word.length();
}
if(word.length()>l)
{
lw=word;
l = word.length();
}
}
System.out.println("LONGEST WORD : "+lw);
System.out.println("SHORTEST WORD : "+sw);
}
public static void main(String[] args) {
Scanner scr=new Scanner(System.in);
StringProblems obj=new StringProblems();
System.out.printf("Enter a line to get shortest and longest word:");
String str=scr.nextLine();
str+=" ";
obj.shortAndLongWord(str);
}
}

关于java - Java 句子中最短和最长的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25286690/

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