java编程题目-数组反转

1.创建一个数组Array类,有两个成员变量:数组和下标。

包含一个构造方法,用于給数组分配空间。

两个成员方法:分别给数组添加元素

package main;

public class Array {
	//定义数组类
	  public int[] temp;
	  public int foot=0;//数组下标,初始下标为0.
	  //构造方法,给数组分配空间
	  public Array(int len) 
	  {
		if(len>0)
			this.temp=new int[len];  //分配空间就是实例化数组的形式  
		else	  
			this.temp=new int[1];   //数组至少维持一个空间
	  }
	  //给数组插入数据i
	  public boolean add(int i) {  
		  if(this.foot<this.temp.length)  //没满
		  { 
			  this.temp[foot++]=i; //没满继续添加 
			  return true;
		  }
		  else return false;
	  }
	  //返回数组
	  public int[] getArray() {
		  return this.temp;
	  }
}

和返回数组。

2.创建一个反转数组类(该类继承数组类Array) 

package main;
//数组反转类
public class ReverseArray extends Array {
     public ReverseArray(int len) {
    	 super(len);//调用超类的构造方法;
	}
     //重写getArray()方法
     public int[] getArray() {
    	 int head=0;
    	 int tail=this.temp.length-1;
    	 int t=this.temp.length/2;
    	 //
    	 for(int i=0;i<t;i++) {
    		 int T;
    		 T=this.temp[head];
    		 this.temp[head]=this.temp[tail];
    		 this.temp[tail]=T;
    		 head++;
    		 tail--;
    	 }
    	 return this.temp;
     }
}

 

3.测试类

 

package main;
public class Test {
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
      ReverseArray r1=new ReverseArray(4);
      r1.add(1);
      r1.add(33);
      r1.add(9);
      r1.add(789);     
      System.out.println("翻转测试:"); 
      //调用打印数组的方法
      print(r1.getArray());
	} 
	//封装了打印数组的方法
	public static void print(int a[]) {
      for(int i=0;i<a.length;i++)
         System.out.print(a[i]+" ");
	}
}

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

z'Healer.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值