忽略变量中的初始化值

时间:2015-08-28 00:52:14

标签: java java.util.scanner

当我运行程序时,控制台忽略第一个整数输入,而是向sumOfPositive添加0。例如,在运行程序后,如果输入为:5,6,7,则sumOfPositive将等于13.但是如果我将sumOfPositive的初始值从0更改为2,则sumOfPositive将等于15.

那么我如何忽略sumOfPositive的初始化值并仅使用从输入中捕获的内容?

我的代码:

import java.util.Scanner;

public class Assignment2 {
public static void main(String[] args) {

    Scanner myScanner = new Scanner(System.in);     

    int sumOfPositive = 0;
    int sumOfOdd = 0;
    int minInt = 0;
    int numberOfInts = 0;
    int eachIntEntered = myScanner.nextInt();


    while (eachIntEntered != 0) {
        // if the number entered is not 0, assign it to numberOfInt

        eachIntEntered = myScanner.nextInt();

        // if the number entered does not equal 0, add one to numberOfInt
        // if the number entered is positive, add the number to sumOfPositive

        if (eachIntEntered > 0 ) {
        numberOfInts++;
        sumOfPositive += eachIntEntered;

        } 
        // if the number entered is odd, add the number to sumOfOdd

        if (eachIntEntered % 2 != 0) {
            sumOfOdd += eachIntEntered;
        }
        if (eachIntEntered < minInt) {
            minInt = eachIntEntered;
        }

    } // end of while loop

    System.out.println("The minimum integer is " + minInt);
    System.out.println("The sum of the positive integers is " + sumOfPositive);
    System.out.println("The sum of the odd integers is " + sumOfOdd);
    System.out.println("The count of the positive integers in the sequence is " + numberOfInts);

} // end of main function


} // end of class

1 个答案:

答案 0 :(得分:0)

您背靠背得到两个输入,但忽略第一个值。在您的while循环之外,您执行int eachIntEntered = myScanner.nextInt();并为其提供值,然后在while循环中执行eachIntEntered = myScanner.nextInt();,然后将之前的值添加到sumOfPositivesumOfOdd,这样您就可以了得到忽略输入的第一个值的行为。

解决此问题的一种方法是将行eachIntEntered = myScanner.nextInt();从循环顶部移到底部,这样第一次循环运行时就会使用eachIntEntered的初始值:

while (eachIntEntered != 0) {   
        // if the number entered does not equal 0, add one to numberOfInt
        // if the number entered is positive, add the number to sumOfPositive

        if (eachIntEntered > 0 ) {
        numberOfInts++;
        sumOfPositive += eachIntEntered;

        } 
        // if the number entered is odd, add the number to sumOfOdd

        if (eachIntEntered % 2 != 0) {
            sumOfOdd += eachIntEntered;
        }
        if (eachIntEntered < minInt) {
            minInt = eachIntEntered;
        }
        // if the number entered is not 0, assign it to numberOfInt

        eachIntEntered = myScanner.nextInt();

    } // end of while loop

没有办法&#34;忽略&#34; sumOfPositive的初始值。您无法在不知道其先前值的情况下添加到变量。将其设置为零似乎是您想要的正确行为。