java 入力値をいくつか持ち,「结束」と入力されたら升顺で并び替えて(バブルソート)表示する。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 入力値をいくつか持ち,「结束」と入力されたら升顺で并び替えて(バブルソート)表示する。相关的知识,希望对你有一定的参考价值。

public class A18_HelloJava{
	public static void main(String[] args){
		List<String> strList = new ArrayList<String>();
		int strListIndex = 0;
		String endFlag;
		// 入力処理
		try{
			BufferedReader bfReader = new BufferedReader(new InputStreamReader(System.in));
			do{
				System.out.println("文字を入力してください。");
				strList.add(bfReader.readLine());
				endFlag = strList.get(strListIndex++);
			}while(!endFlag.equals("end"));
			// 末尾のendを削除
			strList.remove(strListIndex - 1);
			bfReader.close();
		} catch (IOException e){
			System.out.println("例外:" + e);
		}
		// バブルソート
		// 末尾と末尾-1を比べていく
		// 6, 3, 4, 1 : 6, 3, 1, 4
		// 6, 3, 1, 4 : 6, 1, 3, 4
		// 6, 1, 3, 4 : 1, 6, 3, 4
		// 末尾と末尾-1を比べていく
		// 1, 6, 3, 4 :  1, 6, 3, 4
		// 1, 6, 3, 4 :  1, 3, 6, 4
		// ...
		for(int i = 0; i < strList.size() - 1; i++){
			for(int j = strList.size() - 1; j > i; j--){
				// 末尾のほうが大きかった場合末尾-1と交換する
				String last = strList.get(j);
				String nextToLast = strList.get(j - 1);
				if(nextToLast.compareTo(last) > 0){
					String tmpStr = strList.get(j - 1);
					strList.set(j - 1, strList.get(j));
					strList.set(j, tmpStr);
				}
			}

		}

		// 並び替え後を出力
		System.out.println();
		for(String str : strList){
			System.out.println(str);
		}

	}

}

以上是关于java 入力値をいくつか持ち,「结束」と入力されたら升顺で并び替えて(バブルソート)表示する。的主要内容,如果未能解决你的问题,请参考以下文章