Java之break和continue的区别

break和continue的区别

(1) 初步理解
break:  跳出循环.
continue: 跳出这一轮循环,进入下一轮循环.
Demo:

package com.example.firstTest;

public class myClass {
    public static void main(String[] args){
        System.out.println("Continue begin: ");
        for (int i = 0; i < 5; i++) {
            if (i == 3) {
                continue;
            }
            System.out.println("current i ="+i);
        }

        System.out.println("Break begin: ");
        for (int j = 0; j < 5; j++) {
            if(j == 3){
                break;
            }
            System.out.println("current j ="+j);
        }
    }
}

输出:
Continue begin:
current i =0
current i =1
current i =2
current i =4
Break begin:
current j =0
current j =1
current j =2
Process finished with exit code 0

(2)break 只是跳出一层switch 或者for 循环。实例如下:

class Solution {
public:
int romanToInt(string s) {
    int length = s.size();
    int result = 0;
    for (int j =0;j<length;j++) {
        string str;
        if (j<length-1) {
            str = string(1,s[j])+string(1,s[j+1]);
            cout<<"str ="<<str<<endl;
        }
        if (str == "IV") {
            cout<<"str == IV"<<endl;
            result+=4;
            j++;
        } else if (str == "IX") {
            result+=9;
            j++;
        } else if (str == "XL") {
            result+=40;
            j++;
        } else if (str == "XC") {
            result+=90;
            j++;
        } else if (str == "CD") {
            result+=400;
            j++;
        } else if (str == "CM") {
            result+=900;
            j++;
        }
        else {
            char chatStr = s[j];
            switch (chatStr){
                case 'I':
                    result+=1;
                    break; 
                case 'V':
                    result+=5;
                    break; 
                case 'X':
                    result+=10;
                    break; 
                case 'L':
                    result+=50;
                    break; 
                case 'C':
                    result+=100;
                    break;  // 这里的break 只是跳出switch ,不是跳出for循环
                case 'D':
                    result+=500;
                    break;  
                case 'M':
                    result+=1000;
                    break;  
                default:
                    cout<<"Not expected!"<<endl; 
                    break;
            }
        }
    }
    return result;
}
};


好久没有用continue,  今天居然模拟两可了,汗颜,赶紧写个demo压压惊.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值