找出2-100之间所有质数
题目要求 找出2-100之间的所有质数 代码如下
public static void main(String
[] args
) {
for(int i
=2;i
<100;i
++){
boolean flag
=true;
for(int j
=2;j
<=i
-1;j
++){
if(i
%j
==0){
flag
=false;
break;
}
}if(flag
==true){
System
.out
.println(i
);
}
}
}
其中遇到的最大的问题就是并输出结果原因为 if(flag==true)编辑的时候写成if(flag=true)变为赋值导致
使用continue 输出1-100的奇数的前5个
package com
.gyc
.practice
;
public class Practice02 {
public static void main(String
[] args
) {
int count
=0;
for (int i
= 1; i
<100 ; i
++) {
if(!(i
%2==0)){
System
.out
.println(i
);
count
++;
continue;
}
if(count
==5)
break;
}
}
}
break与continue的区别
break:直接跳出当前循环体(while、for、do while)或程序块(switch)。其中switch case执行时,一定会先进行匹配,匹配成功返回当前case的值,再根据是否有break,判断是否继续输出,或是跳出判断(可参考switch的介绍)。continue:不再执行循环体中continue语句之后的代码,直接进行下一次循环。
登陆问题
public static void main(String
[] args
) {
for (int i
= 0; i
< 3; i
++) {
Scanner scanner
=new Scanner(System
.in
);
System
.out
.println("输入你的账号");
String username
=scanner
.next();
System
.out
.println("输入你的密码");
int psw
= scanner
.nextInt();
if(username
.equals("admin")&&psw
==123){
System
.out
.println("登陆成功");
break;
}else{
System
.out
.println("你输入的账号或者密码不对请重新输入,你还剩"+(2-i
)+"次机会");
}
}