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压压惊.