Jump to content

Java - For Each Loop and Boolean Help Please

Hi there, I'm looking for help on how to do this part... I'm completely new to Java and learning bit by bit. My goal for this thread today is: 

"isValidState () is a private method you must write which contains a local ArrayList of the 50 United States state names, and returns true if the String parameter exists in that ArrayList; otherwise it returns false."

How exactly do I return true or false using boolean? I get a feeling I'm going to be using if statements to do that. Also, I'm not sure how to correctly write out the loop section "for( Type Name: Collection)". I was thinking it would have been "for(String name: state)" but that seems to be incorrect. My current code doesn't actually compile because of how I wrote the loop. I'm supposed to be returning a boolean rather than "return 'true'" or false. Hopefully someone out there can help! Thank you for reading!


import java.util.ArrayList;
/**
 * This class describes what a State is and the possible combinations of it.
 * @author: tomoki
 * @version: 1.0
 */
class State{
    private String name;
    private String capital;
    private int populationInMillions;

    public static final int DEFAULT_POPULATION_MILLIONS = 38;
    public static final String DEFAULT_CAPITAL          = "Sacramento";
    public static final String DEFAULT_STATE            = "California";

    /**
     * This is the no arg constructor.
     */
    public State(){}

    /**
     * This is the first constructor.
     */
    public State(String name, String capital, int populationInMillions){
        /*if((isValidPopulation(populationInMillions) && (isValidState(state) && (isValidCapitalCity(capital))*/{
            this.populationInMillions = populationInMillions;
            this.name                 = name;
            this.capital              = capital;
            /*}else{
            System.out.println("ERROR; using default settings instead");
            this.populationInMillions = DEFAULT_POPULATION_MILLIONS;
            this.state                = DEFAULT_STATE;
            this.capital              = DEFAULT_CAPITAL;*/
        }
    }

    public String 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");

        if(state != null){
            for (String state : state){
                return "true";
            }
        }else{
            return "false";
        }
        return "error";
    }
}

Link to comment
Share on other sites

Link to post
Share on other sites

Hey, Java programmer here.
1. First thing to return a boolean you need to change the type of your method to boolean so 

public String isValidState(String name){

should become

public boolean isValidState(String name){

Everything else looks fine but your loops like you said. I am going to loop through it in a older looping method which might be easier for you to understand. 

if(state != null)
{
	for(int i = 0; i < state.getSize(); i++) //the method might be state.getLength() you will need to check that
    {
    	if(name.equalsIgnoreCase(state.get(i)))
     	{
        	return true;
        }else
        {
        	return false;
        }
    }
}else
{
	return false;
}
    

Hope this helps.

 

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, The Falcon said:

Hey, Java programmer here.
1. First thing to return a boolean you need to change the type of your method to boolean so 


public String isValidState(String name){

should become


public boolean isValidState(String name){

Everything else looks fine but your loops like you said. I am going to loop through it in a older looping method which might be easier for you to understand. 


if(state != null)
{
	for(int i = 0; i < state.getSize(); i++) //the method might be state.getLength() you will need to check that
    {
    	if(name.equalsIgnoreCase(state.get(i)))
     	{
        	return true;
        }else
        {
        	return false;
        }
    }
}else
{
	return false;
}
    

Hope this helps.

 

 

 

Hi there,

 

Thank you very much for the help. Much appreciated! I've been stuck on this for hours but um.. would it be alright for you to explain to me what the line means exactly? I don't exactly get what it means by state.get(i) in: 


if(name.equalsIgnoreCase(state.get(i))) 

 

 

So you're taking the local variable (.getLength isn't needed in this I think. It wasn't stated so yup! Thanks for the consideration!) , and then somehow getting that local variable from above.... hmm..

 

I've only just learnt for-each loop lines. I'll try that though! 

Link to comment
Share on other sites

Link to post
Share on other sites

16 minutes ago, tomoki said:

Hi there,

 

Thank you very much for the help. Much appreciated! I've been stuck on this for hours but um.. would it be alright for you to explain to me what the line means exactly? I don't exactly get what it means by state.get(i) in: 

 


if(name.equalsIgnoreCase(state.get(i))) 

 

 

So you're taking the local variable (.getLength isn't needed in this I think. It wasn't stated so yup! Thanks for the consideration!) , and then somehow getting that local variable from above.... hmm..

 

I've only just learnt for-each loop lines. I'll try that though! 

Basically it is a standard for loop. What it does is for every iteration that i is smaller than the number of objects in state (which is why we have state.getSize()) it adds 1 to i. So in the line 

if(name.equalsIgnoreCase(state.get(i))) 

we are saying if the name (passed as a parameter of the function) is equal to (ignore case just means that if the state is spelt "New York" and the value inside name is "new york" it will not reject it because the case is different. 

The state.get(i) is getting the string value stored at position i, remember i is an integer that is being iterated till it reaches the total size of the arrayList. So if state at position 4 is equal to "new york" then when i is equal to 4 the if will return true. I did however mess up the loops by including else statements. It should rather look like this. 

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

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, The Falcon said:

Basically it is a standard for loop. What it does is for every iteration that i is smaller than the number of objects in state (which is why we have state.getSize()) it adds 1 to i. So in the line 


if(name.equalsIgnoreCase(state.get(i))) 

we are saying if the name (passed as a parameter of the function) is equal to (ignore case just means that if the state is spelt "New York" and the value inside name is "new york" it will not reject it because the case is different. 

The state.get(i) is getting the string value stored at position i, remember i is an integer that is being iterated till it reaches the total size of the arrayList. So if state at position 4 is equal to "new york" then when i is equal to 4 the if will return true. I did however mess up the loops by including else statements. It should rather look like this. 


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

 

 

Ah no no I've only learnt up to "if else" statements so that was perfect. I haven't learn what "while" is yet in class. I have another question for you though. From my initial post, I've included your snippet of code and it compiles like such; however, the chunk of code needed a return statement in the very last line which is normal but I'm not sure what to return so I returned false. Is that going to be alright? The method was initially supposed to be a private method but I put it as public in order to test it. I put in "Texas" as my state String and it returned false probably because of that last line. 

 

I'm using BlueJ by the way! Once again, thank you for your help! 

Capture.PNG

Link to comment
Share on other sites

Link to post
Share on other sites

17 minutes ago, tomoki said:

Ah no no I've only learnt up to "if else" statements so that was perfect. I haven't learn what "while" is yet in class. I have another question for you though. From my initial post, I've included your snippet of code and it compiles like such; however, the chunk of code needed a return statement in the very last line which is normal but I'm not sure what to return so I returned false. Is that going to be alright? The method was initially supposed to be a private method but I put it as public in order to test it. I put in "Texas" as my state String and it returned false probably because of that last line. 

 

I'm using BlueJ by the way! Once again, thank you for your help! 

Capture.PNG

You'll want to go through the entire list before returning false. I think it should be pretty self-explanatory why (you need to go through the entire list to check if an item is in that list).

It would be something like this :

for(String i : state)
{
if(name.equalsIgnoreCase(i)) return true;
}
return false;

 

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

12 minutes ago, Nineshadow said:

You'll want to go through the entire list before returning false. I think it should be pretty self-explanatory why (you need to go through the entire list to check if an item is in that list).

It would be something like this :


for(String i : state)
{
if(name.equalsIgnoreCase(i)) return true;
}
return false;

 

Thanks for your input as well! 

Yes that is much simpler and works too (at least from my newbie looks haha) but that last line outside of the chunk of code.. I've highlighted it in my image. Would that affect the code? The compiler said missing return statement so that's what I put. 

Capture2.PNG

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, tomoki said:

Thanks for your input as well! 

Yes that is much simpler and works too (at least from my newbie looks haha) but that last line outside of the chunk of code.. I've highlighted it in my image. Would that affect the code? The compiler said missing return statement so that's what I put. 

Capture2.PNG

That's fine. That's what it should do. But the else statement with the "return false" inside the loop is wrong. It will compile, but it won't work as intended.

i5 4670k @ 4.2GHz (Coolermaster Hyper 212 Evo); ASrock Z87 EXTREME4; 8GB Kingston HyperX Beast DDR3 RAM @ 2133MHz; Asus DirectCU GTX 560; Super Flower Golden King 550 Platinum PSU;1TB Seagate Barracuda;Corsair 200r case. 

Link to comment
Share on other sites

Link to post
Share on other sites

30 minutes ago, tomoki said:

Ah no no I've only learnt up to "if else" statements so that was perfect. I haven't learn what "while" is yet in class. I have another question for you though. From my initial post, I've included your snippet of code and it compiles like such; however, the chunk of code needed a return statement in the very last line which is normal but I'm not sure what to return so I returned false. Is that going to be alright? The method was initially supposed to be a private method but I put it as public in order to test it. I put in "Texas" as my state String and it returned false probably because of that last line. 

 

I'm using BlueJ by the way! Once again, thank you for your help! 

Capture.PNG

This is why I took out the else statements. You dont have to use a while though you can use an if and it should still work. Like this: 

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

You have to use a variable to store the returned boolean otherwise you will end up with the issue you have right now. What for loop you use does not really matter. 

Link to comment
Share on other sites

Link to post
Share on other sites

2 minutes ago, Nineshadow said:

That's fine. That's what it should do. But the else statement with the "return false" inside the loop is wrong. It will compile, but it won't work as intended.

Oh.. I've only learnt if else statements this way. My instructor has told us to not worry about it for now and said that if there is 1 "if", there must be an "else" to end with. Thank you for your reply! 

 

2 minutes ago, The Falcon said:

This is why I took out the else statements. You dont have to use a while though you can use an if and it should still work. Like this: 


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

You have to use a variable to store the returned boolean otherwise you will end up with the issue you have right now. What for loop you use does not really matter. 

Oh... That looks rather interesting :D I've seen a few classmates who know what they're doing do something like that.. not as complex but the return value; they did. Thank you! 

Link to comment
Share on other sites

Link to post
Share on other sites

1 minute ago, The Falcon said:

Your learning Java in high school right? 

I'm learning it in a trades school. They teach something new every class and it just stacks up. I started Java at the beginning of May. It's going too fast for me currently so I want to catch up. I didn't really know where to get help because all of this is really new to me. My understanding of what to do is perfectly fine but the "how" to do it is beyond me a lot of the time. After hours of thinking, I usually come up with something that may or may not work hahaha. I'm not sure if I'm going to ever get a hang of this.

 

Textbook examples aren't good enough and online resources at places like stackoverflow are too complex for me to understand. I'm only supposed to be using up to what they've taught. 

Link to comment
Share on other sites

Link to post
Share on other sites

You should be aware that each time you call isValidState you are recreating that list. Since this looks like static data that won't ever change during the lifetime of your application then you should look to be instantiating this one time only somewhere appropriate.

 

Moreover if you have a look at ArrayList<E>.contains it does exactly what you want for you. One should always be mindful of reinventing the wheel - even when it is forced upon oneself.

The single biggest problem in communication is the illusion that it has taken place.

Link to comment
Share on other sites

Link to post
Share on other sites

12 hours ago, The Falcon said:

This is why I took out the else statements. You dont have to use a while though you can use an if and it should still work. Like this: 


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

You have to use a variable to store the returned boolean otherwise you will end up with the issue you have right now. What for loop you use does not really matter. 

You don't need to have a variable track the value, instead you can just return on true, and after the loops put a return false. It will work exactly the same way except you'll increase the performance (your method must iterate through all states every time, whereas this method would only have to go through half the states on average) 

15" MBP TB

AMD 5800X | Gigabyte Aorus Master | EVGA 2060 KO Ultra | Define 7 || Blade Server: Intel 3570k | GD65 | Corsair C70 | 13TB

Link to comment
Share on other sites

Link to post
Share on other sites

Use the "contains(Object)" method. It returns true if the object is found, else it returns false. So all you have to do is say "string state = "Vermont"" then say "return myList.contains(state)" when you call it in your main method just do something like "bool contains = CheckStates("Vermont")" and then you can pass "contains" around as your object. Alternatively, if you need to use it in just one decision statement, you could just do something like "if (CheckStates"Vermont" == true){//Your code here}".

 

The ArrayList.Contains() method will do exactly the same thing at run time as iterating through your list with a for loop, but it is a much more concise and shows the intent of your code better.

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

Link to post
Share on other sites

20 hours ago, Nuluvius said:

You should be aware that each time you call isValidState you are recreating that list. Since this looks like static data that won't ever change during the lifetime of your application then you should look to be instantiating this one time only somewhere appropriate.

 

Moreover if you have a look at ArrayList<E>.contains it does exactly what you want for you. One should always be mindful of reinventing the wheel - even when it is forced upon oneself.

 

10 hours ago, straight_stewie said:

Use the "contains(Object)" method. It returns true if the object is found, else it returns false. So all you have to do is say "string state = "Vermont"" then say "return myList.contains(state)" when you call it in your main method just do something like "bool contains = CheckStates("Vermont")" and then you can pass "contains" around as your object. Alternatively, if you need to use it in just one decision statement, you could just do something like "if (CheckStates"Vermont" == true){//Your code here}".

 

The ArrayList.Contains() method will do exactly the same thing at run time as iterating through your list with a for loop, but it is a much more concise and shows the intent of your code better.

@Nuluvius and @straight_stewie I ...haven't learnt what the .contains() method is exactly but I'm thinking from common sense that if it contains the Strings I put into the ArrayList, it would check it over? It sorta makes sense from that second quote and I get the idea of it. I'm bound to have more questions on this because I'm stuck elsewhere already haha. I'm giving it multiple tries before asking so I actually attempt to learn something myself. Thanks for the replies :)

 

11 hours ago, Blade of Grass said:

You don't need to have a variable track the value, instead you can just return on true, and after the loops put a return false. It will work exactly the same way except you'll increase the performance (your method must iterate through all states every time, whereas this method would only have to go through half the states on average) 

Wait how does this work? In my head it's like...  if it's outside the if statement block of code, it would return true automatically right...? No matter what it goes through for the if statement. I'm probably too new to understand xD My ideas are still all over. 

Link to comment
Share on other sites

Link to post
Share on other sites

9 minutes ago, tomoki said:

I'm giving it multiple tries before asking so I actually attempt to learn something myself.

That's really good to hear. Many on here simply don't bother... Are you familiar with how to debug your code?

The single biggest problem in communication is the illusion that it has taken place.

Link to comment
Share on other sites

Link to post
Share on other sites

5 minutes ago, Nuluvius said:

That's really good to hear. Many on here simply don't bother... Are you familiar with how to debug your code?

You mean compile and then look for errors + create objects and unit tests to test my code? I'm using BlueJ. We haven't moved on to.... I think it's called Eclipse? I think there are other programs. Not sure which I will be using in the future. 

Link to comment
Share on other sites

Link to post
Share on other sites

13 minutes ago, tomoki said:

You mean compile and then look for errors + create objects and unit tests to test my code?

While those are important concepts, especially the unit testing, I am more meaning the setting of breakpoints and then the stepping through of the execution flow of your program such that you may inspect its state as you go.

13 minutes ago, tomoki said:

I'm using BlueJ. We haven't moved on to.... I think it's called Eclipse? I think there are other programs. Not sure which I will be using in the future. 

I would highly suggest that you switch to IntelliJ as soon as you can over either of those two. For Java especially it is simply superior as it's built onto of their ReSharper technology. You should at least be able to choose your own development environment... right... surly...?

The single biggest problem in communication is the illusion that it has taken place.

Link to comment
Share on other sites

Link to post
Share on other sites

8 minutes ago, Nuluvius said:

While those are important concepts, especially the unit testing, I am more meaning the setting of breakpoints and then stepping through the execution flow of your program such that you may inspect its state as you go.

I would highly suggest that you switch to IntelliJ as soon as you can over either of those two. For Java especially it is simply superior as it's built onto of their ReSharper technology. You should at least be able to choose your own development environment... right... surly...?

Ah I have no idea how to do that. 

 

And for the second part... I'll ask! I'm probably going to be stuck with BlueJ for the next...2 months I'm guessing. I've only been learning for a month. This is my second month into Java. I have another 2 to go after this month. 

 

I'm having trouble with this ...totally different code project from the ones I've posted previously in the thread. Something is wrong with that constructor whenever I try it. I input an integer to create my object such as "5"...which refers to Friday but it spits out "Monday"? The methods in this are:

 


 /**
     * @return the day of the week when dayNumber has an int value.
     */
    public String getDayOfTheWeek(){
        if(dayNumber.getValue() == SUNDAY){
            return SUNDAY_STRING;
        }else if(dayNumber.getValue() == MONDAY){
            return MONDAY_STRING;
        }else if(dayNumber.getValue() == TUESDAY){
            return TUESDAY_STRING;
        }else if(dayNumber.getValue() == WEDNESDAY){
            return WEDNESDAY_STRING;
        }else if(dayNumber.getValue() == THURSDAY){
            return THURSDAY_STRING;
        }else if(dayNumber.getValue() == FRIDAY){
            return FRIDAY_STRING;
        }else if(dayNumber.getValue() == SATURDAY){
            return SATURDAY_STRING;
        }else{
            return "Invalid input for day number.";
        }
    }

    /**
     * calls the dayNumber increment() method. 
     */
    public void incrementDay(){
        if(dayNumber.getValue() == SATURDAY){
            dayNumber.increment();
        }
    }

    /**
     * @return a String corresponding to the next day. 
     */
    public String getWhatDayIsTomorrow(){
        if(dayNumber.getValue() == SUNDAY){
            return MONDAY_STRING;
        }else if(dayNumber.getValue() == MONDAY){
            return TUESDAY_STRING;
        }else if(dayNumber.getValue() == TUESDAY){
            return WEDNESDAY_STRING;
        }else if(dayNumber.getValue() == WEDNESDAY){
            return THURSDAY_STRING;
        }else if(dayNumber.getValue() == THURSDAY){
            return FRIDAY_STRING;
        }else if(dayNumber.getValue() == FRIDAY){
            return SATURDAY_STRING;
        }else if(dayNumber.getValue() == SATURDAY){
            return SUNDAY_STRING;
        }else{
            return "Invalid";
        }
    }

 

It looks perfectly normal to me. My other constructors I've tested and they work correctly.... 

Constructor is below:

 

Capture3.PNG

 

P.S. I need to sleep..gotta get up early. It's past 3:30am here. Thanks for your input btw @Nuluvius

Link to comment
Share on other sites

Link to post
Share on other sites

8 minutes ago, tomoki said:

Capture3.PNG

Look carefully at that condition:

theDayNumber <= 0 && theDayNumber >= 6

What you are saying is: Only enter that block if the variable is less or equal to 0 and greater or equal to 6 thus limiting your day selection to 0 and 6 exclusively. With a value of 5 your else block will therefore be executed providing you 0 = Monday.

 

If you were able to debug your code then you could have clearly observed this at runtime. At this point I would say that it is quite important that you start debugging because it's going to save you a lot of time and grief in the very near future.

The single biggest problem in communication is the illusion that it has taken place.

Link to comment
Share on other sites

Link to post
Share on other sites

7 hours ago, Nuluvius said:

Look carefully at that condition:


theDayNumber <= 0 && theDayNumber >= 6

What you are saying is: Only enter that block if the variable is less or equal to 0 and greater or equal to 6 thus limiting your day selection to 0 and 6 exclusively. With a value of 5 your else block will therefore be executed providing you 0 = Monday.

 

If you were able to debug your code then you could have clearly observed this at runtime. At this point I would say that it is quite important that you start debugging because it's going to save you a lot of time and grief in the very near future.

OHHHH ~ hahaha ...I have always had problems with < , > signs... I had this same error in another post a while back and yeah... this is the second time it's gotten me in code. 

it should be theDayNumber >= 0 && theDayNumber <=6 ... Thanks ~~ 

 

So I should start using "break" for debugging? 

 

EDIT: I'm...still getting some random day hmmm... 

Link to comment
Share on other sites

Link to post
Share on other sites

9 minutes ago, tomoki said:

OHHHH ~ hahaha ...I have always had problems with < , > signs... I had this same error in another post a while back and yeah... this is the second time it's gotten me in code. 

it should be theDayNumber <= 0 && theDayNumber <=6 ... Thanks ~~ 

 

So I should start using "break" for debugging? 

nope, that would check if the day number is only smaller than 0

 

thedaynumber <= 0 ---- day number smaller equal zero

thedaynumber <= 6 ---- day number smaller equal 6

 

these together will only be true if the number is smaller equal 0.

 

A good way to remember how the smaller than (<) and larger than (>) signs work is that the sign itself has a big and a small side.

The large side of the sign is the number that will be larger then the one on the small side

 

if (large_side > small_side) { ---- if large_side is greater than small_side

if (small_side < large_side) { ---- if small_side is smaller than large_side

These are the same condition just showing that you can reverse it however you want.

 

The <> are by default non inclusive, adding the = will include the case that both sides are the same.

 

so your condition should be:

theDayNumber >= 0 && theDayNumber <=6

 

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, tomoki said:

So I should start using "break" for debugging? 

No you should use a break point, it's a different thing entirely. I found this tutorial for BlueJ that demonstrates how to accomplish more or less what you need.

 

I will reiterate once again however that you should make the transition to IntelliJ as soon as you can. Debugging is made many more times easier and the intellisense will often tell you if you have done something that's not quite right and even help you with optimizations.

The single biggest problem in communication is the illusion that it has taken place.

Link to comment
Share on other sites

Link to post
Share on other sites

Just now, tomoki said:

I'm having trouble with this ...totally different code project from the ones I've posted previously in the thread. Something is wrong with that constructor whenever I try it. I input an integer to create my object such as "5"...which refers to Friday but it spits out "Monday"? The methods in this are:

You should research "enums. This is a good place to start (it actually uses your problem as an example, lol): https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

The major benefit of object orientation and managed languages is "abstraction". You can use this to your advantage to make implementing solutions to problems so much easier by "abstracting" away all of the details of implementation and instead focusing on what problem it is you are trying to solve. 

 

Alternatively, you could do something like this (this code is C#):
 

        static void Main(string[] args)
        {
            string[] daysAgain = new string[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

            start:
            Console.WriteLine("Select a number between 1 and 7");
            int userChoice = Convert.ToInt32(Console.ReadLine());

            try
            {
                Console.WriteLine(daysAgain[userChoice - 1]);
            }
            catch (IndexOutOfRangeException)
            {
                Console.WriteLine("Please enter a value between 1 and 7");
            }
            catch (Exception ex)
            {
                Console.WriteLine("There was a problem:");
                Console.WriteLine(ex.Message);
            }

            goto start;
Just now, tomoki said:

I ...haven't learnt what the .contains() method is exactly but I'm thinking from common sense that if it contains the Strings I put into the ArrayList, it would check it over?

That's exactly correct. This is just a method where you pass it a search value and it iterates through the collection (probably using a foreach loop) until it finds your value: If it finds your value it returns a boolean of true, if it gets to the end of the collection and hasn't found your value it returns false. It is just a oneliner for your current implementation. There is a really good resource for finding out what tools (namespaces, classes, methods, and properties) are available to you, how to use them, and what they are called: https://docs.oracle.com/javase/7/docs/api/overview-summary.html

Unfortunately that page is hard to navigate, and requires some knowledge of what you are looking for. For a company that designs and maintains a very nice language they sure don't know how to actually use it. That's one of the reasons why I chose C# as a first language. http://msdn.microsoft.com is much better organized and easier to use. Sounds like yours is for school though, so you're stuck using whatever your teacher wants :/

ENCRYPTION IS NOT A CRIME

Link to comment
Share on other sites

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

×