show rank


Submit solution

Points: 50 (partial)
Time limit: 1.0s
Memory limit: 256M

Authors:
Problem type
Allowed languages
Java 19, Java 8

題目說明

設計一程式,讓使用者輸入數字,並存放於ArrayList中,直到使用者輸入的不是數字即結束輸入,最後將前三大的數值分別改為(由大到小): 1st, 2nd, 3rd後輸出ArrayList中的值

輸入

數值

輸出

將前三大數值更改後輸出ArrayList中的值

測試資料0 輸入

1 2 3 4 5 .

測試資料0 輸出

1 2 3rd 2nd 1st

測試資料1 輸入

1 2 3 5 5 .

測試資料1 輸出

1 2 3rd 1st 2nd

Comments


  • 0
    scu09156146  commented on May 14, 2024, 12:19 p.m.

    題解

    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class ShowRank {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            ArrayList<Integer> nums = new ArrayList<>();    // 記錄輸入的數字
            ArrayList<String> rank = new ArrayList<>();     // 記錄排名
            Scanner input = new Scanner(System.in);
    
            int n;
            while (input.hasNextInt()) {        // 檢查後面是不是數字
                n = input.nextInt();
                nums.add(n);
                rank.add(n + "");
            }
            input.close();
    
            String[] s = { "1st", "2nd", "3rd" };
            for (int i = 0; i < 3; i++) {
                rank.set(maxIndex(nums), s[i]); // 用maxIndex()找出位置,並修改值
            }
    
            // 印出排名
            for (String r : rank) {
                System.out.print(r + " ");
            }
    
        }
    
        public static int maxIndex(ArrayList<Integer> nums) {
            int index = 0;
            int max = nums.get(0);
            for (int i = 1; i < nums.size(); i++) {
                if (nums.get(i) > max) {
                    max = nums.get(i);
                    index = i;
                }
            }
            // 把最大的值改成最小整數,下次執行maxIndex()才能找出第二(第三)大值的index
            nums.set(index, Integer.MIN_VALUE);
            return index;
        }
    
    }