0

I am trying to get an element from array and use it later in my code, but I have some logic error in my code. I would like a user to enter what day he or she needs cleaning and then to print out the day of cleaning. Here is the code:

import java.util.Scanner;

public class arrayLoopTest {

    public static void main(String[] args) {
        Scanner scr = new Scanner(System.in);
        String[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

        int i = 0;
        while (true) {
            System.out.println("On what day should the cleaning be scheduled ? ");
            String schedule = scr.nextLine();

            for (i = 0; i < days.length; i++) {

                if (days[i].equals(schedule)) {

                    System.out.println("Cleaning scheduled for " + schedule);

                } else {
                    System.out.println("Invalid, You have to choose one of these days: \n " + days[i]);
                }
            }

        }
    }
}

Console Output

On what day should the cleaning be scheduled ? 
Thursday
Invalid, You have to choose one of these days: 
Monday
Invalid, You have to choose one of these days: 
Tuesday
Invalid, You have to choose one of these days: 
Wednesday
Cleaning scheduled for Thursday
Invalid, You have to choose one of these days: 
Friday
Invalid, You have to choose one of these days: 
Saturday
Invalid, You have to choose one of these days: 
Sunday
On what day should the cleaning be scheduled ? 
1
  • Please include the error. Commented Sep 2, 2015 at 22:12

6 Answers 6

1

A very simple approach would be to add another variable:

String savedVar = ""; 
....
if (days[i].equals(schedule)) {
            savedVar = schedule; //save your user input here
            System.out.println("Cleaning scheduled for " + schedule);

        } else {
            System.out.println("Invalid, You have to choose one of these days: \n " + days[i]);
        }

Then used the savedVar later on in your code.

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

Comments

1

When checking if any of the days match, you are checking if it matches day[i] and printing out the result immediately (before you've even checked the rest of the array for matches).

One possible solution is to track whether or not the user input has matched a day with a boolean. Try something like this:

public static void main(String[] args) {
        Scanner scr = new Scanner(System.in);
        String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

        int i = 0;

        boolean validEntry;
        while (true) {

            validEntry = false;
            System.out.println("On what day should the cleaning be scheduled ? ");
            String schedule = scr.nextLine();

            for (i = 0; i < days.length; i++) {

                if (days[i].equals(schedule)) {
                    System.out.println("Cleaning scheduled for " + schedule);
                    validEntry = true;
                }
            }

            if (!validEntry) {
                System.out.println("Invalid, You have to choose one of these days: \n" + Arrays.toString(days));
            }
        }
    }

Notice that I also changed

System.out.println("Invalid, You have to choose one of these days: \n" + days[i]);

to this

System.out.println("Invalid, You have to choose one of these days: \n " + Arrays.toString(days));

Comments

1

I think the logic error is that you are printing the response as you loop through your array so it is always going to print out "Invalid..." at least six times.

Instead, you could loop through your array until you find a match and then print a response depending on whether a match was found:

        boolean scheduleIsValid = false;
        for (i = 0; i < days.length; i++) {
            if (days[i].equals(schedule)) {
                scheduleIsValid = true;
                break; // Leave the for loop, we've already found what we were looking for.
            }
        }

        if (scheduleIsValid) {
            System.out.println("Cleaning scheduled for " + schedule);
            break; // Leave the while loop.
        } else {
            System.out.println("Invalid, You have to choose one of these days: \n " + days);
        }

2 Comments

if u just print "days", it is going to print the memory address.
@PedroMagalhaes Haha, yeah to be honest I just got lazy when I got to that part, the logic is what I was trying to get across.
1

Java Arrays utility is your way to go. Instead of looping manually, you can make ArrayList out of your array and use IndexOf to find your day.

List listOfDays = Arrays.asList(days);
int dayIndex = listOfDays.IndexOf(schedule);

if (dayIndex >= 0)
{
    System.out.println("Cleaning scheduled for " + listOfDays[dayIndex]);
}
else
{
    System.out.println("Invalid " + schedule); // Perform error handling as you wish
}

Sources:

http://www.tutorialspoint.com/java/util/arrays_aslist.htm

http://www.tutorialspoint.com/java/util/arraylist_indexof.htm

Comments

1

Try this:

import java.util.Arrays;
import java.util.Scanner;

public class ArrayLoopTest {
    public static void main(String[] args) {
        Scanner scr = new Scanner(System.in);
        String[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };

        int i = 0;
        while (true) {
            System.out.println("On what day should the cleaning be scheduled ? ");
            String schedule = scr.nextLine();

            for (i = 0; i < days.length; i++) {

                if (days[i].equals(schedule)) {

                    System.out.println("Cleaning scheduled for " + schedule);
                    break;
                }
            }

            if (i == days.length){
                System.out.println("Invalid, You have to choose one of these days: \n " + Arrays.asList(days));             
            }

        }
    }
}

If you are worried about performance , u can use a HashSet. If u dont know how to use just send a message and i post the solution.

1 Comment

This does not compile as is. If you post an answer dependent on imports, please include said imports in your code.
1

Please note there are more effective and easier ways to get an array element from a loop, but this is a simple way which should be easy to follow for beginners.

You have a for loop which is great, but you are printing out text to the user before you check the entire array to see if the user input matched any value in the array. What I did was made a boolean called dayIsValid which checks to see if the String the user inputted was a valid day. If the day was valid, then it prints out the desired message. Please note that this message only gets printed after I look through the Entire array.

Another thing I noticed, was that you are trying to print all the days in the String array and were only printing out one day. To fix this I looped through the String array, printing out the values. Hopefully this explanation helped you. If you have any questions please feel free to comment below

Scanner scr = new Scanner(System.in);
String[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
boolean continueLooping = true;
//be aware that this while loop will execute infinitely, unless you change continuelooping to false inside the while loop
while (continueLooping) {
    System.out.println("On what day should the cleaning be scheduled ? ");
    String dayScheduledForCleaning = scr.next();
    boolean dayIsValid = false;
    for (int i = 0; i < days.length; i++) {
        if (days[i].equalsIgnoreCase(dayScheduledForCleaning)) {
            System.out.println("Cleaning scheduled for " + dayScheduledForCleaning);
            dayIsValid = true;
            break;
        }
    }
    if(! dayIsValid) {
        System.out.println("Invalid, You have to choose one of these days:");
        for(int i = 0; i < days.length; i++)
            System.out.println(days[i]);
    }
}

Comments

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.