Always take the last line

Discussion in 'Spigot Plugin Development' started by Roimeiqui7, Jul 5, 2018.

  1. Why always is taking the last line in the StringList?

    Code (Text):

                            for(int i = 0; i<lines2.size();i++) {
                                SHDCommand.h = new Hologram(a(color(lines2.get(i)), e.getPlayer()));
                            }
     
    Thanks for help!
     
  2. because it's obvious that it will happen
     
  3. Because you're constantly overriding the "SHDCommand.h" instance using the loop? What did you expect that it would do?
     
  4. I have this method:

    Code (Text):
     public Hologram(String... lines) {
                  this.lines.addAll(Arrays.asList(lines));
               }
     
    And when the server starts it creates an hologram with the lines setted in the config:

    Config:

    Lines:
    - test1
    - test2
    - test3

    Its look like:
    Code (Text):
    ArrayList<String> lines = new ArrayList<String>();
    lines.addAll(HDFile.hd.getStringList("Holograms.Lines");
    new Hologram(lines.get(0), lines.get(1) .... etc);
     
     
  5. But if i do:
    Code (Text):
    for(int i = 0;i<lines.size();i++){
       new Hologram(lines.get(i));
     
    }
    it takes the last line in the stringlist
     
  6. Change
    Code (Java):
    new Hologram(lines.get(0), lines.get(1) .... etc);
    to
    Code (Java):
    new Hologram(lines);
     
    • Agree Agree x 1
  7. Here is what your code is telling the computer to do:
    1. Create a new variable called i, with the value of 0.
    2. Loop through each index in the list "lines2".
    3. On each index, get the string at that index, color it, apply player formatting (I assume) and replace the existing hologram with a new one containing only one line.

    Now, I assume what you need to do is something along the lines of "new Hologram(lines2)"; however, that would not apply those coloring and formatting functions. For that, you can use streams, and then collect to an array. Or just make your Hologram class apply the functions.
     
  8. I cant make new Hologram(lines2); because Hologram its an string, not a list
     
  9. False. The following constructor takes a multi string. Which means it could also take an array. You could convert your list into an array and use it.
    Code (Java):
    public Hologram(String... lines) {
        this.lines.addAll(Arrays.asList(lines));
    }
     
    • Like Like x 1
  10. EDIT: Now working: I put this method in the Hologram class. Thanks for your help guys!
     
  11. The method I prefer is the following, you do need Java 8 for that:
    Code (Java):
    list.stream().toArray(Integer[]::new);
    If you do not have Java 8 you should update it, but you could also use this method:
    Code (Java):
    list.toArray(new Integer[list.size()]);