选择语句练习
- 写出输出结果。
class Demo
{
public static void main(String[] args)
{
show(0);
show(1);
}
public static void show(int i)
{
switch(i)
{
default:
i+=2;
case 1:
i+=1;
case 4:
i+=8;
case 2:
i+=4;
}
System.out.println("i="+i);
}
}
输出:
i=15 , //没有符合条件的case,又因为default在第一句,case中没有break,所以顺序执行。
i=14 ,//满足条件,从满足条件的case 1 执行,没有break跳出switch,所以往下顺序执行。
2.写出输出结果
class Demo
{
public static void main(String[] args)
{
int x=0,y=1;
if(++x==y-- & x++==1||--y==0)
System.out.println("x="+x+",y="+y);
else
System.out.println("y="+y+",x="+x);
}
}
输出:x=2,y=0 // ++x,先加后参与运算,y–先参与运算再+1,从左到右运算,又 因 逻辑或 “||” 左边为真后,右边的式子不参与运算。so。
3.求出1~100之间,即使3又是7的倍数出现的次数。
class Test
{
public static void main(String[] args)
{
int count=0;
for(int i=1;i<=100;i++)
{
if(i%3==0&&i%7==0)
count++;
else
continue;
}
System.out.println(count);
}
}
4.用程序的方式显示出下列结果。
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
class Test2
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(j+"*"+i+"="+i*j+"\t");
}
System.out.println();
}
}
}
5.写出程序结果。
class Demo
{
public static void main(String[] args)
{
int x = 1;
for(show('a'); show('b') && x<3; show('c'))
{
show('d');
x++;
}
}
public static boolean show(char ch)
{
System.out.println(ch);
return true;
}
}
输出:abdcbdcb
6.输入一个年份,判断是否是闰年(能被4整除并且不能被100整除或者能被400整除的就是闰年)?
public static void main(String[] args) {
System.out.print("请输入个年份:");
Scanner scanner = new Scanner(System.in);
int year = scanner.nextInt();
if (year%4 == 0 && year%100 == 0 || year%400 == 0) {
System.out.println(year+"是闰年。");
}else {
System.out.println(year+"不是闰年。");
}
}
7.已知学生成绩以100分为满分,共分5个等级:A,B,C,D,E。
90~100为等级A,80~89为等级B,70~79为等级C,
60~69为等级D,0~59为等级E。
要求定义一个成绩变量,当成绩变化时,可直接知道该成绩对应的等级。
例如:当成绩为100时,该学生的等级是A。
public static void main(String[] args) {
System.out.print("输入成绩:");
Scanner scanner = new Scanner(System.in);
double score = scanner.nextDouble();
if (score <= 100) {
int grade = (int) score / 10;
switch (grade) {
case 10:
case 9:
System.out.println("成绩为A等");
break;
case 8:
System.out.println("成绩为B等");
break;
case 7:
System.out.println("成绩为C等");
break;
case 6:
System.out.println("成绩为D等");
break;
default:
System.out.println("成绩为E等");
}
}else {
System.out.println("最高为100分,请重新输入");
}
}