banner
NEWS LETTER

实验一:Java 基础程序设计

Scroll down

实验一:Java 基础程序设计

(1)输入一系列成绩,输出最高分、最低分、平均分,并统计存在多少个并列最高分,要求输入输出格式正确,一重循环解决全部问题。

输入:65 87 95 86 72 58 56 75 95 94 78…

输出:最高分:95,最低分:56,平均分:72.36,同时存在 2 个并列最高分。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public static void question1() {

System.out.println("请输入十个数(以空格分割):");
Scanner input = new Scanner(System.in);
String s = input.nextLine();
String s1[] = s.split(" ");
int[] A = new int[11];

for (int i = 0; i < s1.length; i++) {
A[i] = Integer.parseInt(s1[i]);

}
int max = A[0];
int min = A[0];
int sum = 0;
int tag = 0; // 记录最高成绩的出现了几次
for (int i : A) {
if (i == max)
tag++;
if (i > max) {
max = i;
tag = 1;
}
if (i < min)
min = i;
sum += i;
}
System.out.println("最高分:" + max + ",最低分" + min + ",平均分:" +
(double) sum / A.length + ",同时存在" + tag + "个并列最高分.");
}

运行结果:

3

(2)输出 1,000,000 之内的所有素数(即非 1 和自身不能被其他数除尽的数)要求程序简单,程序运行速度较快,行列对齐美观。

2 3 5 7 11 13 17 19……

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static void question2() {
int count = 0;
for (int i = 2; i <= 1_000_000; i++) {
boolean isPrime = true;
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
if (count == 5) {
System.out.println();
count = 0;
}
System.out.print(i + " ");
count++;
}
}
}

运行结果:

2

(3)输出如下图形,行数通过键盘输入的数据确定:

1
2
3
4
5
6
     1
2 2
1 1 1
2 2 2 2
1 1 1 1 1
2 2 2 2 2 2

(用死循环反复测试)

采用 Scanner 类输入方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
System.out.print("请输入金字塔层数:");
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();//读入一个整数
String s=sc.nextLine();//读入一行字符串
采用 JavaIO 流的输入方式:
System.out.print("请输入金字塔层数:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s="";
try{
s=br.readLine();//读入一行字符串
}
catch(IOException e){}
int m =Integer.parseInt(s);//把字符串转为整型
System.out.println("将输出"+m+"层的金字塔:");
……
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static void question3() {
System.out.print("请输入金字塔层数:\n");
int rows = new Scanner(System.in).nextInt();
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
if (i % 2 != 0) {
for (int n = 0; n < i; n++) {
System.out.print(1 + " ");
}
System.out.println();
} else {
for (int n = 0; n < i; n++) {
System.out.print(2 + " ");
}
System.out.println();
}
}
}

运行结果:

1

其他文章
cover
My Gallery
  • 25/09/27
  • 12:57
  • 0
  • 1
目录导航 置顶
  1. 1. 实验一:Java 基础程序设计
    1. 1.1. (1)输入一系列成绩,输出最高分、最低分、平均分,并统计存在多少个并列最高分,要求输入输出格式正确,一重循环解决全部问题。
      1. 1.1.1. 输入:65 87 95 86 72 58 56 75 95 94 78…
      2. 1.1.2. 输出:最高分:95,最低分:56,平均分:72.36,同时存在 2 个并列最高分。
      3. 1.1.3. 运行结果:
    2. 1.2. (2)输出 1,000,000 之内的所有素数(即非 1 和自身不能被其他数除尽的数)要求程序简单,程序运行速度较快,行列对齐美观。
      1. 1.2.1. 2 3 5 7 11 13 17 19……
      2. 1.2.2. 运行结果:
    3. 1.3. (3)输出如下图形,行数通过键盘输入的数据确定:
      1. 1.3.1. (用死循环反复测试)
      2. 1.3.2. 运行结果: