程序輸出錯(cuò)誤調(diào)試
8-1為何只輸出兩個(gè)數(shù)不是三個(gè)?
import java.util.*;
public class HelloWorld {
? ??
? ? //完成 main 方法
? ? public static void main(String[] args) {
? ? ? ? //定義數(shù)組
? ? ? ? int scores[]=new int []{89,-23,64,91,119,52,73};
? ? ? ? HelloWorld hello=new HelloWorld();
? ? ? ? hello.sort(scores);
? ? ? ??
? ? }
? ?
? ? //定義方法完成成績(jī)排序并輸出前三名的功能
? ? public void sort(int [] scores){
? ? ? ?Arrays.sort(scores);
? ? ? ?System.out.println("考試成績(jī)的前三名為:");
? ? ? ?for(int i=scores.length-1;i>=0&&i>=scores.length-3;i--){
? ? ? ? ? if(scores[i]>=0&&scores[i]<=100) {System.out.println(scores[i]);
? ? ? ?}
? ? ? ?
? ? }
?}
}
2016-06-27
?private void sort(int []scores){
? ? ? ? Arrays.sort(scores);
? ? ? ? System.out.println("考試成績(jī)的前三名為:");
? ? ? ? for(int i = scores.length -1; i >-1 ;i--){
? ? ? ? ? ? if(scores[i] <0 || scores[i]>100)
? ? ? ? ? ? ? ? continue;
? ? ? ? ? ? else if(scores.length -1 -i < 4){
? ? ? ? ? ? ? ? System.out.println(scores[i]);
? ? ? ? ? ? }
? ? ? ? }?
? ? }
2016-06-22
數(shù)組排序后,變?yōu)閇-23,52,64,73,89,91,119]。
第一次循環(huán),i=6,scores[i]=119,不滿足boolean條件,不輸出;
第二次循環(huán),i=5,scores[i]=91,輸出;
第三次循環(huán),i=4,scores[i]=89,輸出;
第四次循環(huán),i=3,此時(shí)i<4,不滿足條件,程序執(zhí)行結(jié)束。
只有兩次是因?yàn)槌绦驔](méi)有使用計(jì)數(shù)器,而是直接篩選數(shù)組后三個(gè),而這三個(gè)中又有一個(gè)不滿足輸出條件,因而只有兩個(gè)。
2016-06-22