odd plus one


Submit solution

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

Authors:
Problem type
Allowed languages
Java 19, Java 8

題目說明

讓使用者輸入數字存入陣列,直到輸入不是數字為止,最後將各奇數位數+1,在輸出所有陣列中的值

輸入

陣列值,直至輸入不是整數為止

輸出

奇數位+1後的陣列

測試資料 輸入

1 2 3 .

測試資料 輸出

2 2 4

Comments


  • 0
    scu09156146  commented on May 29, 2024, 9:46 a.m.

    題解

    參考課堂範例A262

    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class OddPlusOne {
    
        public static void main(String[] args) {
            ArrayList<Integer> numbers = new ArrayList<>();
            Scanner scanner = new Scanner(System.in);
    
            int num;
            while (scanner.hasNextInt()) {  // 當下一筆輸入不是數字時 結束迴圈
                num = scanner.nextInt();
                if (num % 2 != 0)           // 接值後,判斷是否為奇數
                    num++;
                numbers.add(num);           // 處理完奇數後,加到ArrayList
            }
            scanner.close();
    
            // 用for-each依序印出ArrayList裡的東西
            for (int number : numbers) {
                System.out.print(number + " ");
            }
    
        }
    
    }