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');
}
}