Java | PTA: jmu-Java-02基本语法-08-ArrayList入门

新建1个ArrayList<String> strList用来存放字符串,然后进行如下操作。

提示: 查询Jdk文档中的ArrayList。
注意: 请使用System.out.println(strList)输出列表元素。

输入格式

  1. 输入: n个字符串,放入strList。直到输入为!!end!!时,结束输入。

  2. strList头部新增一个begin,尾部新增一个end

  3. 输出列表元素

  4. 输入: 字符串str

  5. 判断strList中有无包含字符串str,如包含输出true,否则输出false。并且输出下标,没包含返回-1。

  6. 在strList中从后往前找。返回其下标,找不到返回-1。

  7. 移除掉第1个(下标为0)元素,并输出。然后输出列表元素。

  8. 输入: 字符串str

  9. 将第2个(下标为1)元素设置为字符串str.

  10. 输出列表元素

  11. 输入: 字符串str

  12. 遍历strList,将字符串中包含str的元素放入另外一个ArrayList strList1,然后输出strList1。

  13. 在strList中使用remove方法,移除第一个和str相等的元素。

  14. 输出strList列表元素。

  15. 使用clear方法,清空strList。然后输出strList的内容,size()isEmpty(),3者之间用,连接。

输入样例:

a1 b1 3b a2 b2 12b c d !!end!!
b1
second
b

输出样例:

[begin, a1, b1, 3b, a2, b2, 12b, c, d, end]
true
2
2
begin
[a1, b1, 3b, a2, b2, 12b, c, d, end]
[a1, second, 3b, a2, b2, 12b, c, d, end]
[3b, b2, 12b]
[a1, second, 3b, a2, b2, 12b, c, d, end]
[],0,true

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		ArrayList<String> strList = new ArrayList<>();
		String inputStr = in.next();
		while(!inputStr.equals("!!end!!")) {
			strList.add(inputStr);
			inputStr = in.next();
		}
		strList.add(0,"begin");
		strList.add("end");
		System.out.println(strList);
		String str = in.next();
		System.out.println(strList.contains(str));
		System.out.println(strList.indexOf(str));
		System.out.println(strList.lastIndexOf(str));
		System.out.println(strList.remove(0));
		System.out.println(strList);
		str = in.next();
		strList.set(1, str);
		System.out.println(strList);
		str = in.next();
		ArrayList<String> strList1 = new ArrayList<>();
		for(String aString : strList) {
			if(aString.indexOf(str)!=-1) {
				strList1.add(aString);
			}
		}
		System.out.println(strList1);
		strList.remove(str);
		System.out.println(strList);
		strList.clear();
		System.out.println(strList+","+strList.size()+","+strList.isEmpty());
		
	}
}

Guess you like

Origin blog.csdn.net/weixin_48419914/article/details/121228976