为什么变量必须被初始化?

问题描述:

这里我试图通过输入月份数来获得输出月份,但为什么我有错误 - “月份字符串”可能没有被初始化? - 为什么我没有从“monthString”获取输出字符串?为什么变量必须被初始化?

为什么monthString必须被初始化?

import java.util.Scanner; 
public class SwitchClass { 

public static void main(String[]args) 
{ 
    Scanner input = new Scanner(System.in); 
    System.out.printf(" when did u born ? "); 
    int monthNumber = input.nextInt(); 
    String monthString ; 

switch (monthNumber) 
{ 
    case 1: 
    monthString = "January "; 
     break; 
    case 2: 
     monthString = "February "; 
     break; 
    case 3: 
     monthString = "March "; 
     break; 
    case 4: 
     monthString = "April "; 
     break; 
    case 5: 
     monthString = "May"; 
     break; 
    case 6: 
     monthString = "June"; 
     break; 
    case 7: 
     monthString = "July"; 
     break; 
    case 8: 
     monthString = "August"; 
     break; 
    case 9: 
     monthString = "September"; 
     break; 
    case 10: 
     monthString = "October"; 
     break; 
    case 11: 
     monthString = "November"; 
     break; 
    case 12: 
     monthString = "December"; 
     break; 
    } 
System.out.println(monthString);  } 

} 

如果monthNumber不在1和12之间怎么办?在这种情况下,monthString将不会被初始化。

String monthString = null; // or "" 
+4

或者创建一个默认开关的情况下,它给它一个值。 –

+0

有道理,明白了。谢谢 – tun

这将是一个默认的情况下添加到您的switch语句是一个好主意:当你把它声明你应该给它一些默认值。

例子:

switch (monthNumber) { 
    case 1: monthString = "January"; 
     break; 

    //other cases... 

    default: monthString = "Invalid Month Number"; 
     break; 
} 

这样,如果monthNumber不是那么1-12仍存在一个默认的情况下switch语句流向。

局部变量必须始终在使用前初始化。 对于Java 6,编译器不考虑流控制块和try-catch块内的变量的初始化“012不完整”“”。初始化必须对所有案件进行:

如果 - 否则

String s; 
int a = 10; 
if(a > 5){ 
s = "5"; 
}else{ 
System.out.println(""); 
}  
System.out.println(s); // error if s isn't initialized within both if and else blocks 

While循环

String s; 
int a = 10; 
while(a > 0) { 
    s= ">0"; 
    a--; 
}  
System.out.println(s);// error if s isn't initialized outside the while 

try-catch块

String s; 
try { 
s = ""; 
    } catch (Exception e) {} 
System.out.println(s);// error if s isn't initialized within both try and catch blocks 

开关块

String s; 
int a = 10; 
switch (a) { 
    case 10: 
     s="10"; 
     break; 
    default: 
     break; 
     } 
System.out.println(s);// error if s isn't initialized all cases, default case included 

开关之前初始化变量和所有将被罚款。

String monthString = ""; 
+2

这两个帐户都不正确。 –

+0

@ScottM。我认为在改进我的帖子后,我的想法已经很清楚了。 –

monthString是main()中的局部变量,因此,它必须被初始化以防止编译器错误。

如果monthString是一个类变量,那么它不必显式初始化。

您可以通过移动的主(monthString外做到这一点),并声明为:

静态字符串monthString;

可能是此链接将有助于得到正确的理解。

http://stackoverflow.com/questions/5478996/should-java-string-method-local-variables-be-initialized-to-null-or 

因为Java语言的设计者认为它更有意义!初始化变量时代码更容易阅读。String foo;声明感觉不确定,因为您必须猜测String的默认值是多少,而String foo = null;更具确定性。

为了给你一个更明显的例子,考虑一下:

int x; 
Int y; 

你能很快猜出的默认值?您可能需要暂停几秒钟以实现x可能为0,而y可能为空