虽然循环甚至计数

时间:2014-11-02 17:46:41

标签: java while-loop

我的问题如下。如果我输入数字2,则代码将其计为奇数。

剩余2/2 = 0因此错误没有意义。

以下是该计划:

import java.util.Scanner;

public class Ohjelma {

public static void main(String[] args) {

    // Tänne voit kirjoittaa ohjelmakoodia. Ohjelmasi voit ajaa
    // valitsemalla menusta Run->Run File tai painamalla Shift+F6
    Scanner reader = new Scanner(System.in);
    System.out.println("Type numbers: ");
    int number = Integer.parseInt(reader.nextLine());
    int sum = 0;
    int many = 0;
    double average = 0;
    int even = 0;
    int odd = 0;

    while (number != -1) {
        System.out.println("Type numbers: ");
        sum = sum + number;
        number = Integer.parseInt(reader.nextLine());
        many++;
        average = (double)sum / many;
        if (number%2 == 0) {
            even++;
        } else {
            odd++;
        }
    }

    System.out.println("Thank you and see you later!");
    System.out.println("The sum is " + sum);
    System.out.println("How many numbers: " + many);
    System.out.println("Average: " + average);
    System.out.println("Even numbers: " + even);
    System.out.println("Odd numbers: " + odd);

2 个答案:

答案 0 :(得分:1)

主要问题是,对于程序的关键部分,除了将其添加到正在运行的sum之外,它在很大程度上忽略了第一个输入。你想像这样重铸它:

Scanner reader = new Scanner(System.in);
int sum = 0;
int many = 0;
double average = 0;
int even = 0;
int odd = 0;

do {
    System.out.println("Type numbers: ");
    number = Integer.parseInt(reader.nextLine());
    if (number == -1)
        break;
    sum = sum + number;
    many++;
    average = (double)sum / many;
    if (number%2 == 0) {
        even++;
    } else {
        odd++;
    }
} while (true);

这肯定会正确处理偶数和奇数。

答案 1 :(得分:0)

在检查number是否为奇数并且-1为奇数之前,您的代码会将第二行输入读入number