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

时间:2015-11-14 12:42:32

标签: java string arraylist multiple-columns

有没有办法提取"提取" ArrayList中的单个字符串? 我已将字符串存储在ArrayList中,并希望将它们打印到控制台。 我知道我可以使用for循环,但它并不那么简单。我正在尝试创建基于列的打印,并且我使用一种方法(由#34创建; 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()方法与行的每个arraylists。

如果有更好的解决方法,我会非常乐意知道。

编辑:

从一开始:

我创造了一个拥有1-5名玩家的Yahtzee游戏。每个播放器都由类&#34;播放器&#34;

的实例定义
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结构(尽我所能),这意味着我有一个View类,其中包含一个显示主控制台列记分板的方法。 (方法未完成)

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的完整专栏课程。 (同样,我声称他的代码没有权利。)

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;
}

}

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

3 个答案:

答案 0 :(得分:0)

  

...将逗号分隔的字符串作为输入。

从技术上讲,它需要一个数组(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>将是微不足道的(以及良好的编码练习)。

答案 1 :(得分:0)

我相信你根本不应该使用那个Columns课程。

您的大多数列表都是数字而不是字符串。数字最好显示右对齐。并且您想要显示的每个行中唯一的字符串是播放器名称。

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

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

您可以将这些作为方法添加到Player类,以便查找给定播放列表的最大名称长度:

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方法放在你的View而不是Player类中(因为你试图做MVC),你需要把它作为一个播放器。参数。

答案 2 :(得分:0)

我遵循了不使用列类的建议,即使我想尝试使用它。我对解决方案进行了半硬编码。

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

case Value of
  IntVal  x -> doWhatYouWantToDoWithInteger x
  BoolVal x -> doWhatYouWantToDoWithBoolean x

打印出来:

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";
    }
}

只要用户没有输入可笑的长名称,这种方式就会很好看。这可以通过要求用户输入较短的名称(昵称)来解决。 无论如何,谢谢你的帮助!