How to use if function to call array elements

Basically, I have a 'prime' variable. It can only take values ​​from 0 to 6. Based on its value, I want the string "result" to be Sunday if prime is 0, Monday if 1, and so on. It is currently encoded as follows:

String result = new String();

    if (prime == 0)
    {
        result = "Sunday";
    }

    if (prime == 1)
    {
        result = "Monday";
    }

    if (prime == 2)
    {
        result = "Tuesday";
    }

    if (prime == 3)
    {
        result = "Wednesday";
    }

    if (prime == 4)
    {
        result = "Thursday";
    }

    if (prime == 5)
    {
        result = "Friday";
    }

    if (prime == 6)
    {
        result = "Saturday";
    }

    else
    {
        result = "Check your code.";
    }

      

I am wondering if there is a faster way to do this? I created an array with the days of the week:

String[] days = new String[7];

    days [0] = "Sunday";
    days [1] = "Monday";
    days [2] = "Tuesday";
    days [3] = "Wednesday";
    days [4] = "Thursday";
    days [5] = "Friday";
    days [6] = "Saturday";

      

How to quickly and elegantly code it so that if prime is 0, the string "result" is the first element of the array, and so on until 6 is the result of the string as the seventh element?

+3


source to share


5 answers


You already have all the valid values ​​stored in a simple lookup table, you just need to make sure the requested value is within the range of available values.

The main answer would be to do something like ...

if (prime >= 0 && prime < days.length) { 
    result = days[prime]; 
} else {
    result = prime + " is not within a valid range";
    // Or throw an exception
}

      



This means the value prime

is in the valid range of valid values ​​( 0..days.length - 1

), otherwise it returns an error message (or you can throw an exception).

Remember that arrays are indexed 0

, so you need to use < days.length

(less than), not <= days.length

(less or equal)

+7


source


You were close. For those who say "Switch" or "circuit", it overwhelms the problem.

result = days[Math.abs(prime % days.length)];

      

The array acts like a switch statement, and the modulus statement enclosed in Math.abs

(absolute value) acts as a secure network to stay within the valid range of the array 0-6.



Credits to @MadProgrammer for Math.abs

From Point of Learning

Modulus - Divides the left operand with the right hand and returns the remainder

+5


source


Why don't you use a class DayOfWeek

?

import java.time.DayOfWeek;

      

and try this ...

try {
     DayOfWeek dayOfWeek = DayOfWeek.of(++prime);
     System.out.println(dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault()));
} catch (java.time.DateTimeException ex) {
     System.out.println("Invalid value for DayOfWeek");
}

      

Please note what we have to do ++prime

since your code starts at zero and is enumerated in one.

If you need to set Sunday as the first day (instead of Monday, which is the first in the enum) ... the method minus

will do the trick:

DayOfWeek dayOfWeek = DayOfWeek.of(++prime).minus(1);

      

EDIT: Advantages and Disadvantages of the Solution

Pros:

  • No facility required to sustain your days.

  • Don't use a conditional operator.

  • The style and language of the text can be easily changed.

Minuses:

  • requires java 1.8
+2


source


You can simply do:

if (prime >= 0 && prime < days.length) result = days[prime];
else result = "Check your code."

      

Because it prime

is essentially the index of the day you want.

+1


source


You can use Enum and define yourself

public enum Week {
    SUNDAY(1, "Sunday"), Monday(2, "Monday"), TUESDAY(3, "Tuesday"), WEDNESDAY(
            4, "Wednesday"), THURSDAY(6, "Thursday"), FRIDAY(6, "Friday"), SATURDAY(
            7, "Saturday");
    private int id;
    private String name;

    static Map<Integer, String> map = new HashMap<Integer, String>();
    static {
        for (Week w : Week.values()) {
            map.put(w.getId(), w.name);
        }
    }

    private Week(int id, String name) {
        this.setId(id);
        this.setName(name);
    }

    public static String getNameById(int id) {
        return map.get(id);
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }
}

      

0


source







All Articles