public class PartArea1
{
public static void main(String[] args)
{
int a = 15;
int b = 2;
if(a == 15)
{
int a = 10;
double c = 2;//c是可用的
System.out.println(a + "/" + c + "=" + (a/c));
System.out.println("the value a is " + a);//a是可用的
}
//System.out.println("the value c is " + c);//在这里c已经不再可用
System.out.println(a + "/" + b + "=" + (a/b));
System.out.println(a + "%" + b + "=" + (a%b));
}
}
这段代码在编译的时候通不过,问题在于int a = 15;(a已经赋过值了),到后面再给局部变量a赋值为什么不行?请大家来解惑!
{
public static void main(String[] args)
{
int a = 15;
int b = 2;
if(a == 15)
{
int a = 10;
double c = 2;//c是可用的
System.out.println(a + "/" + c + "=" + (a/c));
System.out.println("the value a is " + a);//a是可用的
}
//System.out.println("the value c is " + c);//在这里c已经不再可用
System.out.println(a + "/" + b + "=" + (a/b));
System.out.println(a + "%" + b + "=" + (a%b));
}
}
这段代码在编译的时候通不过,问题在于int a = 15;(a已经赋过值了),到后面再给局部变量a赋值为什么不行?请大家来解惑!
{
public static void main(String[] args)
{
int a = 15;
int b = 2;
if(a == 15)
{
a = 10;
double c = 2;//c是可用的
System.out.println(a + "/" + c + "=" + (a/c));
System.out.println("the value a is " + a);//a是可用的
}
//System.out.println("the value c is " + c);//在这里c已经不再可用
System.out.println(a + "/" + b + "=" + (a/b));
System.out.println(a + "%" + b + "=" + (a%b));
}
}
int b = 2;
if(a == 15)
{
//错误在这里/////////////////////////////
int a = 10;//a重复定义
double c = 2;//c是可用的
System.out.println(a + "/" + c + "=" + (a/c));
System.out.println("the value a is " + a);//a是可用的
}
15/2.0=7.5
the value a is 15
15/2=7
15%2=1疑惑:
{
a = 10;
double c = 2;//c是可用的
System.out.println(a + "/" + c + "=" + (a/c));
System.out.println("the value a is " + a);//a是可用的
}
在这段代码中为什么a还是15?难道不应该为10吗?不是有个就近原则吗?局部变量优先级不是大于全局的吗?