public class test{
public static void main(String[] args){
while(条件){
switch(变量){
case 1:
执行语句;
退出循环; \\这里怎么写, break是退出switch,但要退循环,要怎么退呢case 2:
执行语句;
退出循环;
}
}System.out.print("程序结束");}}程序满足case1或case2,要使程序退出while循环,用break肯定不行,用switch只能退出switch
用return的话,循环是退出来了,但是整个程序也结速了,运行不到
System.out.print("程序结束"); 这条语句目前想到的,只能用loop 标签的方法,没实践过,不知道行的通不
或者把循环放到方法里去。
大家有其它好的方法么?
public class Main {
public static void main(String[] args) {
int i = 1;
boolean flag = true;//设置变了控制循环
while(flag) {
switch(i) {
case 1:
System.out.println("i=" + 1);
break;
case 2:
System.out.println("i=" + 2);
break;
default:
System.out.println("other");
break;
}
flag = false;
}
System.out.println("程序结束了");
}
}
public class Main {
public static void main(String[] args) {
int i = 1;
boolean flag = true;//设置变了控制循环
while(flag) {
switch(i) {
case 1:
System.out.println("i=" + 1);
break;
case 2:
System.out.println("i=" + 2);
break;
default:
System.out.println("other");
break;
}
flag = false;
}
System.out.println("程序结束了");
}
}
while条件有自己的循环条件,不能用来设置flag这个条件
我想问下 你的switch 本来就只能处理一个传入值
你还要用while去循环什么?
boolean flag = false;
while (原条件 && flag) {
...
flag = true;
...
}或者在while前加标识,比如
loop: while(...) {
...
break loop;
...
}
如while(i<10)
要跳出循环case语句中加一个i=10不就行了
public static void main(String[] args) {
int i=1;
while(i<=10){
switch(i){
case 5:
break;
}
i++;
System.out.println(i);
}
System.out.println("程序结束了"); }
}循环条件i<=10
依次输出i的值,循环体,i++
当碰到i=5时,退出循环,当然实际中,不可能这样写,我只是举个例子.
输出
1
2
3
4程序结束了其实还类似的,比如for循环嵌套的话,当里面的第二层的循环结束时,要求跳出第一层循环. 道理是一样的.
loop: while (i <= 10) {
switch (i) {
case 5:
break loop;
}
i++;
System.out.println(i);
}
System.out.println("程序结束了");
这样就输出
2
3
4
5
public static void main(String[] args) {
int i=0;
Boolean flag = true;
while(i<=10&&flag==true){
switch(i){
case 5:
flag = false;
break;
}
i++;
System.out.println(i);
}
System.out.println("程序结束了");
}
}
只要输出
1
2
3
411楼的方法是可行的
我在前面说过,如果不用loop和方法,还有其他的办法可以做到不?
所谓的while()参数是个boolean值
是可以自己任意指定的,1<2-->true , 1>2 --> false
基础弄扎实吧
是每次循环时候 会做判断 , 相当于每次循环做一次if((i<=10)==true)
public class Test1 {
public static void main(String[] args) {
int i = 1;
flg1: while (i <= 10) {
switch (i) {
case 5:
break flg1;
}
System.out.println(i++); }
System.out.println("程序结束了"); }
}
在要跳出前的语句加个label标记一下就可以了嘛public class test{
public static void main(String[] args){
label1:
while(条件){
switch(变量){
case 1:
执行语句;
break label1;
退出循环; \\这里怎么写, break是退出switch,但要退循环,要怎么退呢case 2:
执行语句;
退出循环;
}
}System.out.print("程序结束");}}
int i = 1;
while(i<=10){
switch(i){
case 5:
break;
}
i++;
System.out.println(i);
if (i == 5){
break;
}
}
System.out.println("程序结束了");
}二:public static void main(String[] args) {
int i = 1;
loop: while (i <= 10) {
switch (i) {
case 5:
break loop;
}
System.out.println(i++);
}
System.out.println("程序结束了");
}
针对楼主的情况我个人觉得以上2种方法够了,我个人感觉以上2个办法都能对问题起到效果(虽然看似第一种方法很稀烂),如果有1000个情况,那么要case1000次,跟if(情况1 && 情况2 && ...)貌似也没多大区别吧, 要说这个,也是效率问题了。
那个 case 5 :
break; 格式没弄好。。
for(...)
{
for(...)
{
for(...)
{
if(..) break label;
}
}
}