Is there a way to assign a user input string to an int value?

262 Views Asked by At

`Im still learning and I sort of feel like Im doing this all wrong, but I could use some help. I have an assignment needs to have the user set a day of the week, then the program will make the user select an option that will either return the day, return the next day, return the previous day, or add certain days to the day they set(ex: If set the day as Monday and add 4 days, then it will return Friday). I really only need help with the adding days part but any advice on how to make the code better is appreciated.


Im wanting to know if I can assign a int value to a string. For example, if String day equals "Sunday", then int a = 1. I want to assign each day of the week to an int value, then add whatever number the user inputs to the int value, then the sum would be the new day.


If theres a better way to do this please let me know, heres my code(sorry if it looks bad).

import java.util.Scanner;
public class Main
{
public static void main(String\[\] args)
{

        Day.userInput();
    }

}

class Day
{
static int b;
public static void userInput()
{
Scanner scan = new Scanner(System.in);

// set day of week
System.out.println("Please set the day of the week:");
String day = scan.nextLine();

        if(day.equals("sunday") || (day.equals("Sunday")) )
        {
          b = 1;
        }
        if(day.equals("monday") || (day.equals("Monday")) )
        {
            b = 2;
        }
        if(day.equals("tuesday") || (day.equals("Tuesday")) )
        {
            b = 3;
        }
        if(day.equals("wednesday") || (day.equals("Wednesday")) )
        {
            b = 4;
        }
        if(day.equals("thursday") || (day.equals("Thursday")) )
        {
            b = 5;
        }
        if(day.equals("friday") || (day.equals("Friday")) )
        {
            b = 6;
        }
        if(day.equals("saturday") || (day.equals("Saturday")) )
        {
            b = 7;
        }
    
    
        System.out.println("Enter 1 to return the day.\nEnter 2 to return tomorrows day.\nEnter 3 to return yesterdays day.\nEnter 4 to add days to the current day.\n");
        int a = scan.nextInt();

// return day
if(a == 1)
{
System.out.println("The day is " + day);
}
//return next day
if(a == 2)
{
if ( b == 1)
{
System.out.println("The next day is Monday.");
}
if (b == 2)
{
System.out.println("The next day is Tuesday.");
}
if (b == 3)
{
System.out.println("The next day is Wednesday.");
}
if (b == 4)
{
System.out.println("The next day is Thursday.");
}
if (b == 5)
{
System.out.println("The next day is Friday.");
}
if (b == 6)
{
System.out.println("The next day is Saturday.");
}
if (b == 7)
{
System.out.println("The next day is Sunday.");
}

        }

//return previous day
if(a == 3)
{
if( b == 1)
{
System.out.println("The previous day was Saturday.");
}
if (b == 2)
{
System.out.println("The previous day was Sunday.");
}
if (b == 3)
{
System.out.println("The previous day was Monday.");
}
if (b == 4)
{
System.out.println("The previous day was Tuesday.");
}
if (b == 5)
{
System.out.println("The previous day was Wednesday.");
}
if (b == 6)
{
System.out.println("The previous day was Thursday.");
}
if (b == 7)
{
System.out.println("The previous day was Friday.");
}
}
// add days  
if(a == 4 )
{
System.out.println("Enter the number of days you want to add");
int c = scan.nextInt();

        }
    
    
    }

}

I know a way I can do this but it'll take a massive amount of lines and if statements. `

5

There are 5 best solutions below

0
Unmitigated On

You can create a List of days in order, then use indexOf after converting the input String to lowercase.

List<String> days = List.of("sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday");
// convert day to index:
int b = days.indexOf(day.toLowerCase()) + 1;

// convert index to day:
String day = days.get(a - 1);
// capitalize it:
day = Character.toUpperCase(day.charAt(0)) + day.substring(1);
0
Mario Mateaș On

While the above answer is clear and accurate, you could also use an enum containing all days of the week, mostly in case you also want to add more functionality to them.

enum DayOfWeek {
    MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6), SUNDAY(7);

    private final int value;

    private DayOfWeek(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }

    public DayOfWeek getPreviousDay() {
        if (value == 1) return DayOfWeek.SUNDAY;
        if (value == 2) return DayOfWeek.MONDAY;
        // Insert other checks here
    }

    public DayOfWeek getNextDay() {
        if (value == 7) return DayOfWeek.MONDAY;
        // Insert other checks here
    }
}

... while the user input part can look like this:

Scanner scan = new Scanner(System.in);

System.out.println("Please set the day of the week:");
String day = scan.nextLine();

DayOfWeek dayOfWeek = DayOfWeek.valueOf(day);

Of course, in this case, if the user inputs the correct value, but with wrong capitalization (e.g. mondaY or Monday), it will throw an Exception. User should type in MONDAY, as specified in DayOfWeek. You could convert day to uppercase pretty easy by just adding:

DayOfWeek dayOfWeek = DayOfWeek.valueOf(day.toUpperCase());
0
Milo On

import java.util.Scanner;

public class DayOfWeek { public static void main(String[] args) { String[] daysOfWeek = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

    // Ask the user to input a day of the week
    Scanner input = new Scanner(System.in);
    System.out.print("Please enter a day of the week: ");
    String day = input.nextLine();

    // Check if the input day is valid
    boolean validDay = false;
    for (String d : daysOfWeek) {
        if (d.equalsIgnoreCase(day)) {
            validDay = true;
            break;
        }
    }
    if (!validDay) {
        System.out.println("Invalid input. Please enter a valid day of the week.");
    } else {
        // Ask the user to select an option
        System.out.println("Please select an option:");
        System.out.println("1. Return the day");
        System.out.println("2. Return the next day");
        System.out.println("3. Return the previous day");
        System.out.println("4. Add certain days to the day you set");
        System.out.print("Option: ");
        int option = input.nextInt();

        if (option == 1) {
            System.out.println("The day is " + day);
        } else if (option == 2) {
            int index = -1;
            for (int i = 0; i < daysOfWeek.length; i++) {
                if (daysOfWeek[i].equalsIgnoreCase(day)) {
                    index = i;
                    break;
                }
            }
            String nextDay = daysOfWeek[(index + 1) % 7];
            System.out.println("The next day is " + nextDay);
        } else if (option == 3) {
            int index = -1;
            for (int i = 0; i < daysOfWeek.length; i++) {
                if (daysOfWeek[i].equalsIgnoreCase(day)) {
                    index = i;
                    break;
                }
            }
            String prevDay = daysOfWeek[(index - 1 + 7) % 7];
            System.out.println("The previous day is " + prevDay);
        } else if (option == 4) {
            System.out.print("Enter the number of days to add: ");
            int numDays = input.nextInt();
            int index = -1;
            for (int i = 0; i < daysOfWeek.length; i++) {
                if (daysOfWeek[i].equalsIgnoreCase(day)) {
                    index = i;
                    break;
                }
            }
            String newDay = daysOfWeek[(index + numDays) % 7];
            System.out.println("The new day is " + newDay);
        } else {
            System.out.println("Invalid option. Please select a valid option.");
        }
    }
}

}

0
zamwon On

You can also use Map<String, Integer> where key is String like "Monday" etc, and an Integer as your value that should be associated with it.

Then you can call for exact value by calling map.get(scanner.nextLine()).

Later on focus on cleaning up the if-'ish' approach - get acquainted with switch.

Final step would be to extract functionalities to separate methods: one for retrieving day, then second for logic to deal with further processing, and last but not least for example the returning value method.

0
Reilas On

I adapted your code, utilizing an enum as the main reference point for your day values.

int d;

void userInput() {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Please enter a day of the week: ");
    String day = scanner.nextLine();
    Day value;
    try {
        value = Day.valueOf(day.toUpperCase());
        d = value.ordinal() + 1;
    } catch (IllegalArgumentException exception) {
        System.out.printf("Invalid input, '%s'%n", day);
        return;
    }

    System.out.println("Enter 1 to return the day.\nEnter 2 to return tomorrows day.\nEnter 3 to return yesterdays day.\nEnter 4 to add days to the current day.\n");
    switch (scanner.nextInt()) {
        case 1 -> System.out.println(value);
        case 2 -> System.out.println(value.next());
        case 3 -> System.out.println(value.previous());
        case 4 -> {
            System.out.println("Enter the number of days you want to add");
            int c = scanner.nextInt();
            while (c-- > 0)
                value = value.next();
            System.out.println(value);
        }
    }
}

enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;

    Day next() {
        if (this == SATURDAY) return SUNDAY;
        return values()[ordinal() + 1];
    }

    Day previous() {
        if (this == SUNDAY) return SATURDAY;
        return values()[ordinal() - 1];
    }
}

Output.

Please enter a day of the week: saturday
Enter 1 to return the day.
Enter 2 to return tomorrows day.
Enter 3 to return yesterdays day.
Enter 4 to add days to the current day.

4
Enter the number of days you want to add
6
FRIDAY