【发布时间】:2014-08-13 12:50:29
【问题描述】:
我是 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);
}
}
这个程序的输出是: *输入一行得到最短和logest word:This is Sentence
最长的单词: 最短的单词:句子**
我不知道我的逻辑哪里出错了!请帮我解决!
【问题讨论】:
-
一旦你的当前实现技术发挥作用,尝试不创建字符串数组来解决这个问题。比较速度上的差异。
-
我也一定会尝试的..