作者LaPass (LaPass)
看板java
标题Re: [问题] 面试遇到的JAVA问题
时间Sat Nov 12 21:49:14 2011
1F:→ wemee:有没有什麽范例可显示出原例与x,y在同一区块中初始化的差别11/12 11:05
public class Test
{
public static void main(String[] args) {
int a = 1;
{
int b = 2;
System.out.println(a); //OK
}
//System.out.println(b); //编译错误
Lable1:{
if(a==1) break Lable1; //跳离区块
}
}
}
很多程式语言都能够直接打个未标记的{}而不会出现错误
在JAVA中,我觉得有需要直接给括弧的状况,也只有给他一个标签(Lable)
然後用break直接跳离那个区块而已
离开括弧,在括弧中宣告的变数会被注销,但这也没什麽用途
我实在搞不懂直接用括弧刮起来能干什麽
像范例那个,好像完全没必要
※ 引述《qrtt1 (我要越级挑战)》之铭言:
: ※ 引述《wemee (我不为读者改变作风)》之铭言:
: : 有一些题目 类似以下用法
: : 但我完全不知道这麽用的意义是什麽
: : 例如
: : class Foo
: : {
: : {
: : x = 1;
: : {
: : y = 2;
: : }
: : }
: : int x, y;
: : }
: : 分成区块中的区块 有什麽意义吗?
: : 通常不是这麽写就好了
: : {
: : x = 1;
: : y = 2;
: : }
: : 难道只是要先吓吓人而已
: 写个小例子跑看看呗。
: public class Init {
: static {
: System.out.println("class init.");
: }
: {
: System.out.println("instance init. 1");
: x = 1;
: {
: System.out.println("instance init. 2");
: y = 2;
: }
: }
: int x, y;
: public Init() {
: System.out.println("ctor");
: }
: {
: System.out.println("instance init. 3");
: }
: public static void main(String[] args) {
: new Init();
: }
: }
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 125.233.155.87