遇到java arraylist的问题

时间:2015-02-05 05:27:36

标签: java arraylist

我需要做的是创建一个存储所有分数的数组并反向显示数字。帮助~~ !! 到目前为止,我提出了这个问题。

// wbin

    import java.util.Scanner;
    import java.text.DecimalFormat;

    public Class ArrayPractice
    {
    public static void main(String[] args) {
     int count = 0;
     int total = 0;
     final int SENTINEL = 0;
     int score;
     int sum;


     Scanner scan = new Scanner( System.in );

     System.out.println( "Enter your score then Press 0 to display your average and total score. " );
     System.out.println( "When you are finished, Press 0" );

     System.out.print( "Enter the first test score > " );
     score = scan.nextInt( );

     while ( score != SENTINEL )
     {
        total = score + total;

        count++;

        System.out.print( "Enter the next test score > " );
        score = scan.nextInt( );
     }



     if ( count != 0 )
     {
        DecimalFormat oneDecimalPlace = new DecimalFormat( "##.0" );
        System.out.println("\nYour Average is "
          + oneDecimalPlace.format( (double) ( total  / count) ) );
          System.out.println("Your Total score is " + total);
}
         else
        System.out.println( "\nNo grades were entered" );

  }
}

2 个答案:

答案 0 :(得分:0)

在循环中添加各个分数:

ArrayList<Integer> scores = new ArrayList<Integer>();
while ( score != SENTINEL )
 {
    scores.add(score)
    total = score + total;

    count++;

    System.out.print( "Enter the next test score > " );
    score = scan.nextInt( );
 }

你可以做另一个循环来反向显示你的成绩:

for(int i = scores.size(); i > 0; i--){
    System.out.println(scores.get(i));
}

希望这有帮助。

答案 1 :(得分:0)

另一种以相反顺序打印商品的方法

Scanner scan = new Scanner( System.in );
    List<Integer> scores = new ArrayList<Integer>();
    int totalScore =0;
    while(true) {
        System.out.print( "Enter the test score > " );
        int score=scan.nextInt( );
        if(score==0) break;
        totalScore+=score;
        scores.add(score);
    }

    Collections.reverse(scores);

    for(int score:scores){
        System.out.println(score);
    }