gpt4 book ai didi

java - 在 Java 中查找字符串中最小的单词

转载 作者:行者123 更新时间:2023-11-29 08:04:23 24 4
gpt4 key购买 nike

我试图在用户输入的字符串中找到最小的单词。这是我目前所拥有的:

import java.util.*;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

String myText = sc.next();
String[] myWords = myText.split(" ");
int shortestLength,shortestLocation;

shortestLength=(myWords[0]).length();

shortestLocation=0;

for (int i=1;i<myWords.length;i++) {
if ((myWords[i]).length() < shortestLength) {
shortestLength=(myWords[i]).length();
shortestLocation=i;
}
}
System.out.println(myWords[shortestLocation]);
}

如果我输入 "SMALLEST WORD SHOULD BE A",输出应该是 A 但它只给出了字符串的第一个单词。有什么想法吗?

最佳答案

你的算法很好,但不是使用 next() :

String myText = sc.next();

它只会读取一个标记,即第一个 单词,使用nextLine() ,它将读取整个行:

String myText = sc.nextLine();

关于java - 在 Java 中查找字符串中最小的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12327576/

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