import java.util.Arrays;
import java.util.Scanner;
public class Sort {
public static void main(String[] args) {
String temp = "";
String a ="";
String[] New;
Scanner keyboard = new Scanner(System.in);
//String s1 = new String(keyboard.nextLine());
System.out.println("Please write your elements.");
while(keyboard.hasNext()){
String currentString = keyboard.next();
if(currentString.equals(" ")){
System.out.println("Bye");
}
a += (currentString.charAt(0) + "").toUpperCase() + currentString.substring(1).toLowerCase()+",";
}
a = a.substring(0, a.length()-1);
New = a.split(",");
System.out.println("Your elements are" + Arrays.toString(New) + ".");
for (int x = 1; x < New.length; x++) {
for (int y = 0; y < New.length - x; y++) {
if (New[y].compareTo(New[y + 1]) > 0) {
temp = New[y];
New[y] = New[y + 1];
New[y + 1] = temp;
}
}
} for(int i=0;i<New.length;i++){
System.out.println(New[i]);
}
/*System.out.println("In alphabethical order form is:");
System.out.println(Arrays.toString(New));*/
}
}
hasnext 处于无限循环中,我已经搜索了 stackowerflow,但答案无法修复错误。请帮助我。这里是我的代码,请写下您的元素。
如果我按空格键并输入,我就会遇到问题。
再见 线程“main”中的异常 java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1 在 java.lang.String.substring(来源未知) 在 aa.Sort.main(Sort.java:38)
最佳答案
有几件事。您应该使用hasNextLine()
和nextLine()
而不是hasNext()
和next()
.
更改后,您的 while 循环永远不会结束,因为您只是打印 Bye
并继续循环。添加break
打印 Bye
后的语句.
if(currentString.equals(" ")){
System.out.println("Bye");
break;
}
关于java - 还没有挂起 我怎样才能纠正这个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35465166/