编写一个 JAVA 程序,实现输出考试成绩的前三名

J2EE 码拜 8年前 (2016-09-22) 1114次浏览
package com.imooc4;
import java.util.Arrays;
public class HelloWorld {
// 完成 main 方法
public static void main(String[] args) {
HelloWorld hello = new HelloWorld();
int[] scores = { 89, -23, 64, 91, 119, 52, 73 };
System.out.println(“考试成绩的前3名为:”);
System.out.println(hello.sort(scores));
}
// 定义方法完成成绩排序并输出前三名的功能
public int[] sort(int[] scores) {
Arrays.sort(scores);
int count = 0;
for (int i = scores.length – 1; i >= 0; i–) {
if ((scores[i] <= 0) && (scores[i] >= 100)) {
continue;
}
count++;
if (count > 3) {
break;
}
System.out.println(scores[i]);
}
return scores;
}
}
考试成绩的前3名为:
119
91
89
[I@19e0bfd
解决方案

3

哈哈,前面三个是你sort方法里面输出的,底下那个你输出的是个 int[] 对象,所以。哈哈编写一个 JAVA 程序,实现输出考试成绩的前三名

1

引用:
Quote: 引用:
Quote: 引用:

哈哈,前面三个是你sort方法里面输出的,底下那个你输出的是个 int[] 对象,所以。哈哈编写一个 JAVA 程序,实现输出考试成绩的前三名

还有一个问题,本人不是已经进行了有效值判断了吗,怎么输出还有119?

把 ||  写成 && 了

小姑娘,你还是不理解代码的执行过程啊,来来分析一下:
第一步,Arrays.sort(scores),这个时候scores变成了–>[-23, 52, 64, 73, 89, 91, 119]
第二部,对于数组的最后一个数,也就是119,不满足在0-100直接,重点来了,count++,count变成1,继续执行,count<3,继续执行,输出score[i],也就是119。
第三部,继续循环,得到的结果就是 输出前三个最大的数,然后结束。
根本没有实现你要的考试成绩前三名,你的scores数组只是排了序而已。
所以:可以调整下:

public static void main(String[] args) {
		HttpTest hello = new HttpTest();
		int[] scores = { 89, -23, 64, 91, 119, 52, 73 };
		System.out.println("考试成绩的前3名为:");
		System.out.println(hello.sort(scores));
	}
	// 定义方法完成成绩排序并输出前三名的功能
	public String sort(int[] scores) {
		Arrays.sort(scores);
		int count = 0;
		StringBuilder top3Str = new StringBuilder();
		for (int i = scores.length - 1; i >= 0; i--) {
			if ((scores[i] <= 0) && (scores[i] >= 100)) {
				continue;
			}else{
				top3Str.append(scores[i]+"\n");
				count++;
			}
			if (count > 3) {
				break;
			}
			//System.out.println(scores[i]);
		}
		return top3Str.toString();
	}

15

sorry,刚刚那个代码有点问题,要修改一下:把&&改为||,把3改成2。编写一个 JAVA 程序,实现输出考试成绩的前三名

public String sort(int[] scores) {
		Arrays.sort(scores);
		int count = 0;
		StringBuilder top3Str = new StringBuilder();
		for (int i = scores.length - 1; i >= 0; i--) {
			if ((scores[i] <= 0) || (scores[i] >= 100)) {
				continue;
			}else{
				top3Str.append(scores[i]+"\n");
				++count;
			}
			if (count > 2) {
				break;
			}
		}
		return top3Str.toString();
	}

1

引用:
Quote: 引用:

为什么运行结果会有乱码?

调用写错了。百思不得其解。一问出来突然就知道了编写一个 JAVA 程序,实现输出考试成绩的前三名

编写一个 JAVA 程序,实现输出考试成绩的前三名


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明编写一个 JAVA 程序,实现输出考试成绩的前三名
喜欢 (0)
[1034331897@qq.com]
分享 (0)