基础语法练习
-
水仙花数
// 在 main 方法中打印 100-999 之间所有的水仙花数(各位数字立方和等于该数本身) public class Bs_exe01_shuixianhua { public static void main(String[] args) { for (int i = 100; i <= 999; i++) { int a = i / 100; int b = i % 100; int c = b / 10; int d = i % 10; if (a * a * a + c * c * c + d * d * d == i) { System.out.print(i + "\t"); } } } }
-
阶乘
// 输入一个数,计算数字阶乘,使用 while 完成 import java.util.Scanner; public class Bs_exe02_factorial { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入数字:"); double a = scanner.nextInt(); double result = a; while (true){ a--; if (a==0){ break; }else { result *= a; } } System.out.println("计算结果为:"+result); } }
-
九九乘法表
// 使用 for 循环打印九九乘法表 public class Bs_exe03_multiplication_table { public static void main(String[] args) { for (int i = 1; i <= 9; i++) { for (int j = 1; j <= i; j++) { System.out.print(i+"*"+j+"="+i*j+"\t"); } System.out.println(); } } }
-
随机生成数求偶
// 获取一个 2-500 之间(包含2和500)的随机数n,求0-n之间(包含0和n)的偶数和,并打印到控制台上 public class Bs_exe04_random { public static void main(String[] args) { // int num = m + (int)(Math.random()*n); 生成m----m+n的随机数 int num = 2 + (int)(Math.random()*248); System.out.println("生成的随机数为:" + num); int result = 0; for (int i = 0; i <= num; i++) { if (i % 2 == 0){ result += i; } } System.out.println("求偶结果为:"+result); } }
-
数组打印指定元素的出现次数
// int[] arr = {1,1,2,2,3,4,5,4,3,2,1},打印出数字2出现的次数 import java.util.Arrays; public class Bs_exe05_array01 { public static void main(String[] args) { int[] arr = {1,1,2,2,3,4,5,4,3,2,1}; System.out.println("原始数组为:"+Arrays.toString(arr)); int sum = 0; for (int element : arr) { if(element == 2){ sum++; } } System.out.println("2出现次数:"+sum); } }
-
数组打印指定元素第二次出现的索引
// 在数组中 查询数据55第二次出现的位置,打印第二次出现的索引 {11,32,55,47,55,79,23} (索引从0开始) import java.util.Arrays; public class Bs_exe06_array02 { public static void main(String[] args) { int[] array = {11,32,55,47,55,79,23}; int num = 0; System.out.println("原始数组为:"+Arrays.toString(array)); for (int i = 0; i < array.length; i++) { if (array[i] == 55){ num++; if (num == 2){ System.out.println("55第二次出现的位置的索引为:"+i); break; } } } } }
-
随机生成数组然后进行操作
/* 定义一个长度为5的 int型数组,之后生成5个随机数存入数组,随机数范围为10-100,遍历数组,将数组中小于50的元素替换成0, 之后打印修改后的数组。 */ import java.util.Arrays; public class Bs_exe07_array03 { public static void main(String[] args) { int[] array = new int[5]; int num ; for (int i = 0; i < 5; i++) { num = 10+(int)(Math.random()*90); array[i] = num; } // 这里可以考虑重写 Arrays 中的:fill 方法来填充 System.out.println("随机生成的数组为:"+Arrays.toString(array)); for (int i = 0; i < array.length; i++) { if (array[i] < 50){ array[i] = 0; } } System.out.println("最终的数组为:"+Arrays.toString(array)); } }
小结: 生成随机数的方法
int num = m + (int)(Math.random()*n); 生成m——m+n的随机数