I want to make Java count from one input integer to another, printing weekdays

本小妞迷上赌 提交于 2020-12-15 03:33:56

问题


So first off, I'm completely brand new to Java and I know this is probably really easy for most of you. But right now I'm stuck with an exercise. I have googled almost frantically, but I can't find any helpful tips to this particular problem. That or I don't really know what to search for.

I have a piece of code that looks like this:

import java.util.Scanner;

public class Week {

public static void main(String[] args) { Scanner input = new Scanner(System.in);

System.out.println("Type a number: ");
int day = input.nextInt();

if (day == 1) {
  System.out.println("Monday ");
}
if (day == 2) {
  System.out.println("Tuesday ");
}
if (day == 3) {
  System.out.println("Wednesday ");
}
if (day == 4) {
  System.out.println("Thursday ");
}
if (day == 5) {
  System.out.println("Friday ");
}
if (day == 6) {
  System.out.println("Saturday ");
}
if (day == 7) {
  System.out.println("Sunday");
}

} }

As all you can probably see, this program prompts the user to type a number, and if that number is somewhere between 1-7 the program will answer with the corresponding day of the week. What I would like to do now however, is to modify the code to start a counter or loop or something. I want to make it count +1 from my input number to a specified break. Let's say I type 2, and the program would print: Tuesday, Wednesday, Thursday, Friday and then make it stop.

I have only really dipped my toe in for, while, if statements etc but I know that somewhere there is the key. While playing around I only succeeded in making the program print 2 five times, or letting me type numbers for infinity.

Any help would be greatly appreciated!


回答1:


Since you are currently learning, I'll point you some leads to brighten the path to follow instead of giving the answer.

First of all to solve a problem, you have to clearly define what it is. We will assume that numbers bellow 1 or higher than 7 are not in scope. I understand that you need to enter two numbers : the starting day and the end day. You already know how to store the first one. The second one is the same process. But there is a catch. Scanner.nextInt() consumes the number entered in the console but not the you do to validate the value. You have to find how to consume that between the two nextInt() calls.

Then loops. A loop shall be :

  1. an initialization : what is the state of the program when the loops begin (use the start day value since it is the first thing to display)
  2. a condition to loop : when does the loop stops ? (use the end day value maybe +1 since it is the last one to display)
  3. an evolution instruction : every time the loop is performed something shall progress to make your program state go closer and closer to the end loop condition (+1 every loop since you want all days between start and end)

Go further :

  • I advise you to look at switch cases to avoid chained if statements that perform a discrimination on a given set of values on one variable
  • Later, you could look at enums. It is a way to store finite states and week Days clearly is one good exemple to learn them. (of cours they already exist -> https://kodejava.org/how-do-i-use-the-java-time-dayofweek-enum/)



回答2:


public class Week {

    public static void main(String[] args) { Scanner input = new Scanner(System.in);

        System.out.println("Type a number: ");
        int day = input.nextInt();
        
        System.out.println("Type a stop number: ");
        int stopDay = input.nextInt();

        for (int i = day; i <= stopDay; i++) {      // if the stopday should be printed, then use '<=', '<' otherwise
            printWeekDay(i);
        }
    }
    
    private static void printWeekDay(int day) {
        if (day == 1) {
            System.out.println("Monday ");
        }
        if (day == 2) {
            System.out.println("Tuesday ");
        }
        if (day == 3) {
            System.out.println("Wednesday ");
        }
        if (day == 4) {
            System.out.println("Thursday ");
        }
        if (day == 5) {
            System.out.println("Friday ");
        }
        if (day == 6) {
            System.out.println("Saturday ");
        }
        if (day == 7) {
            System.out.println("Sunday");
        }
    }
}



回答3:


You could just create an array of DAYS[] and iterate through the array from that particular index towards the end.

String DAYS[] = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};

System.out.println("Type a number: ");
int day = input.nextInt();

if(day >= 1 && day <= 7) {
  for(int i = day - 1; i < DAYS.length; i++) {
      System.out.println(DAYS[i]);
   }
}
else
   System.out.println("Enter a valid number");

The logic would be the same if you want to stop by taking in the stop index. Just replace the DAYS.length in the for loop with your desired stop index




回答4:


I would do it using switch-case in which when I want the program to print a specific day, I would use break which break the switch-case block after executing the matching case. If break is not used in a case, the execution falls through the remaining cases until a break is found or where the block ends.

In order to continue doing it repeatedly, I would use an infinite loop (while(true) { }) which can be broken using break statement as per the business logic.

Note that I have also used Integer.parseInt(input.nextLine()) instead of input.nextint() to avoid the problem described here.

Demo:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("+=+=+ Menu +=+=+");
        System.out.println("A. Show a specific day");
        System.out.println("B. Show all days starting from the specific day");
        System.out.println("C. Exit");
        String choice;
        while (true) {
            System.out.print("Enter your choice: ");
            choice = input.nextLine().toUpperCase();
            if ("C".equals(choice)) {
                System.out.println("Good bye!");
                break;
            }

            System.out.print("Type a number: ");
            int day = Integer.parseInt(input.nextLine());

            if ("A".equals(choice)) {
                switch (day) {
                case 1:
                    System.out.println("Monday ");
                    break;
                case 2:
                    System.out.println("Tuesday ");
                    break;
                case 3:
                    System.out.println("Wednesday ");
                    break;
                case 4:
                    System.out.println("Thursday ");
                    break;
                case 5:
                    System.out.println("Friday ");
                    break;
                case 6:
                    System.out.println("Saturday ");
                    break;
                case 7:
                    System.out.println("Sunday");
                    break;
                }
            } else if ("B".equals(choice)) {
                switch (day) {
                case 1:
                    System.out.println("Monday ");
                case 2:
                    System.out.println("Tuesday ");
                case 3:
                    System.out.println("Wednesday ");
                case 4:
                    System.out.println("Thursday ");
                case 5:
                    System.out.println("Friday ");
                case 6:
                    System.out.println("Saturday ");
                case 7:
                    System.out.println("Sunday");
                }
            }
        }
    }
}

A sample run:

+=+=+ Menu +=+=+
A. Show a specific day
B. Show all days starting from the specific day
C. Exit
Enter your choice: A
Type a number: 4
Thursday 
Enter your choice: B
Type a number: 4
Thursday 
Friday 
Saturday 
Sunday
Enter your choice: C
Good bye!


来源:https://stackoverflow.com/questions/64471001/i-want-to-make-java-count-from-one-input-integer-to-another-printing-weekdays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!