ArrayList的add方法get新技能

本文介绍了一个Java程序,该程序使用ArrayList进行逆序字符串插入,并根据不同条件打印列表元素。程序通过Scanner读取用户输入的字符串,然后将这些字符串逆序插入到列表中,并在每次插入后打印列表的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.ethjava;
import java.util.ArrayList;
import java.util.Scanner;

public class bianpaifanli {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        for (int i = 0; i < x; i++) {
            String s = sc.next();
            list.add(0, s);//what??用于在列表的指定位置插入指定元素,并将当前处于该位置的元素及其后续元素的索引加1。
            System.out.println(list);
            if (list.size() < 5) {//当list里面还没有增加超过4个数时则执行下面
                for (int j = 0; j < list.size(); j++) {
                    if (j == list.size() - 1) {
                        System.out.println(j + 1 + "=" + list.get(j) + " ");//当每行最后一个时就得换行
                    } else {
                        System.out.print(j + 1 + "=" + list.get(j) + " ");
                    }
                }
            } else {//当list里面超过4个数时则执行下面
                for (int k = 0; k < 4; k++) {
                    if (k == 3) {
                        System.out.println(k + 1 + "=" + list.get(k) + " ");//当每行最后一个时就得换行
                    } else {
                        System.out.print(k + 1 + "=" + list.get(k) + " ");
                    }
                }
            }
        }
    }
}

 

题目描述:

题目描述

请输入字符串,最多输入4 个字符串,要求后输入的字符串排在前面,例如

输入:EricZ

输出:1=EricZ

输入:David

输出:1=David 2=EricZ

输入:Peter

输出:1=Peter 2=David 3=EricZ

输入:Alan

输出:1=Alan 2=Peter 3=David 4=EricZ

输入:Jane

输出:1=Jane 2=Alan 3=Peter 4=David

输入描述:

第一行为字符串个数m,接下来m行每行一个字符床,m不超过100,每个字符床长度不超过20。

输出描述:

输出m行,每行按照样例格式输出,注意用一个空格隔开。

 

 

自测练习:

6
a
[a]
1=a 
b
[b, a]
1=b 2=a 
c
[c, b, a]
1=c 2=b 3=a 
d
[d, c, b, a]
1=d 2=c 3=b 4=a 
e
[e, d, c, b, a]
1=e 2=d 3=c 4=b 
f
[f, e, d, c, b, a]
1=f 2=e 3=d 4=c 

Process finished with exit code 0
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值