【问题标题】:Java Calculating average from users inputJava根据用户输入计算平均值
【发布时间】:2013-09-20 04:46:08
【问题描述】:

我的代码有问题。请帮我解决。当输入 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;
}

}

【问题讨论】:

  • 问题是什么?
  • 你打电话给input.hasNextInt()q 是整数吗?
  • 这就是问题所在,我知道 q 不是整数,但要让它全部工作我不知道。当输入 q 时,程序应该退出并返回平均值。
  • 我还想补充一点,如果输入准确的 5 个整数,代码将运行并给出平均值,但如果或多或少 5,我会出错
  • 你应该调用 while(input.hasNext()) 然后检查输入的输入是 char 还是 int 类型。如果找到 char 然后退出。

标签: java arrays average


【解决方案1】:

使用列表而不是数组。检查输入是否为 q 打印平均值并返回 system.exit(0)

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      您正在使用一个复合循环,它否定了打破第一个/外部循环的能力。

      您应该将两个循环合并为一个循环,寻找两个转义条件,用户按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...");
          }
      }
      

      【讨论】:

      • 谢谢,但是这段代码现在对我来说太复杂了,这只是第二次分配,代码应该尽可能简单。
      • 哪些部分有问题?
      • 如果输入非整数值,程序会崩溃,没关系。所以我想我不需要使用 catch 和后面的一切?
      • 我尝试使用您的代码,但平均值不再有效。你能告诉我如何让它工作吗?例如,用户输入 6 个数字,然后输入 q,它应该返回平均值。
      • 你在while循环之后调用了你的平均方法吗?
      猜你喜欢
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多