在switch语句中将值从一个case传递到另一个case [英] Passing a value from one case to another in switch statement
问题描述
所以这是一个示例代码:
So here is a sample code :
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
System.out.println("Please type in a number");
Scanner in = new Scanner(System.in);
switch (in.nextInt()){
case 1:
save(in);
break;
case 2:
System.out.println(value);
break;
default:
System.out.println("Default case");
break;
}
in.close();
}
public static String save(Scanner in){
System.out.println("Type in a word");
String value = in.next();
return value;
}
}
在这种特殊情况下我想在这里做的一切是访问存储在案例1中的值
。
In this particular situation all I am trying to do here is to have access to the value
that was stored in case 1.
推荐答案
切换
所有类似c语言的语句,包括java都非常通用。它根据switch变量的值跳转到标签,然后继续,直到出现 break
语句。
switch
statement in all c-like languages including java is very general. It jumps to label according to the value of switch variable and then continues until break
statement appears.
我不是确定你在长篇解释中的意思如下:
I am not sure what did you meant in your long explanation but in following example:
switch(op) {
case ONE:
foo();
case TWO:
bar();
break;
case THREE:
aaa();
qqq();
break;
}
op == ONE
将调用第一个方法 foo()
,然后流将到达 TWO
的块,因为没有break语句是用 ONE
编写,所以将调用 bar()
。但是,break语句会将流程跳转到切换后出现的代码。
op == ONE
first method foo()
will be called, then the flow will arrive to block of TWO
because no break statement was written in ONE
, so bar()
will be called. However then the break statement will jump the flow to code that appears just after the switch.
这是一个简短的解释。有关详细信息,请查找好的书籍或教程,并阅读有关switch语句的章节。
This is a short explanation. For more details find a good book or tutorial and read chapter about switch statement.
这篇关于在switch语句中将值从一个case传递到另一个case的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!