Java根据用户输入计算平均值

fv2wmkja  于 2023-01-15  发布在  Java
关注(0)|答案(3)|浏览(133)

我有一个问题,我的代码。请帮助我解决它。程序应该退出,并返回平均值时,q输入。如果你输入5个数字,它是工作正常。数组大小应该是20。下面是代码:

import java.util.Scanner;

public class test{

public static void main(String[] args){

int x;

int count=0;
char q= 'q'; 
Scanner input = new Scanner(System.in);
int[] array = new int[5];
System.out.print("You have entered 0 numbers, please enter a number or q to quit:" );

while (input.hasNextInt()){

for (int i = 0; i < array.length; i++)
{

    array[i] = input.next();

    count++;
    System.out.print("You have entered " +count+ " numbers, please enter a number or q to quit:" );
    }
}

System.out.println("Average is " + Average(array));
}


public static int Average(int[] array) {
int sum = 0;
for (int i = 0; i < array.length; i++)
sum += array[i];
return sum / array.length;
}

}
p4rjhz4m

p4rjhz4m1#

使用列表代替数组。检查输入是否为q打印平均值并返回系统。退出(0)

tcbh2hod

tcbh2hod2#

您应该在每个input.nextInt()之前检查input.hasNextInt()。

pjngdqdw

pjngdqdw3#

您正在使用一个复合循环,它否定了中断first/outter循环的能力。
您应该将两个循环合并为一个循环,查找两个转义条件,用户按q或输入5个数字...
因为您需要混合输入,所以需要手动将输入转换为int...。

String line = null;
// Loop until count >= 5 or the user inputs "q"
while (count < array.length && !(line = input.nextLine()).equalsIgnoreCase("q")) {
    try {
        // Convert the input to an int...
        int value = Integer.parseInt(line);
        array[count] = value;
        count++;
        System.out.print("You have entered " + count + " array, please enter a number or q to quit:");
    } catch (NumberFormatException exp) {
        System.out.println(line + " is not an int value...");
    }
}

相关问题