When would I loop over an array's length?

Discussion in 'Programming' started by NaJated, May 27, 2015.

Thread Status:
Not open for further replies.
  1. hey all, I was just wondering, I know how to use all the for loops, I know how to use a foreach loop correctly just the for looping over an array just seems pointless, could someone give me some context of when I would use it? THX :D
  2. Inkzzz

    Resource Staff

    You'd loop over an array for many reasons, but below is an example...

    Code (Text):
    String[] myArray = {"Hello","GoodBye"};
    for(String s : myArray) { if(myArray.contains("Hello") { p.sendMessage("Why does one do such a thing?"); } }
  3. That's a foreach loop..
  4. Inkzzz

    Resource Staff

    You mean something like this?
    Code (Text):
    var myStringArray = ["Hello","World"];
    var arrayLength = myStringArray.length;
    for (var i = 0; i < arrayLength; i++) {
        //Do something
  5. yersss
  6. Here's an example off the top of my head:

    Let's say I have a list of strings that I want to print out to a player in the following fashion:
    1. String 1
    2. String 2
    3. String 3
    4. ...
    This list could be defined as
    Code (Java):
    List<String> strings = new ArrayList<String>();
    I would print the list in the format to the player using:
    Code (Java):
    Player player = ...;
    for (int i = 0 ; i < strings.size() ; i++) {
        player.sendMessage((i + 1) + ". " + strings.get(i));
    You could use a for-each loop to accomplish the same thing (using a separate integer to count the index), but the standard for loop is the better option. Other uses I have in my code are below:
    Code (Java):
    * Gets the last chat color in the message, defaults to white

    private ChatColor getLast(String s) {
        char c = 'f';

        for (int i = s.length() - 1 ; i > -1 ; i--) {
            if (s.charAt(i) == '&') {
                c = s.charAt(i + 1);

        return ChatColor.getByChar(c);
    Code (Java):
    Block block = event.getBlockPlaced();
    Sign state = (Sign) block.getState();
    List<String> lores = item.getItemMeta().getLore();

    for (int i = 0 ; i < 4 && i < lores.size() ; i++) {
        state.setLine(i, lores.get(i));
  7. That's what I don't get, how can a declared int value be turned into a string.[/QUOTE]
  8. wat?
    • Like Like x 1
  9. never mind haha
  10. [/QUOTE]
    Java has a method called "toString" in every object that will convert the object into a string automatically whenever needed.
  11. jflory7

    jflory7 Retired Moderator
    Retired Benefactor

    Thread locked per request
Thread Status:
Not open for further replies.