Java while循环,直到用户输入值0

时间:2015-02-01 06:08:02

标签: java

创建一个继续读取用户输入值的while循环时遇到问题,直到输入值为0。然后计算所有值的平均值并在最后打印。这是我的编码的一部分,但这是不正确的。只是告诉你我认识问题的方式。

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String inputValues;

int sum = 0;
double average;

inputValues = input.readLine();
String[] intValues = inputValues.split("\\s+");


// This is incorrect but this is the idea I am looking for
while(intValues != 0) {       
    sum += Integer.parseInt(intValues[i]);
}

// Here the average is calculated as a double, and printed below. 
average = Double.parseDouble(sum / intValues.length);
System.out.print(average);

3 个答案:

答案 0 :(得分:1)

您可能想在此处尝试Scanner

Scanner scanner = new Scanner(System.in);
while(scanner.hasNextInt()) {
  int num = scanner.nextInt();
  if (num == 0)
    break;

  sum += num;
  count += 1;
}

System.out.println("Average: " + sum/count);

对于BufferedReader案例:

int i = 0;
while(intValues[i] != 0) {// assuming all the number were entered in one line with space as delimiter    
    sum += Integer.parseInt(intValues[i++]);
}

System.out.println("Average: " + sum/intValues.length);

答案 1 :(得分:0)

您可以先使用Scanner类,这样您就可以处理输入,例如......

Scanner input = new Scanner(System.in);
int sum = 0;
boolean exit = false;
do {
    String input = scanner.nextLine();
    Scanner check = new Scanner(input);
    if (check.hasNextInt()) {
        int value = check.nextInt();
        if (value == 0) {
            exit = true;
        } else {
            sum += value;
        }
    }
} while (!exit);

hasNextInt避免了Integer.parseInt在您尝试解析非数值时可能产生的异常。

您还可以使用while (check.hasNextInt()) {...循环来自单行输入的多个输入值...

您可以查看Scanner here

的文档

如果您希望继续使用BufferedReader,您可以使用一些逻辑......

BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

int sum = 0;
int count = 0;
double average;

try {
    boolean exit = false;
    do {
        System.out.print(">> ");
        String inputValues = input.readLine();
        String[] intValues = inputValues.split("\\s+");
        for (String value : intValues) {
            if ("0".equals(value.trim())) {
                exit = true;
                break;
            } else {
                count++;
                System.out.println(value);
                sum += Integer.parseInt(value);
            }
        }
    } while (!exit);

    System.out.println(sum + " / " + count);
    average = (double) sum / (double) count;
    System.out.print(average);
} catch (IOException exp) {
    exp.printStackTrace();
} catch (NumberFormatException exp) {
    exp.printStackTrace();
}

答案 2 :(得分:0)

试试这个

Boolean flag=true;
int counte=0;
while(flag)
{
          inputValues = input.readLine();
          if(Integer.parseInt(inputValues)==0)
          {
                flag=false;
                continue;
           }
         counter++; // used to take avarage
         sum+=Integer.parseInt(inputValues);
 }

After Loop完成后计算 avarage

相关问题