白富美:身为女子,洁身自好为白,经济独立为富,|

huxingxin

园龄:6年10个月粉丝:26关注:0

day04-分支结构

1、switch后面使用的表达式可以是哪些数据类型的。

byteshortcharint、枚举类型变量、字符串类型。

2、使用switch语句改写下列if语句:

int a = 3;
int x = 100;
if(a==1)
x+=5;
else if(a==2)
x+=10;
else if(a==3)
x+=16;
else
x+=34;
int a = 3;
int x = 100;
switch(){
case 1:
x += 5;
break;
case 2:
x += 10;
break;
case 3:
x += 16;
break;
default:
x += 34;
break;
}

3、谈谈你对三元运算符、if-else和switch-case结构使用场景的理解。

(1)三元运算符、swithc-case结构都可以改写成if-else结构,反之,则不成立。

(2)如果三种结构都适合用,且判断的具体数值不多,优先考虑三元运算符或者 switch-case结构,代码简洁、效率略高。

4、如何从控制台获取String和int型的变量,并输出?使用代码实现。

(1)导包

import java.util.Scanner;

(2)创建对象

Scanner scanner = new Scanner(System.in);

(3)获取键盘输入的值

String str = scanner.next();
int number = scanner.next
import java.util.Scanner;
public class Demo(){
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
String str = scanner.next();
int number = scanner.nextInt();
System.out.println("str: " + str);
System.out.println("number: " + number)
}
}

5、使用for循环遍历100以内的奇数,并计算所有的奇数的和并输出。

public class Demo(){
public static void main(String args[]){
int sum = 0;
for(int i = 1; i <= 100; i++){
if(i % 2 != 0){
sum += i;
System.out.println("i: " + i);
}
}
System.out.println("奇数的和: " + sum);
}
}

本文作者:huxingxin

本文链接:https://www.cnblogs.com/huxingxin/articles/16903887.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   huxingxin  阅读(26)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起