利用分支结构,循环结构解题
- 编写程序数一下 1到 100 的所有整数中出现多少个数字9
public class Test {
public static void main(String[] args) {
//数字9 出现的次数
int count=0;
for(int i=1;i<=100;i++){
if(i/10==9){
count++;
}if(i%10==9){
count++;
}
}
System.out.println(count);
}
}
运行结果
2. 输出 1000 - 2000 之间所有的闰年
public class Test {
public static void main(String[] args) {
for(int year=1000;year<=2000;year++){
if(year%100==0){
//判定世纪闰年
if(year%400==0){
System.out.println(" "+year+"是闰年");
}else{
System.out.println(" "+year+"不是闰年");
}
}else{
//普通闰年
if(year%4==0){
System.out.println(" "+year+"是闰年");
}else{
System.out.println(" "+year+"不是闰年");
}
}
}
}
}
运行结果
- 打印 1 - 100 之间所有的素数
public class Practice {
public static void main(String[] args) {
//打印 1 - 100 之间所有的素数int i=0;int j=0;
for(i=1;i<=100;i++){
for(j=2;j<=i;j++){
if(i%j==0){
break;
}
}
if(j==i){
System.out.println(i);
}
}
}
}
运行结果
- 给定一个数字,判定一个数字是否是素数
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
//给定一个数字,判定一个数字是否是素数
Scanner sc=new Scanner(System.in);
System.out.print("请输入一个数字:");
int num=sc.nextInt();
int j=0;
for(j=2;j<=num;j++){
if(num%j==0){
break;
}
}
if(j==num){
System.out.println(" "+num+"是素数");
}else{
System.out.println(" "+num+"不是素数");
}
}
运行结果
- 根据输入的年龄, 来打印出当前年龄的人是少年(低于18), 青年(19-28), 中年(29-55), 老年(56以上)
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
//根据输入的年龄, 来打印出当前年龄的人是少年(低于18), 青年(19-28), 中年(29-55), 老年(56以上)
int age=88;
if(age<=18){
System.out.println("少年");
}else if(age>19&&age<=28){
System.out.println("青年");
}else if(age>29&&age<=55){
System.out.println("中年");
}else{
System.out.println("老年");
}
}
}
运行结果