如何在"if"或"else"语句之后收集信息

0 java if-statement

我正在尝试收集关于他们在约会方面有多远的几个月的信息.

我首先让用户输入他们想要使用的月份.

Scanner uMonth = new Scanner(System.in);

String tMonth = uMonth.next();
    if (tMonth.equals("January")){
        int eMonth = 1;
    }else if (tMonth.equals("February")){
        int eMonth = 2;
    }else if (tMonth.equals("March")){
        int eMonth = 3;
    }else if (tMonth.equals("April")){
        int eMonth = 4;
    }else if (tMonth.equals("May")){
        int eMonth = 5;
    }else if (tMonth.equals("June")){
        int eMonth = 6;
    }else if (tMonth.equals("July")){
        int eMonth = 7;
    }else if (tMonth.equals("August")){
        int eMonth = 8;
    }else if (tMonth.equals("September")){
        int eMonth = 9;
    }else if (tMonth.equals("October")){
        int eMonth = 10;
    }else if (tMonth.equals("November")){
        int eMonth = 11;
    }else if (tMonth.equals("December")){
        int eMonth = 12;
Run Code Online (Sandbox Code Playgroud)

然后相同的第二个日期,除了我使用新的扫描仪并使用tMonth2和uMonth2作为下一个变量.

当我尝试在循环之外使用eMonth变量时,我的问题出现了.

int finalMonths = int(eMonth - eMonth2);{
if (finalMonths < 0);
finalMonths = (eMonth2 - eMonth);
Run Code Online (Sandbox Code Playgroud)

有什么我想念的吗?我不能在循环中使用变量吗?我缺少一些额外的步骤吗?

谢谢.

Zby*_*000 5

该变量仅在声明它的块中有效.因此,您必须将变量移动到外部作用域,以便从设置部分和计算部分访问它:

int eMonth; // variable declaration in the outer scope
...
String tMonth = uMonth.next();
if (tMonth.equals("January")){
    eMonth = 1; // only assignment, not declaration
}
...
int finalMonths = int(eMonth - eMonth2);
...
Run Code Online (Sandbox Code Playgroud)