このプログラムには、アレイに対してさまざまな機能を実行するためのオプションを含むメニューがあります。この配列は、「data.txt」というファイルから取得されます。このファイルには、整数が 1 行に 1 つずつ含まれています。これらの整数を配列に格納するメソッドを作成して、計算を実行する必要があるときにそのメソッドを呼び出すことができるようにしたいと考えています。明らかに、コード全体を含めていません (長すぎます)。しかし、誰かが平均を計算する最初の問題で私を助けてくれることを望んでいました. 現在、コンソールは平均値として 0 を出力します。これは、1、2、3 がファイル内にあることに加えて、残りの配列が 0 で埋められているためです。私が望む平均は2です。どんな提案も大歓迎です。私のプログラムの一部は以下のとおりです。ありがとう。
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Calculation Program!\n");
startMenus(sc);
}
private static void startMenus(Scanner sc) throws FileNotFoundException {
while (true) {
System.out.println("(Enter option # and press ENTER)\n");
System.out.println("1. Display the average of the list");
System.out.println("2. Display the number of occurences of a given element in the list");
System.out.println("3. Display the prime numbers in a list");
System.out.println("4. Display the information above in table form");
System.out.println("5. Save the information onto a file in table form");
System.out.println("6. Exit");
int option = sc.nextInt();
sc.nextLine();
switch (option) {
case 1:
System.out.println("You've chosen to compute the average.");
infoMenu1(sc);
break;
case 2:
infoMenu2(sc, sc);
break;
case 3:
infoMenu3(sc);
break;
case 4:
infoMenu4(sc);
break;
case 5:
infoMenu5(sc);
break;
case 6:
System.exit(0);
default:
System.out.println("Unrecognized Option!\n");
}
}
}
private static void infoMenu1(Scanner sc) throws FileNotFoundException {
File file = new File("data.txt");
sc = new Scanner(file);
int[] numbers = new int[100];
int i = 0;
while (sc.hasNextInt()) {
numbers[i] = sc.nextInt();
++i;
}
System.out.println("The average of the numbers in the file is: " + avg(numbers));
}
public static int avg(int[] numbers) {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum = (sum + numbers[i]);
}
return (sum / numbers.length);
}