在java中查找字符串中的最小单词
这是我编写的用于查找字符串中最小单词的代码,但每当我尝试在eclipse中运行它时,它都会显示一个(字符串索引超出范围-2147483648)嵌套while语句错误,我已标记,我不明白它的原因,因为我的程序似乎在范围内运行良好,即小于输入字符串的长度。在java中查找字符串中的最小单词
在此先感谢!
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);
}
}
您使用的是可变i
,这是一个signed int
,所以它的范围从-2147483648到2147483647 下面的案例表明您的问题:
i = 2147483647;
i++;
增量后,i
的由于int溢出,值将为-2147483648。检查这question。
看来你正在得到一个巨大的输入,因此它造成了问题。
我的代码出现问题,但要获取最短的单词长度,您可以使用Stream和min()
。你的minLengthWord方法可能是这样的:
String f = "haha hah ha jajaja";
OptionalInt shortest = Arrays.stream(f.split(" ")).mapToInt(String::length).min();
System.out.println(shortest.getAsInt());
那么,-2147483648是最大整数+1。你有一个环绕。变量我变得如此之大,以至于它再次从负面开始。
如果要处理大于2 GB的文本,则必须使用long。
文本不大于2 GB。你可以输入短语“你好世界”,它仍然会发生。 –
原因是外环始终为真,变量i增加到最大值 – haifzhan
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++;
}
你的问题是你当文字和minidx都为0,你的外循环,而始终是真实的和字总是等于minidx,我不断增加,直到达到其最大数目。
你需要你的内心,而循环;其次,您需要更改i<j
到i<=j
以下后添加break
被更正后的代码:
int minidx = 0;
for (i = 1; i <= j; i++) { //-------------------------> change i<j to i<=j
if (count[minidx] > count[i])
minidx = i;
}
int words = 0;
i = 0;
System.out.println(minidx);
while (words <= minidx) {
if (words == minidx) {
while (i < len && input.charAt(i) != ' ') {
output += input.charAt(i);
i++;
}
break; //-------------------------> add break statement here.
} else if (i < len && input.charAt(i) == ' ') {
words++;
}
i++;
}
,当我试图与运行代码输入“Hello World”,minidx
在while
循环之前为0。 words
也是0,因此words<=minidx
为真,并输入循环。 words==minidx
为真(它们都是0),因此输入if
语句。因为它永远不会进入else if
(这是唯一的地方words
被更改),因此words
始终是0.因此,循环变成无限循环。与此同时,i
只是继续增长,直到它溢出,并成为负面。
这里有一个版本,使得采用Java 8的流API的: 从minLengthWord方法删除所有的代码,并粘贴下面的代码,将工作和解决运行时的问题太
List<String> words = Arrays.asList(input.split(" "));
String shortestWord = words.stream().min(
Comparator.comparing(
word -> word.length()))
.get();
System.out.println(shortestWord);
你的外'while'环路无限的,因为在某些条件下'单词'不会增加。 –
你的外部while循环总是为真,我增加直到达到最大整数值。详细请参阅我的答案 – haifzhan