2

I'm sorry if the question is a bit vague so i'll try to explain it.

I got this code:

    public String toString()
{
    String s = "text.\n";

    for (Klus k : alleKlussen)
    {
        s += k.toString() + ".\n";
    }
    return s;
}

But I want to make different loops for different conditions. For example, "Klus" has a couple of variables like: status, date etc.

I'm not very experienced with java yet, but would it be possible to do something like this:

for (Klus k : alleKlussen; status = "completed")
{..}

I know this is wrong but I'd like it to show all "Klus" objects where the status is "completed" and all "Klus" objects where the statis is "not completed".

Thanks and if anything is unclear or I used the wrong word for something, please tell me.

Edit:

It should make something like this:

if (k.getStatus().equals("completed"){
  String s = "completed ones \n"
  s += k.toString() + ".\n"; //get all completed ones
}
if (k.getStatus().equals("uncompleted"){
      String s = "uncompleted ones \n"
      s += k.toString() + ".\n"; //get all uncompleted ones
    }
5
  • 2
    Please use a StringBuilder for iterative String concatenation! So much object burn... Commented Apr 5, 2013 at 11:04
  • Inside your for loop you'll just be wanting an if surely? Commented Apr 5, 2013 at 11:06
  • 1
    I think I explained it a bit wrong, I edited my question Commented Apr 5, 2013 at 11:09
  • your edit basically shows the answer. I fail to see the question now. Commented Apr 5, 2013 at 11:16
  • What version of java you are using? Commented Apr 5, 2013 at 11:20

5 Answers 5

4

Simply add the condition inside the for() loop:

for (Klus k : alleKlussen) {
    if (k.getStatus().equals("completed")) {
        s += k.toString() + ".\n";
    }
}

From the additional information in the question, it seems like the following is what is intended:

String completed = "completed ones \n";
String uncompleted = "uncompleted ones \n";

for (Klus k : alleKlussen) {

    if (k.getStatus().equals("completed")) {
      completed += k.toString() + ".\n"; //get all completed ones
    }
    else if (k.getStatus().equals("uncompleted")) {
       uncompleted += k.toString() + ".\n"; //get all uncompleted ones
    }
}

You should also consider using a StringBuilder to create the result strings, which reduces the memory overhead.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! I forgot about the if statement but it's not exactly what I'm looking for, I think I explained it a bit wrong. I edited my question
This works for all completed ones, but how should i do the same for the uncompleted ones? just make another for-loop in the toString()?
@colin check my updated answer - is this what you need? You have two different Strings afterwards, containing information from completed and uncompleted objects. You could use two for() loops, but then you would need to iterate your list twice
Depending on what @colin needs, he could always just concatenate the two strings and return the result
Thanks, this did it for me. I just needed a list with the completed and uncompleted ones and this does just that!
2

You can use switch if you have many conditions and it is easy to read

for (Klus k : alleKlussen) {

switch(k.getStatus()){
       case "completed": ....
                          break;

       case "uncompleted": ....
                            break;

        default: ...
}

}

Please note switch with String literals is only supported in Java 7.

6 Comments

Why, this would be a perfect case for enums, even if String literals are supported
Thanks for your answer, but how should it select only the "Klus" objects with "completed" in that case?
@Colin It is not possible to "just" get "Klus" objects depending on object status in this scenario. You need to iterate through the objects and check.
@Simon I agree, but in the original question the user is not using enums. He is using status as String literals.
I think this everntually also would've worked, but the other one was a bit more simple because I haven't learned to use cases yet. Thanks anyway!
|
0
   Use this - this toString will print only Klus are completed.
 public String toString()
    {
        String s = "text.\n";

        for (Klus k : alleKlussen)
        {
            if("completed".equals(k.getStatus ()))
            s += k.toString() + ".\n";
        }
        return s;
    }

Comments

0

Why not just do the standard if-conditionals, such as:

if ("".equals(k.getStatus())) {

} else if ("completed".equals(k.getStatus())) {

}

2 Comments

A person with 20k rep suggestion to use == for String value comparison? Unbelievable.
@R.J That wasn't my suggestion, my suggestion was to use a standard convention in most languages - if statements - the equality check was incidentally my lack of knowledge of Java specifically, but I don't think that detracts from the actual suggestion. Unbelievably judgmental, maybe, as if you expect I got 20k rep in the java.
0

To append the uncompleted after the completed ones, try this (And I suggest using enums, but you are welcome to stick to Strings. But then this will only work in Java SE 7!):

State.java:

// Makes switches easy to use and String typos are impossible
public enum State { COMPLETE, INCOMPLETE };

Replace your current String "state" with the enum like so:

Klus:java

public class Klus {
   private State state;
   ...
   public State getState() { return this.state; }
   ...
}

Now use it in a switch in the for loop. Use two strings, one for complete, one for incomplete. Append them in the end. (Note the use of StringBuilder instead of str +=... )

Class containing your toString():

public String toString() {
    StringBuilder complete = new StringBuilder("completed ones \n"), 
                  uncompleted = new StringBuilder("uncompleted ones \n");
    for(Klus k : alleKlussen) {
       switch(k.getStatus())
       case COMPLETE:
          complete.append(k.toString()).append(".\n"); break;
       case INCOMPLETE:
          uncompleted.append(k.toString()).append(".\n"); break;
       default:
       }
    }

    complete.append(uncompleted.toString();

    return complete.toString();
}

2 Comments

Thanks for the answer, I see a lot of things I haven't heard about yet. But maybe in the final version I could also use this method for the statuses. Thanks.
@colin you're welcome. Andreas' answer helps you out without all the extra bells and whistles, though :-D Have fun coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.