※J.Y Chen 的個人部落格 ※

Just Follow Our Heart And We will shine!

60 瀏覽人次

【程式語言】JAVA的期中上機測驗 |TEST 3 印二維陣列 並將奇偶數的值 換成輸入的值num

Published: in JAVA by .

import java.util.Scanner;
    public class midterm3 {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            int myarray[][] = {{23,45,43,26},
                                 {7,34,21,6},
                                 {3,1,4,12}};
            System.out.print("Input a number:");
            int num = input.nextInt();
            System.out.println("My Array is");
            for (int a = 0 ; a < myarray.length ; a++) {
                for (int b = 0 ; b <myarray[1].length ; b++) {
                    System.out.print(myarray[a][b] + "\t");
                }
                System.out.println();
            }

            if(num%2 == 0) {
                System.out.print("Even numbers are: ");
                for (int x = 0 ; x < myarray.length ; x++) {
                    for (int y = 0; y < myarray[1].length ; y++) {
                        if (myarray[x][y] % 2 ==0){
                        System.out.print(myarray[x][y] + ", ");
                    }
                }
            }
        }           
            else {
                System.out.print("Odd numbers are: ");
                for (int x = 0 ; x < myarray.length ; x++) {
                    for (int y = 0; y < myarray[1].length ; y++) {
                        if (myarray[x][y] % 2 ==1){
                            System.out.print(myarray[x][y] + ", ");
                        }
                    }
                }
            }
                for (int i = 0 ; i < myarray.length ; i++) {
                    for (int j = 0 ; j < myarray[1].length ; j++) {
                        if (num %2 == 0 ) {
                            if(myarray[i][j] % 2==0) {
                                myarray[i][j] = num;
                            }
                        } 
                        if (num % 2 ==1 ){
                            if (myarray[i][j] %2 ==1) {
                                myarray[i][j] = num;
                            }
                        }
                    }   
                }
                System.out.println("\nArray is set to:");
                for (int a = 0 ; a < myarray.length ; a++) {
                    for (int b = 0 ; b <myarray[1].length ; b++) {
                        System.out.print(myarray[a][b] + "\t");
                    }
                    System.out.println();
                }
                System.out.println();
            }
        }

Result:

©2019 - 2024 Henry Chen