繁体   English   中英

如何让我的代码不同时执行这两个语句?

[英]How do I make my code not execute both statements at once?

package homework;

import java.util.Scanner;

public class PA3b {

    static final int ARIES_START_DAY = 21;
    static final int ARIES_END_DAY = 19;
    static final int ARIES_START_MONTH = 3;
    static final int ARIES_END_MONTH = 4;
    
    public static void main(String[] args) {

        // Input
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your birth month (1-12): ");
        int month = scanner.nextInt();
        System.out.print("Enter your birth day (1-31): ");
        int day = scanner.nextInt();
        scanner.close();
        
        // Process
        
        String sign;
        
        if (month < 1 || month > 12) {
            System.out.println("Please enter a valid month number between (1-12)."); 
        }
        else if (day > 31 || day < 1 ) {
            System.out.println("Please enter a valid day number between (1-31)."); 
            System.exit(0); 
        }
        
        if (month==ARIES_START_MONTH && day >= ARIES_START_DAY || 
                         month==ARIES_END_MONTH && day <= ARIES_END_DAY) {
            sign = "Aries!"; 
        }
        else {
            sign = "Test";
        }

        // Output
        System.out.print("You are a " + sign);
    }
}

这是我的代码(尚未完成,但仅用于测试)但基本上我希望它适用于所有十二生肖,但问题是当我输入例如 13 个月的值时,我希望它说它无效月值,但是当我输入时它会说“你是白羊座”和“检查你的值是否正确”那么我该如何防止这种情况?

以下更改应该可以解决您的问题:

    if (month < 1 || month > 12) {
        System.out.println("Please enter a valid month number between (1-12)."); }
    else if (day > 31 || day < 1 ) {
        System.out.println("Please enter a valid day number between (1-31)."); 
    }else
    {
    if (month==ARIES_START_MONTH && day >= ARIES_START_DAY || month==ARIES_END_MONTH && day <= ARIES_END_DAY) 
        sign = "Aries!"; 
    
    else 
        sign = "Test";

    // Output
    System.out.print("You are a " +sign);
    }

仅当前两个值不为真时,最终条件才会得到解决。

仅仅因为用户输入了无效的月份值并不意味着程序流将自动停止。 您需要告诉它在满足条件的同一个if块内停止,否则代码将继续前进到下一个可运行代码行。 最好在提示时捕获(验证)输入,以便用户可以输入正确的值,而不是仅仅结束应用程序。

这是一个例子:

if (month < 1 || month > 12) {
    System.out.println("Please enter a valid month number between (1-12)."); 

    /* Exit the method you are in. If this is the 
       main() method then the application will end.     */
    return;
}

看起来会有很多常量:

ARIES_START_MONTH
ARIES_END_MONTH
ARIES_START_DAY
ARIES_END_DAY

我明白了,这是一个测试,我不确定你的总体计划是什么,但是,你确定要处理 48 个常量和可能的一堆if/else if语句吗? 你当然可以这样做,但我认为更好的方法是使用 Zodiac class,或二维字符串数组,或字符串列表接口,或除了 48 个常量和可能的一堆if/else if语句之外的任何东西。

以下可运行代码是您可以尝试的概念。 它演示了一种通过输入错误重试执行控制台提示的方法。 每个提示还包含退出当前程序流或完全退出应用程序的功能(取决于您运行代码的位置),并且每个提示都包含条目验证:

public class ZodiacDemo {

    /* The appropriate System newline character sequence.
       Not all systems use the same newline. Some use "\n" 
       and some use "\r\n".              */
    private final String LS = System.lineSeparator();
    
    /* Open a keyboard input stream. There is no need 
       to close this resource. The JVM will take care 
       of that when the appliaction closes.       */
    private final java.util.Scanner userInput = new java.util.Scanner(System.in);
    
    
    public static void main(String[] args) {
        // Started this way to avoid the need for statics.
        new ZodiacDemo().startApp(args);
    }
    
    private void startApp(String[] args) {
        // Prompt for Month value:
        String month = "";
        while (month.isEmpty()) {
            System.out.print("Enter your birth month (1-12 or q to quit): ");
            month = userInput.nextLine();
            
            // Has quit been requested?
            if (month.equalsIgnoreCase("q")) {
                /* Yes...Exit this method which will ultimately
                   close the application.                   */
                return;
            }

            // Validates Month Range (1-12). Also accepts 01-09. 
            if (!month.matches("^(1[0-2]|0?[1-9])$")) {
                System.out.println("Invalid month (" + month + ") entry! Try again..." + LS);
                month = "";  // Empty variable so as to re-prompt.
            }
        }

        // Make sure month is padded with leading "0" (ex: "01").
        month = String.format("%02d", Integer.parseInt(month));

        // Prompt for Day of month value:
        String day = "";
        while (day.isEmpty()) {
            System.out.print("Enter your birth day (1-31 or q to quit): ");
            day = userInput.nextLine();
            
            // Has quit been requested?
            if (day.equalsIgnoreCase("q")) {
                /* Yes...Exit this method which will ultimately
                   close the application.                   */
                return;
            }

            /* Validates Day Range 1-31. Also accepts 01-09. The number of 
               actual days in the month (povided in previous prompt) is also 
               checked against the month `day` entered. If the day entered is 
               beyond the actual number of days in the month supplied then 
               the input is considered Invalid. example: Month: 11,  Day: 31 
               is invalid since there are only 30 days in November.        */
            if (!day.matches("^(0?[1-9]|[12][0-9]|3[01])$")
                    || Integer.parseInt(day) > java.time.Month.of(Integer.parseInt(month)).length(true)) {
                System.out.println("Invalid day (" + day + ") entry! Try again..." + LS);
                day = "";  // Empty variable so as to re-prompt.
            }
        }

        // Make sure day is padded with leading "0" (ex: "01").
        day = String.format("%02d", Integer.parseInt(day));

        /* Get the Zodiac sign from the `getSign()` method the
           print it in the Console Window.                 */
        System.out.println("You are a " + getSign(month, day));
        // <Done>
    }
    
    public String getSign(String month, String day) {
        /* 2000 is just an arbitrary year that is used merely
           because it was simple to enter and it's a leap year
           for days in month validation. Besides, lots of people 
           are born on Feb. 29th.       */
        final String[][] zodiac = {
                {"Aquarius",    "2000-01-20", "2000-02-18"},
                {"Pisces",      "2000-02-19", "2000-03-20"},
                {"Aries",       "2000-03-21", "2000-04-19"},
                {"Taurus",      "2000-04-20", "2000-05-20"},
                {"Gemini",      "2000-05-21", "2000-06-20"},
                {"Cancer",      "2000-06-21", "2000-07-22"},
                {"Leo",         "2000-07-23", "2000-08-22"},
                {"Virgo",       "2000-08-23", "2000-09-22"},
                {"Libra",       "2000-09-23", "2000-10-22"},
                {"Scorpio",     "2000-10-23", "2000-11-21"},
                {"Sagittarius", "2000-11-22", "2000-12-21"},
                {"Capricorn",   "2000-12-22", "2000-01-19"}
            };
        
        /* Iterate through the zodiac[][] Array and 
           retrieve the appropriate sign based on the 
           supplied Month and Day.        */
        String sgn = "Unknown";
        for (String[] array : zodiac) {
            sgn = array[0];
            java.time.LocalDate sDate = java.time.LocalDate.parse(array[1]);
            java.time.LocalDate eDate = java.time.LocalDate.parse(array[2]);
            java.time.LocalDate userDate = java.time.LocalDate.parse("2000-" + month + "-" + day);
            if ((userDate.isEqual(sDate) || userDate.isEqual(eDate))
                    || (userDate.isAfter(sDate) && userDate.isBefore(eDate))) {
                break; // Get out of loop - we have what we need.
            }
        }
        return sgn;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM