韩顺平java | doWhileExercise01

1. 题目要求: 用do-while循环打印1-100

public class doWhileExercise01 {
    public static void main (String[] args){
        int i = 1;
        do {
            System.out.println(i);
            i++;
        } while (i <= 100);
    }
}

下方代码是用while循环

public class doWhileExercise01 {
    public static void main (String[] args) {
        int i = 1;
        while (i <= 100) {
            System.out.println(i);
            i++;
        }
    }
}

2. 题目要求: 计算1-100 的和

public class doWhileExercise02 {
    public static void main (String[] args){
        int i = 0;
        int sum = 0;
        while (i <= 100){
            sum += i;
            i++;
        }
        System.out.println(sum);
    }
}

注意,System.out.println(sum)不要写到while里面去,不然会把所有的sum都打印出来。 

public class doWhileExercise02 {
    public static void main (String[] args){
        int i = 0;
        int sum = 0;
        do{
            sum+=i;
            i++;
        } while (i <= 100);
        System.out.println(sum);
    }
}

3. 题目要求: 统计1-200之间能被5整除,但不能被3整除的个数

public class doWhileExercise03 {
    public static void main (String[] args){
        int i = 1;
        int endNum = 200;
        int count = 0;
        do {
            if (i % 5 ==0 && i % 3 != 0){
                count++;
            }
            i++;
        } while (i <= endNum);
        System.out.println(count);
    }
}

4. 题目要求: 如果李三不还钱,则老韩一直使出五连鞭一直到李三还钱为止。[System.out.println("老韩问:还钱吗?“)]

 这是我写的,多用了几行if statement

public class doWhileExercise04 {
    public static void main(String[] args){

        Scanner myScanner = new Scanner(System.in);

        char answer = ' ';
        do {
            System.out.println("Do you give back the money?");
            answer = myScanner.next().charAt(0);
            System.out.println("Your answer is " + answer);
            if (answer == 'y'){
                break;
            }
            else{
                System.out.println("Wulianbian");
            }


        } while (true);
    }
}

 这是老师写的,直接在判断语句中定义一个条件

public class doWhileExercise04 {
    public static void main(String[] args){

        Scanner myScanner = new Scanner(System.in);

        char answer = ' ';
        do {
            System.out.println("Do you give back the money?");
            answer = myScanner.next().charAt(0);
            System.out.println("Your answer is " + answer);


        } while (answer != 'y');
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值