switch语句也是多重选择的一种 其表达方式
switch(a)
case a://注意case后面有空格
case b:
case c:
case d:
.....
default: //可有可无
switch语句会根据表达式的值从相匹配的执行,一直执行到break处。开始直到break语句处或是switch语句的末尾,与任一case值不匹配则进入default语句
switch只能处理等值条件判断的情况且表达式必须为byte,short,int,或者char型 不能是string,double和float。
常量值必须是与表达式类型兼容的特定的一个常量。
不允许有重复的case值。
default字句可有可无。
switch具有一个穿越属性当流程进入到case语句段中没有遇到break,他将会继续向下运行直到见到break为止。
循环
循环的三要素:初始化,条件表达式,增量。
表达式表明了循环的结束条件。
增量是循环逐渐靠近结束,避免死循环。
while
//循环打印1到100
public class WhileDemo
{
public static void main(String[] args){
//初始值
int i = 1;
//表达式
while(i<=100){
System.out.println(i);
//增量
i++;
}
}
}
//循环打印并加起来
public class WhileDemo
{
public static void main(String[] args){
int i = 1;
//定义一个变量用来 计算他们的和
int sum = 0;
while(i<=100){
//sum +=i 相当于 sum=sum+i;
sum+=i;
i++;
}
//循环外面输出 循环里面输出会加一次输出一次
System.out.println(sum);
}
}
do-while循环
// do while 计算和
public class WhileDemo
{
public static void main(String[] args){
int i = 1;
int sum=0;
do{
sum+=i;
i++;
}while(i<=100);
//与while一样 最后输出sum
System.out.println(sum);
}
}
do-while 和while 的区别
public class WhileDemo
{
public static void main(String []args){
int i = 1;
//while 不会执行
while(i!=1){
System.out.println("我是while");
}
// do while 会先执行一次
do{
System.out.println("我是do while!");
}while(i!=1);//注意后面分号
}
}
while先判断后执行
do-while 先执行后判断
for循环跟while 和do-while差不多 但是for 更简洁
// for 循环 打印1到100
public class ForDemo
{
public static void main(String[] args){
for(int i = 1;i<=100;i++){
System.out.println(i);
}
}
}
//打印1到100奇数和 还有偶数和 用不同方法
public class ForDemo
{
public static void main(String[] args){
int i = 1;
int sum = 0,count = 0;
int b = 0,c = 0;
//while 打印
while(i<=100){
if(i%2!=0){
sum+=i;
}else{
count+=i;
}
i++;
}
//for 打印
for(i=1;i<=100;i++){
if(i%2==0){
b+=i;
}else{
c+=i;
}
}
System.out.println("奇数和是:"+sum+"偶数和是"+count);
System.out.println("偶数和是:"+b+"奇数和是"+c);
}
}
//判断一个数是否是素数
import java.util.*;
public class Lkj
{
public static void main(String[]args){
Scanner sc = new Scanner(System.in);
System.out.println("输入一个数:");
int a = sc.nextInt();
int i = 2;
boolean c = true;
for(i=2;i<a;i++){
if(a%i==0){
c = false;
break;
}
}if(c==true){
System.out.println("是素数");
}else{
System.out.println("不是素数");
}
}
}