Java 忽略变量中的初始化值

Java 忽略变量中的初始化值,java,java.util.scanner,Java,Java.util.scanner,当我运行程序时,控制台将忽略第一个整数输入,而是将0添加到sumOfPositive。例如,在运行程序后,如果输入为:5、6、7,则sumOfPositive将等于13。但是如果我把sumOfPositive的初始值从0改为2,那么sumOfPositive将等于15 那么,我如何忽略sumOfPositive的初始化值,而只处理从输入中捕获的内容呢 我的代码: import java.util.Scanner; public class Assignment2 { public static

当我运行程序时,控制台将忽略第一个整数输入,而是将0添加到sumOfPositive。例如,在运行程序后,如果输入为: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

您将获得两个背对背的输入,但忽略第一个值。在while循环之外,您可以int eachintered=myScanner.nextInt;然后在while循环中执行eaccentered=myScanner.nextInt;在将上一个值添加到sumofopositive或sumOfOdd之前,您会得到忽略输入的第一个值的行为

解决此问题的一种方法是移动行eaccentered=myScanner.nextInt;从循环的顶部到底部,以便第一次运行循环时使用每个中心的初始值:


没有办法忽略sumOfPositive的初始值。如果不知道变量的前一个值是什么,则无法将其添加到变量中。将其设置为零似乎是您想要的正确行为。

在循环之前读取第一个数字。计算机正按照你说的做着。忽略sumOfPositive的初始化值,只处理从输入中捕获的内容,这是什么意思?我认为你的初始化不是一个好的做法,因为如果值为-1,可能是人键入的第一个数字是0,但是程序将已经在循环中。第二个是我要说的,这是一个很好的例子;
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