• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wchenfeng

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

数组进行逆序数存储,可随意输入数组,不限定数组长度

 

提炼函数的目的是为了代码重用,就像别人程序中的一个数组,需要逆序存储,用这个函数可以实现吗。

不过函数的功能一般不会太多,例如reverse函数只负责逆序,不管输出。

函数设计的理念是要成为可复用的模块,所以一个函数不是功能越多越好。

 read()方法负责读取数组,并存储。

reverse()方法负责逆序存储。

import java.util.Scanner;
public class ke9_18 {
    public static void main(String[] args) {
        System.out.println("请输入你进行逆反操作的数");
        int[] list=read();//创建一个数组,调用读取函数
        reverse(list);//调用读取和逆反函数
        System.out.print("逆序数为:");
        for(int i=0;i<list.length;i++)
            System.out.print(list[i] + " ");
    }
    public static int [] read() {//读取函数
        int i;
        Scanner reader = new Scanner(System.in);
        String input = reader.nextLine();//字符串类型读取
        String[] temp = input.split(" ");//返回下标从0开始的数组
        int[] list = new int[temp.length];//创建一个整数型数组,用来存储正序列
        for (i = 0; i < temp.length; i++) {//遍历存储
            list[i] = Integer.parseInt(temp[i]);
        }
        return list;//返回正存储的数组
    }
    public static void reverse(int[] list) {//逆反函数
        int i=list.length-1, j,temp;
        for (j = 0; j <list.length/2; i--, j++) {//遍历打印
            temp=list[j];
            list[j] = list[i];//进行头尾输入
            list[i]=temp;
        }
    }
}

输出

输入

1 2 3 4 5 6 7 8 9

 

posted on 2022-04-12 20:02  王陈锋  阅读(61)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3