數(shù)組元素反轉(zhuǎn)分析
反轉(zhuǎn)分析
package com.itheima;
import java.util.Scanner;
/*
* 需求:
* (1)鍵盤錄入5個int類型的數(shù)據(jù)存儲數(shù)組arr中
* (2)定義方法將arr數(shù)組中的內(nèi)容反轉(zhuǎn)
* (3)定義方法對反轉(zhuǎn)后的數(shù)組進(jìn)行遍歷
*
* 分析:
* A:定義一個長度為5的數(shù)組
* B:通過鍵盤錄入數(shù)據(jù)給數(shù)組中的元素賦值
* C:定義方法將arr數(shù)組中的內(nèi)容反轉(zhuǎn)
* 什么是反轉(zhuǎn)劲装?
* 如何實現(xiàn)反轉(zhuǎn)煮落?
* D:定義方法對反轉(zhuǎn)后的數(shù)組進(jìn)行遍歷
*/
public class Test7 {
public static void main(String[] args) {
//定義一個長度為5的數(shù)組
int[] arr = new int[5];
//通過鍵盤錄入數(shù)據(jù)給數(shù)組中的元素賦值
Scanner sc = new Scanner(System.in);
for(int x = 0; x < arr.length; x++) {
System.out.println("請輸入"+(x + 1) + "個元素值:");
int number = sc.nextInt();
arr[x] = number;
}
//反轉(zhuǎn)前也調(diào)用一下
printArray(arr);
//定義方法將arr數(shù)組中的內(nèi)容反轉(zhuǎn)
reverse(arr);
//定義方法對反轉(zhuǎn)后的數(shù)組進(jìn)行遍歷
printArray(arr);
}
//遍歷數(shù)組
public static void printArray(int[] arr) {
System.out.print("[");
for(int x = 0; x < arr.length; x++) {
if(x == arr.length - 1) {
System.out.println(arr[x] + "]");
}else {
System.out.print(arr[x] + ", ");
}
}
}
/*
* 兩個明確:
* ※返回值類型:void
* 參數(shù)列表:int[] arr
*/
public static void reverse(int[] arr) {
for(int start = 0,end = arr.length-1;start <= end; start++, end--) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
}
}
}