温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JAVA中数组插入与删除指定元素的实例代码

发布时间:2020-08-25 13:12:29 来源:脚本之家 阅读:183 作者:tangyaya8 栏目:编程语言

今天学了Java的数组,写了数组的插入和删除,本人小白,写给不会的小白看,大神请忽略,有错请大家指出来;

/**
给数组指定位置数组的插入
*/
import java.util.*;
public class ArrayInsert{
  public static void main(String []args){
    System.out.println("请用键盘输入5个数:");
    int [] array =new int[10];
    Scanner sc=new Scanner(System.in);
    //通过键盘向数组输入数
    for(int i=0;i<array.length-5;i++){
      array[i]=sc.nextInt();
    }
    //遍历数组
    System.out.print("原数组为:");
    for(int a:array){
      System.out.print(" "+a);
    }
    //向指定的位置插入数
    System.out.println("\n请输入插入位置:有效位置为0-----"+(array.length-1));
    int index=sc.nextInt();
    System.out.println("\n请输入插入的值-----");
    int num=sc.nextInt();

    //调用静态函数index
    //遍历插入后的数组
      System.out.println("插入元素之后的数组遍历:");
      Insert(index,num,array);
       for(int i=0;i<array.length;i++){
      System.out.print(" "+array[i]);
    }
  }
  //向数组指定位置插入数据方法
  public static int[] Insert(int index,int num,int a[]){
      //如果有元素,在索引之后的元素向后移一位,
      for(int  a[i]=a[i-1];
      }
      a[index]=num;
 return a;   
  }
}
//删除数组指定位置的数字。
import java.util.*;
public class ArrayDelete{
  public static void main(String args[]){
    System.out.println("请用键盘输入5个数:");
    int [] array =new int[10];
    Scanner sc=new Scanner(System.in);
    //通过键盘向数组输入数
    for(int i=0;i<array.length-5;i++){
      array[i]=sc.nextInt();
    }
    //遍历数组
    System.out.print("原数组为:");
    for(int a:array){
      System.out.print(" "+a);
    }
    //删除在指定位置的数字
    System.out.println("\n输入你要删除的位置: 范围在0---"+(array.length-1));
    int index=sc.nextInt();
    delete(index,array);//调用delete方法
    //删除之后的遍历
    System.out.println("删除之后的遍历:");
    for(int i=0;i<array.length;i++){
      System.out.print(" "+array[i]);
    }
  }
  public static int[] delete(int index,int array[]){
    //根据删除索引,把数组后面的向前移一位
    for(int i=index;i<array.length;i++){
      if(i!=array.length-1){
        array[i]=array[i+1];
      }else{//处理最后一位超出情况
      array[i]=array[i];
      }
    }
    return array;
  }
}

以上这篇JAVA中数组插入与删除指定元素的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI