String value for integer?

Firstly, I am a beginner programmer and have only about 7 weeks of programming experience. Secondly, this is for homework. This is where I am stuck.

String curDay;
String curDaylow;
int sunday;
int monday;
int tuesday;
int wednesday;
int thursday;
int friday;
int saturday;
sunday = 0;
monday = 1;
tuesday = 2;
wednesday = 3;
thursday = 4;
friday = 5;
saturday = 6;
int dayNum;

curDay = console.next();
curDaylow = curDay.toLowerCase();
dayNum = valueOf.curDaylow;

What I'm trying to do is get the dayNum variable equal to the value of the string. Example. if the user enters Monday, the program reduces it to the entire lower region on Monday, and then dayNum should = 1. I already have Sun-Sat declared as an INT value, and each of them starts with SUN = 0 and moves along the line to SAT = 6.

Since this is homework, I do not expect anyone to do it for me, but it may push me to where I can learn it. Or maybe tell me what this operation will be called, so I know to research it. Thanks.

+4
3
enum Day {
    sunday(0),monday(1),tuesday(2),wednesday(3),thursday(4),
    friday(5),saturday(6);

    private final int value;

    Day(int value) {
        this.value = value;
    }

    int getValue() {
        return value;
    }
}

:

Day m = Day.valueOf(curDay.toLowerCase());
int dayNum = m.getValue();
+2

, .

-, . , , "dayNum ", "dayNum should = 1" - 1 " ". , , . .

, , Java. , . int monday, - "". Java . , int monday , , - .

, , , , , , .

- , ():

String[] days = new String[] { 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday' }

- curDay = console.next().trim().toLowerCase() - , , , , :

int dayNum = -1;
for(int i=0; i<days.length; i++) {
    if(days[i].equals(curDay) {
        dayNum = i;
        break;
    }
}

, , , , , , ( - Map), ):

Map<String, Integer> daysOfWeek = new HashMap<String, Integer>();
daysOfWeek.put("sunday", 0);
...
daysOfWeek.put("saturday", 6);

String curDay = console.next().trim().toLowerCase();
int dayNum = daysOfWeek.get(curDay); // Will throw null-pointer exception if value of curDay is not in the map.

Java API - java.util.Calendar ( java.text.DateFormatSymbols) - . . , : Java, (Sun, Mon,..., Sat) Locale ()

+2

, , , int , , ... , . . , , java 1.7, , , case "sunday": dayNum = 0; break; . , .

int dayNum;
    String curDay;
    String curDaylow;
    curDay = console.next();
    curDaylow = curDay.toLowerCase();
    switch (curDaylow) {
    case "sunday":
        dayNum = 0;
        break;
    case "monday":
        dayNum = 1;
        break;
    // Similarly write all cases for remaining days
    }
0

Source: https://habr.com/ru/post/1626460/


All Articles