需求:
1 键盘录入指定数组长度,并通过键盘录入向数组中添加数据
2 实现三个功能如图
3 选择1 实现反转功能,并把反转后的数组打印
4 选择2 实现查找功能,如果数组中存在返回相应索引,不存在也要提示
5 选择3求最值
- package Exercise_0311;
- import java.util.Scanner;
- public class Test_Homework {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("请指定数组长度:");
- int a = sc.nextInt();
- int[] arr = new int[a];
- System.out.println("请输入数组:");
- for (int i = 0; i < arr.length; i++) {
- arr[i] = sc.nextInt();
- }
- System.out.print("原来数组:");
- printArray(arr);
- System.out.println();
- System.out.println("请输入你需要的操作:");
- System.out.println("-------------------------------------------");
- System.out.println("1.反转" + "\n" + "2.查找" + "\n" + "3.找最大值");
- System.out.println("------------input 886 end------------------");
- int x = sc.nextInt();
- if (x == 1) {
- System.out.println();
- exchangeArray(arr);
- System.out.print("反转之后数组数组:");
- printArray(arr);
- } else if (x == 2) {
- System.out.println();
- System.out.println("请输入你要查找的内容:");
- int b = sc.nextInt();
- searchArray(arr, b);
- } else if (x == 3) {
- System.out.println();
- int max = arr[0];
- getMax(arr, max);
- } else if (x == 886) {
- System.out.println("goodbye!");
- } else {
- System.out.println("输入错误!");
- }
- }
- public static void printArray(int[] arr) {
- for (int i = 0; i < arr.length; i++) {
- System.out.print(arr[i] + " ");
- }
- }
- public static void exchangeArray(int[] arr) {
- for (int i = 0; i < arr.length / 2; i++) {
- int temp = arr[i];
- arr[i] = arr[arr.length - i - 1];
- arr[arr.length - i - 1] = temp;
- }
- }
- public static void searchArray(int[] arr, int b) {
- boolean c = false;
- int d = 0;
- for (int i = 1; i < arr.length; i++) {
- if (b == arr[i]) {
- d = i;
- break;
- } else {
- d = 0;
- }
- }
- if (d == 0) {
- System.out.println("输入错误");
- } else {
- System.out.println(b + "第一次出现的索引位置是:" + (d + 1));
- }
- }
- private static void getMax(int[] arr, int max) {
- max = arr[0];
- for (int i = 0; i < arr.length; i++) {
- if (max < arr[i]) {
- max = arr[i];
- }
- }
- System.out.println("最大值是:" + max);
- }
- }
复制代码
|
|