在If语句中声明变量(Java)

时间:2017-12-22 01:51:59

标签: java variables if-statement

我试图编写一个程序,根据输入的月份和日期为您提供季节,但是在中途遇到问题。在if语句中初始化变量month后,要检查输入的值是否为有效月份,我不能在代码中使用变量月份来查找季节,因为它给出了错误“找不到符号”。任何帮助将不胜感激。

import java.util.Scanner;
public class Date 
{
    public static void main(String [] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Please enter the number of the month: ");
        if (in.hasNextInt() && in.nextInt() > 0 && in.nextInt() <= 12)
            {
            int month = in.nextInt();
            }
        else 
            {
                System.out.println("Error: Invlaid month value");
            }
        System.out.println("Please enter the day: ");
        int day = in.nextInt();

        String season;
        if (0 < month && month <= 3)
            {
                season = "Winter";
            }
        else if (3 < month && month <= 6)
            {
                season = "Spring";
            }
        else if (6 < month && month <= 9)
            {
                season = "Summer";
            }
        else if (9 < month && month <= 12)
            {
                season = "Fall";
            }

    }

}

1 个答案:

答案 0 :(得分:0)

您遇到的问题是您已在if语句中声明了变量,这意味着它只能在{}中访问。 This article goes over the basics of variable scope in Java。如果变量是在作为当前作用域子集的作用域中定义的,则只能从作用域访问变量。

要实现您想要的目标,您需要在if语句之外声明变量,以便可以访问它。请注意,当月份无效时,您将需要处理该情况,否则您将具有默认值0。

int month = 0;
if (in.hasNextInt()) {
    month = in.nextInt();

    if (!(month > 0 && month <= 12)) {
        month = 0;
        System.out.println("ERROR");
    }
} else {
    // Handle graceful exit
}

...
if (0 < month && month <= 3) { ... }
相关问题