为了账号安全,请及时绑定邮箱和手机立即绑定

java中循环可以随意嵌套么?

java中循环可以随意嵌套么?

断桥丶晓风残月 2016-06-29 17:04:50
import java.util.Arrays; public class Demo{        public static void main(String[] args){               int[] scores={89,-23,64,91,119,52,73}               Demo hello=new Demo();               System.out.println("考试成绩的前三名为:");               hello.getScores(scores);        }        public int[] getScores(scores){        Arrays.sort(scores);        int count=0;        if(count<3){          for(int i=scores.length-1;i--){               if(scores[i]<0||scores[i]>100){                  continue;              }else{                      System.out.println(scores[i]);                      count++;              }         }       } } 代码要实现输出考试成绩的前三名。 }
查看完整描述

3 回答

已采纳
?
绿洲仙人球

TA贡献39条经验 获得超47个赞

循环怎么嵌套应该和需求有关系,我读了一下题主的代码,就贴出来的这部分而言是无法运行的,一是代码语法有点错误,而是根据需求,要输出考试成绩的前三名,代码的逻辑也有点问题,在没有大改动题主的代码的基础上,实现了功能,代码如下

public class Demo {
	public static void main(String[] args) {
		int[] scores = {89, -23, 64, 91, 119, 52, 73 };
		Demo hello = new Demo();
		System.out.println("考试成绩的前三名为:");
		hello.getScores(scores);
	}

	public void getScores(int[] scores) {
		Arrays.sort(scores);
		int count = 0;
		for (int i = scores.length - 1;; i--) {
			if (count < 3) {
				if (scores[i] < 0 || scores[i] > 100) {
					continue;
				} else {
					System.out.println(scores[i]);
					count++;
				}
			}
		}
	}
}

需要把for循环和if (count < 3) 的判断调换一下位置,这样就没有问题了

查看完整回答
3 反对 回复 2016-06-30
  • qq_匡璐_0
    qq_匡璐_0
    这样就没有问题了,这么肯定?你运行过?你这样不是输出的后3名?
  • 绿洲仙人球
    绿洲仙人球
    你自己运行一下不就知道了么
  • 绿洲仙人球
    绿洲仙人球
    Arrays.sort(scores);默认是升序排列,我取后三个当然是前三名呀
点击展开后面3
?
断桥丶晓风残月

TA贡献32条经验 获得超15个赞

有人可以解答一下么?

查看完整回答
反对 回复 2016-06-29
?
qq_匡璐_0

TA贡献96条经验 获得超96个赞

public void main(String[] args) {
   int[] scores = {89, -23, 64, 91, 119, 52, 73};
   Arrays.sort(scores);
   System.out.println("考试成绩的前三名为:");
   for(int i = 0 ;i<3;i++){
       int j = scores[scores.length-1-i];
       System.out.println(j);
   }
}

查看完整回答
反对 回复 2016-06-30
  • 3 回答
  • 1 关注
  • 2323 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信