gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:39:05 24 4
gpt4 key购买 nike

这是我编写的用于查找字符串中最小单词的代码,但是每当我尝试在 Eclipse 中运行它时,它都会在嵌套 while 语句中显示 (String index out of range -2147483648) 错误,我有标记,我不明白其原因,因为我的程序似乎在范围内运行良好,即小于输入字符串的长度。

提前致谢!!

import java.util.Scanner;

public class Minword {
public static String minLengthWord(String input){

// Write your code here
int count[]=new int[50],i,j=0,len=input.length();
String output = "";
for(i=0;i<len;i++)
{
if(input.charAt(i)!=' ')
{
count[j]++;
}
else
j++;
}
int minidx=0;
for(i=1;i<j;i++)
{
if(count[minidx]>count[i])
minidx=i;
}
int words=0;
i=0;
while(words<=minidx)
{

if(words==minidx)
{
***while(i<len && input.charAt(i)!=' ')***
{
output+=input.charAt(i);
i++;
}
}
else if(i<len && input.charAt(i)==' ')
words++;
i++;
}

return output;


}
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
String input,output;
input=s.nextLine();
output=minLengthWord(input);

}

}

最佳答案

我在执行您的代码时遇到问题,但要获得最短的单词长度,您可以使用 Stream 和 min()。您的 minLengthWord 方法可能类似于:

String f = "haha hah ha jajaja";
OptionalInt shortest = Arrays.stream(f.split(" ")).mapToInt(String::length).min();
System.out.println(shortest.getAsInt());

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

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