Jump to content

Hey Everyone, 

So around 2 weeks ago, I learnt how to write a foreach loop but now I'm given the task of writing a while loop. 

Here's the method these loops are responsible for: 


/*
     * This method returns true if a valid state name is given.
     */
    private boolean isValidState(String name){
        ArrayList<String> state; 
        state = new ArrayList<String>();

        state.add("Alabama");
        state.add("Alaska");
        state.add("Arizona");
        state.add("Arkansas");
        state.add("California");
        state.add("Colorado");
        state.add("Connecticut");
        state.add("Delaware");
        state.add("Florida");
        state.add("Georgia");
        state.add("Hawaii");
        state.add("Idaho");
        state.add("Illinois");
        state.add("Indiana");
        state.add("Iowa");
        state.add("Kansas");
        state.add("Kentucky");
        state.add("Louisana");
        state.add("Maine");
        state.add("Maryland");
        state.add("Massachusetts");
        state.add("Michigan");
        state.add("Minnesota");
        state.add("Mississippi");
        state.add("Missouri");
        state.add("Montana");
        state.add("Nebraska");
        state.add("Nevada");
        state.add("New Hampshire");
        state.add("New Jersey");
        state.add("New Mexico");
        state.add("New York");
        state.add("North Carolina");
        state.add("North Dakota");
        state.add("Ohio");
        state.add("Oklahoma");
        state.add("Oregon");
        state.add("Pennsylvania");
        state.add("Rhode Island");
        state.add("South Carolina");
        state.add("South Dakota");
        state.add("Tennessee");
        state.add("Texas");
        state.add("Utah");
        state.add("Vermont");
        state.add("Virginia");
        state.add("Washington");
        state.add("West Virginia");
        state.add("Wisconsin");
        state.add("Wyoming");

 

 

boolean value = false;
        if(state != null)
        {
            if(value == false)
            {
                for(int i = 0; i < state.size(); i++)
                {
                    if(name.equalsIgnoreCase(state.get(i)))
                    {
                        value = true;
                    }
                }
            }
        }
        return value;

 

How exactly do I change this code above to a while loop? So far I've attempted this but it doesn't exactly work... I think I'm missing something: 


int i;
        while(i < state.size()){
        i++;
        
        }

 

Link to comment
https://linustechtips.com/topic/611423-java-from-foreach-loops-into-while-loops/
Share on other sites

Link to post
Share on other sites

3 minutes ago, tomoki said:

Hey Everyone, 

So around 2 weeks ago, I learnt how to write a foreach loop but now I'm given the task of writing a while loop. 

Here's the method these loops are responsible for: 

-snip-

How exactly do I change this code above to a while loop? So far I've attempted this but it doesn't exactly work... I think I'm missing something: 


int i;
        while(i < state.size()){
        i++;
        
        }

 

On mobile right now so I am only glancing over. For starters try initializing I to an appropriate value such as 0.

CPU: Intel i7 - 5820k @ 4.5GHz, Cooler: Corsair H80i, Motherboard: MSI X99S Gaming 7, RAM: Corsair Vengeance LPX 32GB DDR4 2666MHz CL16,

GPU: ASUS GTX 980 Strix, Case: Corsair 900D, PSU: Corsair AX860i 860W, Keyboard: Logitech G19, Mouse: Corsair M95, Storage: Intel 730 Series 480GB SSD, WD 1.5TB Black

Display: BenQ XL2730Z 2560x1440 144Hz

Link to post
Share on other sites

As a sort of tip, while loops are good if the variable you're checking does not have a pattern to it. Like waiting for a specific input from a user to exit. For loops are better when the variable you're checking has a pattern.

Link to post
Share on other sites

3 minutes ago, SSL said:

You need to initialize the value of i.

 

fwiw, I use for loops almost exclusively; the syntax is tidier and more readable.

 

2 minutes ago, M.Yurizaki said:

You forgot to initialize i.

 

If you want to be fancy, you can also do:


while (i++ < state.size()) {
  /* do stuff here */
}

 

 

1 minute ago, trag1c said:

On mobile right now so I am only glancing over. For starters try initializing I to an appropriate value such as 0.

Would it be possible to do something like 


     int i = 0; 

     while (i < state.size()){

     return true;

     i++;

}

 

Would that be the same as @M.Yurizaki 's code? 

Link to post
Share on other sites

4 minutes ago, SSL said:

fwiw, I use for loops almost exclusively; the syntax is tidier and more readable.

 

1 minute ago, M.Yurizaki said:

As a sort of tip, while loops are good if the variable you're checking does not have a pattern to it. Like waiting for a specific input from a user to exit. For loops are better when the variable you're checking has a pattern.

These. For loops are the way to go when it needs to operate for n iterations.

CPU: Intel i7 - 5820k @ 4.5GHz, Cooler: Corsair H80i, Motherboard: MSI X99S Gaming 7, RAM: Corsair Vengeance LPX 32GB DDR4 2666MHz CL16,

GPU: ASUS GTX 980 Strix, Case: Corsair 900D, PSU: Corsair AX860i 860W, Keyboard: Logitech G19, Mouse: Corsair M95, Storage: Intel 730 Series 480GB SSD, WD 1.5TB Black

Display: BenQ XL2730Z 2560x1440 144Hz

Link to post
Share on other sites

1 minute ago, tomoki said:

 


     int i = 0; 

     while (i < state.size()){

     return true;

     i++;

}

 

Would that be the same as @M.Yurizaki 's code? 

No. That return line would break out of the loop well before it executes another iteration. Remove that line and it is a functioning while loop.

CPU: Intel i7 - 5820k @ 4.5GHz, Cooler: Corsair H80i, Motherboard: MSI X99S Gaming 7, RAM: Corsair Vengeance LPX 32GB DDR4 2666MHz CL16,

GPU: ASUS GTX 980 Strix, Case: Corsair 900D, PSU: Corsair AX860i 860W, Keyboard: Logitech G19, Mouse: Corsair M95, Storage: Intel 730 Series 480GB SSD, WD 1.5TB Black

Display: BenQ XL2730Z 2560x1440 144Hz

Link to post
Share on other sites

1 minute ago, trag1c said:

 

These. For loops are the way to go when it needs to operate for n iterations.

Ah... I was just given the task to try it out and then got stuck. I'm supposed to try it out with the import java.util.Iterator as well but with different methods. I'll probably make a different post on that because ...while I know something about while loop at least, I know nothing about Iterator (get, add, remove, and such). 

Link to post
Share on other sites

1 minute ago, trag1c said:

No. That return line would break out of the loop well before it executes another iteration. Remove that line and it is a functioning while loop.

Oh... but if I were to return a value of true or false, I would need a local variable then? Sorta like the initial foreach loop I had? 

Link to post
Share on other sites

3 minutes ago, tomoki said:

Oh... but if I were to return a value of true or false, I would need a local variable then? Sorta like the initial foreach loop I had? 

If you're returning a true/false the moment you hit something, you should have the exit condition in the loop and return in there. Like

 

while ( i < state.size() {
  if (state[i] == "Something"){
    return true;
  }
}
                        
return false;

Also if Java is like C# and I have no reason to believe this isn't in Java since C# is a copypasta of Java... you could try a foreach loop instead of a for or while loop to iterate through the list.

 

EDIT: There's an error in my code, but I can't fix it so I'll leave it up to you to figure it out :3

Link to post
Share on other sites

1 minute ago, tomoki said:

Would it be possible to do something like 


     int i = 0; 

     while (i < state.size()){

     return true;

     i++;

}

 

Avoid early returns. It is less readable and makes in harder to logically prove program correctness.

 

if(name.equalsIgnoreCase(state.get(i)))
{
  value = true;
}

 

Don't do this. You're checking the result of a boolean expression, and then setting another boolean variable.

Link to post
Share on other sites

3 minutes ago, M.Yurizaki said:

If you're returning a true/false the moment you hit something, you should have the exit condition in the loop and return in there. Like

 


while ( i < state.size() {
  if (state[i] == "Something"){
    return true;
  }
}
                        
return false;

 

In this case, would I have to put if statements for every state listed due to "state == "Something" " ? I'm just wondering if this works like the .contains() method.. 

 

8 minutes ago, SSL said:

Avoid early returns. It is less readable and makes in harder to logically prove program correctness.

 


if(name.equalsIgnoreCase(state.get(i)))
{
  value = true;
}

 

Don't do this. You're checking the result of a boolean expression, and then setting another boolean variable.

Ah okay. And for the "don't do this" part, I posted on this forum about foreach loop as well cause I got stuck on that 2 weeks ago. I wasn't sure how to return a value because the compiler kept asking me to return something. Should I have just return false at the end of everything? 

Link to post
Share on other sites

20 minutes ago, paprikman said:

Btw, you can create a string array with all those names like


String[] arr = {"name1", "name2"};

And then go like


for (String s : arr) {
  state.add(s);
}

 

At that point, just use the String array. No need for the ArrayList to even be involved.

 

24 minutes ago, tomoki said:

In this case, would I have to put if statements for every state listed due to "state == "Something" " ? I'm just wondering if this works like the .contains() method.. 

 

Ah okay. And for the "don't do this" part, I posted on this forum about foreach loop as well cause I got stuck on that 2 weeks ago. I wasn't sure how to return a value because the compiler kept asking me to return something. Should I have just return false at the end of everything? 

 

You should have a single return at the end of the function. Use a variable to keep track of the result:

boolean valid = true;

for (int i = 0; i < state.size() && valid; ++i)
{
  valid = name.equalsIgnoreCase(state.get(i))
}
                                
return valid;

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×