数组的倒序与隔位输出

本文介绍了如何使用Java编程语言实现将整数数组倒序输出以及每两个元素间间隔输出的功能,分别展示了使用数组和ArrayList两种数据结构的实现方法。
摘要由CSDN通过智能技术生成

时间限制:1.000S  空间限制:128MB

题目描述

给定一个整数数组,编写一个程序实现以下功能:

1. 将输入的整数数组倒序输出,每个数之间用空格分隔。
2. 从正序数组中,每隔一个单位(即索引为奇数的元素),输出其值,同样用空格分隔。

输入描述

第一行包含一个整数 n,表示数组的长度。
接下来一行包含 n 个整数,表示数组的元素。

输出描述

首先输出倒序排列的数组元素,然后输出正序数组中每隔一个单位的元素。

输入示例

5
2 3 4 5 6

输出示例

6 5 4 3 2
2 4 6

提示信息

数据范围:

1 <= n <= 1000.


题解1(数组) : 
import java.util.Scanner;
// import java.util.ArrayList;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();       //准备输入数组的大小
        int[] array = new int[n];   //初始化数组
        for(int count = 0; count < n; count++){     //给数组赋值
            array[count] = sc.nextInt();
        }
        for(int count = array.length - 1; count >= 0;count--){      //倒序输出
            System.out.print(array[count]);
            if(count > 0){
                System.out.print(" ");
            }
        }
        System.out.println();
        for(int count = 0; count < array.length; count +=2 ){      //隔位输出
            System.out.print(array[count]);
            if (count < array.length - 1) {
                System.out.print(" ");
            }
        }
    }
}

 

 题解2(ArrayList) : 
import java.util.Scanner;
import java.util.ArrayList;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> nums = new ArrayList<Integer>();
        int n = sc.nextInt();       //      ArrayList 的长度输入
       
        for(int a = 0; a < n; a++){
            while(sc.hasNext()){
                int num = sc.nextInt();
                 nums.add(num); 
            }
            }       //接收ArrayList值
            
        for(int a = nums.size() - 1; a >= 0; a--){
            System.out.print(nums.get(a));      //不要写nums[a],ArrayList里要写nums.get(a)
            if(a > 0){
                System.out.print(" ");
            }
        }       //倒序输出
        System.out.println();     //换行
        
        for(int a = 0; a < nums.size(); a+=2){
            System.out.print(nums.get(a));
            if(a < nums.size() - 1){
                System.out.print(" ");
            }
        }       //隔位输出
        
        }
    }

心得 : 

① 本次实验最大的麻烦莫在于...括号没写对(该有的地方少写一个,但是其他地方多一个),导致搜查bug半天...(GPT也没找出来这个问题)

②ArrayList不是直接获取数组元素值的.需要用到get()方法.而且get()里面还得写变量.

题源:卡码网

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值