有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我想让它变得更简单

我这里有我的java代码,目标是输出应该如下所示: 问题NEL01A021問題 NEL01L01A021英語 11-22-2016 NEL01L01A021/NEL01L01A021问题。文本

我已经做了,但我想让它更简单。你能帮帮我吗? 导入java。util。ArrayList

public class TestTabSeparator {

String str;
ArrayList<String> strings = new ArrayList<>();

TestTabSeparator(ArrayList<String> strings) {
    this.strings = strings;
}

void showArrayList() {

    for (int index = 0; index < this.strings.size(); index++) {
        System.out.print(this.strings.get(index) + "   ");
    }
}
}

另一类:

import java.util.Arrays;
import java.util.ArrayList;

public class TabSeparator {

public static void main(String[] args) {

    ArrayList<String> stringList = new ArrayList();

    String topicName = "problem";
    String title = "NEL01L01A021";
    String idTitle = "問題";
    String questionNo = "NEL01L01A021";
    String keyword = "英語";
    String comment = "11-22-2016";
    String bodyKey = "NEL01L01A021/NEL01L01A021-problem.txt";

    String[] str2 = new String[7];
    str2[0] = topicName;
    str2[1] = title;
    str2[2] = idTitle;
    str2[3] = questionNo;
    str2[4] = keyword;
    str2[5] = comment;
    str2[6] = bodyKey;

    stringList.addAll(Arrays.asList(str2));
    TestTabSeparator strList = new TestTabSeparator(stringList);
    strList.showArrayList();
}
}

共 (2) 个答案

  1. # 1 楼答案

    我有两个建议。首先你可以做数组。asList直接在变量上列出,而不是首先创建数组

    ArrayList<String> stringList = Arrays.asList(topicName, title, idTitle, questionNo, keyword, comment, bodyKey)
    

    第二个showArrayList方法可以使用字符串简化。加入

    void showArrayList() {
        System.out.print(String.join(" ", strings));
    }
    
  2. # 2 楼答案

    我是这样做的:

    public class TestTabSeparator {
    
        private ArrayList<String> strings = new ArrayList<>();
    
        private TestTabSeparator(ArrayList<String> strings) {
            this.strings = strings;
        }
        private void showArrayList() {
            strings.stream().forEach(s -> System.out.print(s+"  "));
        }
        public static void main(String[] args) {
    
            String topicName = "problem";
            String title = "NEL01L01A021";
            String idTitle = "問題";
            String questionNo = "NEL01L01A021";
            String keyword = "英語";
            String comment = "11-22-2016";
            String bodyKey = "NEL01L01A021/NEL01L01A021-problem.txt";
    
            ArrayList stringList = new ArrayList(){{
                add(topicName);
                add(title);
                add(idTitle);
                add(questionNo);
                add(keyword);
                add(comment);
                add(bodyKey);
            }};
            TestTabSeparator strList = new TestTabSeparator(stringList);
            strList.showArrayList();
        }
    }