由於某些原因,當我嘗試向用戶詢問名稱,以便我可以將它們添加到列表並按字母順序排序時,此代碼將不會打印任何內容。它甚至不會經過while循環,有沒有人知道問題是什麼?另一個問題;如果用戶在詢問輸入值時按下輸入按鈕,那麼如何執行一些代碼,它會是空嗎?謝謝!嘗試使用Java將用戶輸入按字母順序排序,爲什麼不能使用此代碼?
import java.util.Scanner;
import java.util.*;
public class project16u
{
public static void main(String[] args)
{
int n;
String input = "nothing";
String temp;
ArrayList<String> names = new ArrayList<String>();
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
while(!input.equals("done")){
input = s1.nextLine();
names.add(input);
}
for (int i = 0; i < names.size()-1; i++)
{
if (names.get(i).compareTo(names.get(i+1))>0)
{
temp = names.get(i);
names.add(i, names.get(i+1));
names.add(i+1, temp);
i=0;
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < names.size() - 1; i++)
{
System.out.print(names.get(i).toString() + ",");
}
System.out.print(names.get(names.size()-1));
}
}
你需要** **調試代碼input.equals( 「完成」)。它肯定停留在'for'循環中,因爲你在其中的某個位置重置'i = 0',這通常是一個糟糕的做法:所有的循環都應該在控制變量的每個值上迭代一次,而且只循環一次。他們可能會立即退出,但不是最近。 –