import java.util.Arrays; //定义一个数组{1,3,4,2,6,2,6,2,8,2,6},要求输出结果是不重复的数 public class ZY01 { public static void main(String[] args) { int a[] = {1, 3, 4, 2, 6, 2, 6, 2, 8, 2, 6}; Arrays.sort(a); for (int i =0;i<a.length-1;i++){ if (a[i]!=a[i+1]){ if (i+1==a.length-1){ System.out.println(a[i]); System.out.println(a[i+1]); }else { System.out.println(a[i]); } }else if (i+1==a.length-1){ System.out.println(a[i+1]); } } } }
//在数组{4,5,6,2,3,1,9,8,7,10,12,14,15}中查找元素 // (先打印输出所有元素,输入一个数,如果找到了则打印输出其位置, // 没有找到则提示没有找到) public class ZY02 { public static void main(String[] args) { int a[] = {4,5,6,2,3,1,9,8,7,10,12,14,15}; for(int i:a){ System.out.println(i+" "); } System.out.println(); System.out.println("请输入一个数"); int b = new Scanner(System.in).nextInt(); for (int i = 0;i<a.length;i++){ if (b==a[i]){ System.out.println("数据的位置为:+i"); break; }else if (i==a.length-1){ System.out.println("没有找到"); } } } }
//.有一个整数数组,其中存放着序列 // 1,3,5,7,9,11,13,15,17,19。 // 请将该序列倒序存放并输出。 public class ZY04 { public static void main(String[] args) { int a[] = {1,3,5,7,9,11,13,15,17,19}; for (int i= 0;i<a.length/2;i++){ int temp = a[i]; a[i] = a[a.length-1-i]; a[a.length-1-i] = temp; } for (int i:a){ System.out.println(i+" "); } } }
编写一个程序,读入数目确定得考试分数,并且判断有多少个分数高于或等于平均分,有多少个分数低于平均分, 输入一个负数标志输入结束,假设最高分为100.
import java.util.Scanner; | |
public class ScoreAnalysis { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
double sum = 0; | |
int count = 0; | |
// 用于存储分数的数组(在实际应用中,如果不知道具体数量,可以使用ArrayList等动态数据结构) | |
// 但为了简化,这里我们假设输入的数量不会超过某个预定义的最大值 | |
// 注意:在实际应用中,这样做可能会导致内存浪费或数组越界异常 | |
// 这里仅作为示例 | |
double[] scores = new double[100]; // 假设最多只有100个分数 | |
System.out.println("请输入考试分数(输入负数结束):"); | |
while (scanner.hasNextDouble()) { | |
double score = scanner.nextDouble(); | |
if (score < 0) { | |
break; // 遇到负数,退出循环 | |
} | |
if (score >= 0 && score <= 100) { // 确保分数在有效范围内 | |
scores[count++] = score; // 存储分数并增加计数器 | |
sum += score; // 计算总分 | |
} else { | |
System.out.println("分数必须在0到100之间,该分数已被忽略。"); | |
} | |
} | |
if (count == 0) { | |
System.out.println("没有输入任何有效分数。"); | |
} else { | |
double average = sum / count; // 计算平均分 | |
int aboveOrEqual = 0; | |
int below = 0; | |
// 统计高于或等于平均分以及低于平均分的分数数量 | |
for (int i = 0; i < count; i++) { | |
if (scores[i] >= average) { | |
aboveOrEqual++; | |
} else { | |
below++; | |
} | |
} | |
// 输出结果 | |
System.out.printf("平均分是: %.2f\n", average); | |
System.out.printf("有 %d 个分数高于或等于平均分。\n", aboveOrEqual); | |
System.out.printf("有 %d 个分数低于平均分。\n", below); | |
} | |
scanner.close(); | |
} | |
} |
请注意,这个程序使用了Scanner
类来从控制台读取输入,并使用了一个固定大小的数组scores
来存储分数。然而,这种方法在实际应用中可能不是最优的,因为您可能不知道用户将输入多少个分数。在这种情况下,使用ArrayList<Double>
这样的动态数据结构可能会更好。
另外,程序在读取分数时进行了范围检查,以确保输入的分数在0到100之间(包括0和100)。如果输入的分数不在这个范围内,程序将输出一个错误消息,并忽略该分数。