从 ArrayList 到单个字符串的字符串 JAVA

Strings from ArrayList to individual strings JAVA

有没有办法从 ArrayList 中 "extract" 单独的字符串? 我已将字符串存储在 ArrayList 中,并希望将它们打印到控制台。 我知道我可以使用 for 循环,但并不是那么简单。我正在尝试创建一个基于列的打印,并且我使用了一种方法(由 "CandiedOrange" 在堆栈溢出时创建)将以逗号分隔的字符串作为输入。

它主要做的是;它根据每列中字符串的长度创建列间距。 (全部归功于 "CandiedOrange")

List<List<String>> lines = new ArrayList<>();
List<Integer> maxLengths = new ArrayList<>();
int numColumns = -1;

public Columns addLine(String... line) {

    if (numColumns == -1){
        numColumns = line.length;
        for(int i = 0; i < numColumns; i++) {
            maxLengths.add(0);
        }
    }

    if (numColumns != line.length) {
        throw new IllegalArgumentException();
    }

    for(int i = 0; i < numColumns; i++) {
        maxLengths.set(  i, Math.max( maxLengths.get(i), line[i].length() )  );
    }

    lines.add( Arrays.asList(line) );

    return this;
}

我要打印的列数在编译期间是未知的,因为用户在 运行 期间输入了 1-5 的列数。所以我想我可以对行使用 ArrayLists,并对行的每个数组列表使用 addLine() 方法。

如果有更好的方法来解决这个问题,我将非常乐意知道。

编辑:

从头开始:

我正在创建一个有 1-5 名玩家的 Yahtzee 游戏。每个 Player 都由 class "Player"

的实例定义
public class Player {

private String name;

private int ones;
private int twos;
private int threes;
private int fours;
private int fives;
private int sixes;

private int threeofakind;
private int fourofakind;
private int fullhouse;
private int smallstraight;
private int largestraight;
private int chance;
private int yahtzee;

private int totalscore;

public int getOnes() {
    return ones;
}

public void setOnes(int ones) {
    this.ones = ones;
}

public int getTwos() {
    return twos;
}

public void setTwos(int twos) {
    this.twos = twos;
}

public int getThrees() {
    return threes;
}

public void setThrees(int threes) {
    this.threes = threes;
}

public int getFours() {
    return fours;
}

public void setFours(int fours) {
    this.fours = fours;
}

public int getFives() {
    return fives;
}

public void setFives(int fives) {
    this.fives = fives;
}

public int getSixes() {
    return sixes;
}

public void setSixes(int sixes) {
    this.sixes = sixes;
}

public int getThreeofakind() {
    return threeofakind;
}

public void setThreeofakind(int threeofakind) {
    this.threeofakind = threeofakind;
}

public int getFourofakind() {
    return fourofakind;
}

public void setFourofakind(int fourofakind) {
    this.fourofakind = fourofakind;
}

public int getFullhouse() {
    return fullhouse;
}

public void setFullhouse(int fullhouse) {
    this.fullhouse = fullhouse;
}

public int getSmallstraight() {
    return smallstraight;
}

public void setSmallstraight(int smallstraight) {
    this.smallstraight = smallstraight;
}

public int getLargestraight() {
    return largestraight;
}

public void setLargestraight(int largestraight) {
    this.largestraight = largestraight;
}

public int getChance() {
    return chance;
}

public void setChance(int chance) {
    this.chance = chance;
}

public int getYahtzee() {
    return yahtzee;
}

public void setYahtzee(int yahtzee) {
    this.yahtzee = yahtzee;
}

public int getTotalscore() {
    return totalscore;
}

public void setTotalscore(int totalscore) {
    this.totalscore = totalscore;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

我正在实施 MVC 结构(尽我所能),这意味着我有一个视图 class 以及显示主控制台列记分牌的方法。 (方法未完成)

public void displayMainScoreBoard(ArrayList<Player> playerList) {

    Columns col = new Columns();                                //Instance of column class.

    ArrayList<String> Name = new ArrayList<>();
    ArrayList<Integer> Ones = new ArrayList<>();
    ArrayList<Integer> Twos = new ArrayList<>();
    ArrayList<Integer> Threes = new ArrayList<>();
    ArrayList<Integer> Fours = new ArrayList<>();
    ArrayList<Integer> Fives = new ArrayList<>();
    ArrayList<Integer> Sixes = new ArrayList<>();

    ArrayList<Integer> Threeofakind = new ArrayList<>();
    ArrayList<Integer> Fourofakind = new ArrayList<>();
    ArrayList<Integer> Fullhouse = new ArrayList<>();
    ArrayList<Integer> Smallstraight = new ArrayList<>();
    ArrayList<Integer> Largestraight = new ArrayList<>();
    ArrayList<Integer> Chance = new ArrayList<>();
    ArrayList<Integer> Yahtzee = new ArrayList<>();

    ArrayList<Integer> Totalscore = new ArrayList<>();

    for (Player p : playerList) {                           //For every player, append their category data.
        Name.add(p.getName());
        Ones.add(p.getOnes());
        Twos.add(p.getTwos());
        Threes.add(p.getThrees());
        Fours.add(p.getFours());
        Fives.add(p.getFives());
        Sixes.add(p.getSixes());

        Threeofakind.add(p.getThreeofakind());
        Fourofakind.add(p.getFourofakind());
        Fullhouse.add(p.getFullhouse());
        Smallstraight.add(p.getSmallstraight());
        Largestraight.add(p.getLargestraight());
        Chance.add(p.getChance());
        Yahtzee.add(p.getYahtzee());
        Totalscore.add(p.getTotalscore());
    }

}

这里是 CandiedOrange 的完整专栏 class。 (再次声明,我对他的代码没有任何权利。)

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


public class Columns {

List<List<String>> lines = new ArrayList<>();
List<Integer> maxLengths = new ArrayList<>();
int numColumns = -1;

public Columns addLine(String... line) {

    if (numColumns == -1){
        numColumns = line.length;
        for(int i = 0; i < numColumns; i++) {
            maxLengths.add(0);
        }
    }

    if (numColumns != line.length) {
        throw new IllegalArgumentException();
    }

    for(int i = 0; i < numColumns; i++) {
        maxLengths.set(  i, Math.max( maxLengths.get(i), line[i].length() )  );
    }

    lines.add( Arrays.asList(line) );

    return this;
}

public void print(){
    System.out.println( toString() );
}

public String toString(){
    String result = "";
    for(List<String> line : lines) {
        for(int i = 0; i < numColumns; i++) {
            result += pad( line.get(i), maxLengths.get(i) + 1 );
        }
        result += System.lineSeparator();
    }
    return result;
}

private String pad(String word, int newLength){
    while (word.length() < newLength) {
        word += " ";
    }
    return word;
}

}

如何将视图中 ArrayList 的字符串传递给 addLine() 方法?

...that takes strings separated by commas as input.

从技术上讲,它需要一个数组 (more in this Java tutorial on varargs)。但是 Java 允许您在使用离散参数调用它时自动创建该数组。

因为它接受一个数组,而你有一个 ArrayList,你可以很容易地得到一个数组传递给它,使用 toArray(T[]):

List<List<String>> linesToAdd = /*...*/;
// ...
for (List<String> line : linesToAdd) {
    addLine(line.toArray(new String[line.size()]));
}

也就是说,修改 addLine 以直接接受 List<String> 是微不足道的(也是一个很好的编码练习)。

我认为您根本不应该使用 Columns class。

您的大部分列表都是数字而不是字符串。数字最好右对齐显示。在每一行中,您想要显示的唯一字符串是玩家名称。

因此,与其将所有数据复制到各种列表,并假设对于大多数数字,您有一个合理的宽度,它们不会通过(4 位数字?6 位数字?),那么您的任务就变成了:

  • 查找列表中最长的名字
  • 显示每个玩家,以便填充名称以容纳找到的最长名称。

您可以将这些作为方法添加到 Player class,因此找到给定玩家列表的最大名称长度:

public static int maxNameLength( List<? extends Player> players ) {
    int maxLength = 0;
    for ( Player player : players ) {
        int currLength = player.getName().length();
        if ( currLength > maxLength ) {
            maxLength = currLength;
        }
    }
    return maxLength;
}

现在,可以使用 String.format 以适当填充的方式显示当前玩家,它使用 Formatter

为了简洁起见,假设我只想显示名称、Yahtzee 和总分。您将在 Player:

中使用这样的方法
public String getScoreLine( int maxLength ) {

    String format = "%-" + maxLength + "s %6d %6d";

    return String.format( format, getName(), getYahtzee(), getTotalscore() );
}

第一部分所做的是为字符串创建一个左对齐的字段。因此,如果 maxLength 是 20,则格式将为 %-20s %6d %6d。数字将在 6 个字符宽的字段中右对齐显示,名称将左对齐并填充到 20 个字符。

现在您可以在您的列表上循环并将其显示为:

int maxNameLength = Player.maxNameLength( playerList );
for ( Player p : playerList ) {
    System.out.println( p.getScoreLine( maxNameLength ) );
}

注意:如果您想将 getScoreLine 方法放在视图中而不是 Player class 中(因为您正在尝试执行 MVC),则需要给它播放器作为参数。

我听从了不使用列 class 的建议,尽管我想尝试使用它。我对解决方案进行了半硬编码。

playerList 是游戏中的玩家列表。类别是从另一个 class 获得的,以检查评分时哪些类别是可选的。 (不可用时显示为 X,可拾取时显示为 O。)

public void displayMainScoreBoard(ArrayList<Player> playerList, ArrayList<Boolean> categories) {

    List<String> Name = new ArrayList<>();
    List<String> Ones = new ArrayList<>();
    List<String> Twos = new ArrayList<>();
    List<String> Threes = new ArrayList<>();
    List<String> Fours = new ArrayList<>();
    List<String> Fives = new ArrayList<>();
    List<String> Sixes = new ArrayList<>();

    List<String> Threeofakind = new ArrayList<>();
    List<String> Fourofakind = new ArrayList<>();
    List<String> Fullhouse = new ArrayList<>();
    List<String> Smallstraight = new ArrayList<>();
    List<String> Largestraight = new ArrayList<>();
    List<String> Chance = new ArrayList<>();
    List<String> Yahtzee = new ArrayList<>();

    List<String> Totalscore = new ArrayList<>();

    for (Player p : playerList) {                           //For every player, append their category data.
        Name.add(p.getName());
        Ones.add(String.valueOf(p.getOnes()));
        Twos.add(String.valueOf(p.getTwos()));
        Threes.add(String.valueOf(p.getThrees()));
        Fours.add(String.valueOf(p.getFours()));
        Fives.add(String.valueOf(p.getFives()));
        Sixes.add(String.valueOf(p.getSixes()));

        Threeofakind.add(String.valueOf(p.getThreeofakind()));
        Fourofakind.add(String.valueOf(p.getFourofakind()));
        Fullhouse.add(String.valueOf(p.getFullhouse()));
        Smallstraight.add(String.valueOf(p.getSmallstraight()));
        Largestraight.add(String.valueOf(p.getLargestraight()));
        Chance.add(String.valueOf(p.getChance()));
        Yahtzee.add(String.valueOf(p.getYahtzee()));
        Totalscore.add(String.valueOf(p.getTotalscore()));
    }

    boolean checkones = categories.get(0);              //Checkers for which categories are available to score in.
    boolean checktwos = categories.get(1);
    boolean checkthrees = categories.get(2);
    boolean checkfours = categories.get(3);
    boolean checkfives = categories.get(4);
    boolean checksixes = categories.get(5);
    boolean checkthreeofkind = categories.get(6);
    boolean checkfourofkind = categories.get(7);
    boolean checkfullhouse = categories.get(8);
    boolean checksmallstraight = categories.get(9);
    boolean checklargestraight = categories.get(10);
    boolean checkchance = categories.get(11);
    boolean checkyahtzee = categories.get(12);



    System.out.println("| "+                                  "|   | Name            " + stringBuilder(Name));
    System.out.println("|" + isPickable(checkones) +          "|1. | Ones            " + stringBuilder(Ones));
    System.out.println("|" + isPickable(checktwos) +          "|2. | Twos            " + stringBuilder(Twos));
    System.out.println("|" + isPickable(checkthrees) +        "|3. | Threes          " + stringBuilder(Threes));
    System.out.println("|" + isPickable(checkfours) +         "|4. | Fours           " + stringBuilder(Fours));
    System.out.println("|" + isPickable(checkfives) +         "|5. | Fives           " + stringBuilder(Fives));
    System.out.println("|" + isPickable(checksixes) +         "|6. | Sixes           " + stringBuilder(Sixes));
    System.out.println("|" + isPickable(checkthreeofkind) +   "|7. | Three of a kind " + stringBuilder(Threeofakind));
    System.out.println("|" + isPickable(checkfourofkind) +    "|8. | Four of a kind  " + stringBuilder(Fourofakind));
    System.out.println("|" + isPickable(checkfullhouse) +     "|9. | Full House      " + stringBuilder(Fullhouse));
    System.out.println("|" + isPickable(checksmallstraight) + "|1. | Small Straight  " + stringBuilder(Smallstraight));
    System.out.println("|" + isPickable(checklargestraight) + "|11.| Large Straight  " + stringBuilder(Largestraight));
    System.out.println("|" + isPickable(checkchance) +        "|12.| Chance          " + stringBuilder(Chance));
    System.out.println("|" + isPickable(checkyahtzee) +       "|13.| Yahtzee         " + stringBuilder(Yahtzee));
    System.out.println("| "+                                  "|   | Total Score     " + stringBuilder(Totalscore));

}

/*
 * Method for creating the lines for the scoreboard.
 */
public String stringBuilder(List<String> arrIn) {
    StringBuilder sb = new StringBuilder();
    for (String s : arrIn) {
        sb.append("|");
        sb.append(s);
        sb.append(pad(s));
    }
    return sb.toString();
}

/*
 * Method for padding the spaces between columns.
 */
public String pad(String s) {
    int space = 15;
    int sLength = s.length();
    String retPad = "";
    int temp = space - sLength;

    for (int i = 0; i <= temp ; i++) {
        retPad += " ";
    }
    return retPad;
}

public String isPickable(boolean b) {
    if (b == true) {
        return "O";
    }
    else {
        return "X";
    }
}

打印出来:

| |   | Name            |one             |two             |three           
|X|1. | Ones            |0               |0               |0               
|X|2. | Twos            |0               |0               |0               
|X|3. | Threes          |0               |0               |0               
|X|4. | Fours           |0               |0               |0               
|X|5. | Fives           |0               |0               |0               
|X|6. | Sixes           |0               |0               |0               
|X|7. | Three of a kind |0               |0               |0               
|X|8. | Four of a kind  |0               |0               |0               
|X|9. | Full House      |0               |0               |0               
|X|1. | Small Straight  |0               |0               |0               
|X|11.| Large Straight  |0               |0               |0               
|X|12.| Chance          |0               |0               |0               
|X|13.| Yahtzee         |0               |0               |0               
| |   | Total Score     |0               |0               |0  

只要用户不输入长得离谱的名称,这种方式就不错。这可以通过要求用户输入更短的名称(昵称)来解决。 无论如何,感谢您的帮助!