如何从带有for循环的数组中有选择地输出某些特定索引及其值?

时间:2019-10-12 10:49:18

标签: java arrays for-loop

  

程序应检查数组中的高度是否超过180厘米,然后应使用for循环打印索引和高度值。 (例如学生4:185厘米)

import java.util.Scanner;
public class Kursteilnehmer {

    public static void main(String[] args) {
        Scanner p = new Scanner(System.in);
        int students;
        System.out.print("Please enter the number of students: ");
        students = p.nextInt();

        // The number of students should be entered

        double[] height = new double[students];
        System.out.println("Please enter the height of every student: ");
        for (int i = 0; i < students; i++) {
            height[i] = p.nextDouble();

            //The height of every student muss be entered
        }

        // how to output the students that are taller than 180 cm with for-loop??

        double sum = 0;
        for (int i = 0; i < students; i++) {
            sum = sum + height[i];
        }
        System.out.println("The sum of every height is: " + sum + " cm");
        System.out.println();
        double average = sum / height.length;
        System.out.println("Average height: " + average + " cm");

        //The average height will be given
    }

}

1 个答案:

答案 0 :(得分:0)

使用此点获取输出。您正在遍历数组中的每个条目。使用height[i],您可以在当前索引处获取元素。如果当前高度超过180,则会打印该语句。

System.out.println("Students taller than 180 cm");
        for (int i = 0; i < height.length; i++) {
            if (height[i] > 180) {
                System.out.println("Student " + i + ": " + height[i]);
            }
        }