如何在循环Java中添加更多变量

时间:2018-09-12 12:58:15

标签: java loops class variables

将每个部门的计算机数量存储在变量中。让程序将值存储在变量中,计算总数和平均计算机并显示它们。

示例输出: 化学:4 物理:8 音乐:2 数学实验室:12

总计:26 平均:6.5

import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);

    System.out.print("What is the name of your first class?");
    String class1 = sc.nextLine();

    System.out.print("What is the name of your second class?");
    String class2 = sc.nextLine();

    System.out.print("What is the name of your third class?");
    String class3 = sc.nextLine();

    System.out.print("What is the name of your fourth class?");
    String class4 = sc.nextLine();

    System.out.print(" \n\n");
    System.out.println("How many computers are in each class?");
    System.out.print(class1 + ": \t");
    int class1comp = sc.nextInt();
    System.out.print(class2 + ": \t");
    int class2comp = sc.nextInt();
    System.out.print(class3 + ": \t");
    int class3comp = sc.nextInt();
    System.out.print(class4 + ": \t");
    int class4comp = sc.nextInt();
    int sum = class1comp + class2comp + class3comp + class4comp;
    double avg = sum / 4.0;

    System.out.print(" \n\n");

    System.out.println("\n\n" + class1 + ":\t" + class1comp);
    System.out.println(class2 + ":\t" + class2comp);
    System.out.println(class3 + ":\t" + class3comp);
    System.out.println(class4 + ":\t" + class4comp);

    System.out.println("\n");
    System.out.println("Total:\t\t" + sum);
    System.out.println("Average:\t" + avg);
  }
}

第2单元之后:允许用户添加更多部门。

我希望用户能够添加更多的类,直到他们说停止为止。然后,稍后询问每个班级需要多少台计算机。然后显示它们,将它们添加到总和和平均值中。

1 个答案:

答案 0 :(得分:0)

这应该适合您的目的,它使用ArrayList作为类名,并使用整数数组作为成绩。它使用this answer中的AddOrdinal方法。

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    ArrayList<String> stringList = new ArrayList<>();
    String capture;
    int count =1;
    System.out.println("Please enter your "+AddOrdinal(count) +" class:");
    while (!((capture = scan.nextLine()).toLowerCase().equals("stop"))) {
        count++;
        stringList.add(capture);
        System.out.println("Please enter your "+AddOrdinal(count) +" class:");
    }
    System.out.println("How many computers are in each class?");
    int[] intList = new int[stringList.size()];
    for (int i = 0; i < stringList.size(); i++) {
        String className = stringList.get(i);
        System.out.println(className + "\t:");
        intList[i] = (scan.nextInt());
    }
    scan.close();
    Arrays.stream(intList).sum();
    int sum = Arrays.stream(intList).sum();
    double average = (double)sum/intList.length;
    /*
     Output goes here
    */
}