本日練習:
import java.util.Scanner;
public class CH12_1 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("請輸入陣列的個數:");
int n = input.nextInt();
char[] chr = new char[n];
for(int i = 0; i < n; i++){
System.out.println("請輸入字符符合個數的字元數:");
chr[i] = Character.toUpperCase(input.next().charAt(0));
// Character.toUpperCase 將字元轉成大寫
// charAt(0) 取出文字的第一個字元
}
System.out.println("轉換後的字元:");
System.out.println(chr);
input.close();
}
}
public class CH12_2 {
public static void main(String[] args){
int[] primes = new int[10];
int num = 0;
int i = 2;
while(num < 10){
boolean isPrime = true;
for(int j = 2; j * j <= i; j++){
if(i % j == 0){
isPrime = false;
break;
}
}
if(isPrime){
primes[num] = i;
num++;
}
i++;
}
System.out.println(java.util.Arrays.toString(primes));
}
}
public class CH12_3 {
public static void main(String[] args){
int[][] arr = {{18,21,30},{40,34,61},{41,15,18}};
int min = arr[0][0];
int mi = 0, mj = 0;
for(int i = 0; i <= 2; i++){
for(int j = 0; j <= i; j++){
if(arr[i][j] < min){
min = arr[i][j];
mi = i;
mj = j;
}
}
}
System.out.println("The minimum element is at position [" + mi + "," + mj + "] and its value is " + min);
}
}
import java.util.Scanner;
public class CH12_4 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("請輸入要列印的行數:");
int k = input.nextInt();
greeting(k);
input.close();
}
public static int greeting(int k){
for(int i = 0; i < k; i++){
System.out.println("Hello Java!");
}
return k;
}
}
import java.util.Scanner;
public class CH2_5 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("請輸入陣列的個數:");
int n = input.nextInt();
int[] arr = new int[n];
System.out.println("請輸入陣列元素:");
for(int i = 0; i < n; i++){
arr[i] = input.nextInt();
}
System.out.println("陣列中奇數的個數為:" + odd(arr));
input.close();
}
public static int odd(int[] arr){
int count = 0;
for(int i = 0; i < arr.length; i++){
if(arr[i] % 2 != 0){
count++;
}
}
return count;
}
}
本日結語:
覺得自己對陣列、函數還是不太熟悉,需要多練習才能掌握