Java做while while循环不循环

时间:2015-10-04 23:07:18

标签: java loops do-loops

我在使用while循环时遇到了一些麻烦。系统将打印出行并停止。我究竟做错了什么?谢谢你的时间!

Scanner keyboard = new Scanner(System.in);

    String answer;
    int inputNum = 1;
    int countOdd = 0;
    int countEven = 0;

    do{
        do{
            System.out.println("Please enter an interger. When you are finished, enter 0.");
            inputNum = keyboard.nextInt();

                while (inputNum % 2 == 0)
                    countOdd++;
                while (inputNum % 2 != 0)
                    countEven++;
        }while(inputNum != 0);


        System.out.println("Thank you. The amount of odd intergers you entered is " 
        + countOdd + ". The amount of even intergers you entered is " + countEven);


        System.out.println("Thank you. The amount of odd intergers you entered is " 
        + countOdd + ". The amount of even intergers you entered is " + countEven);

        System.out.println("Would you like to run this program again? (Y) (N)");
        answer = keyboard.nextLine();

    }while (answer.equals("Y"));

    System.out.println("Thank you!");
}

}

3 个答案:

答案 0 :(得分:4)

以下循环无法完成,因为#x内部未更改:

inputNum

您需要 while (inputNum % 2 == 0) countOdd++; while (inputNum % 2 != 0) countEven++; 语句而不是if

答案 1 :(得分:2)

您需要使用#!/bin/bash folders=$(find $1 -type d) #associative memory typeset -A Tab #max col iMaxCol=10 iLg=0 iCol=0 for fold in ${folders} do Tab[${iLg}_${iCol}]=${fold} iCol=$(( iCol + 1 )) if [ ${iCol} -eq ${iMaxCol} ] ; then iLg=$(( iLg + 1 )) iCol=0 fi done #Like Tab[0][0] echo ${Tab[0_0]} #Like Tab[0][9] echo ${Tab[0_9]} #Like Tab[1][5] echo ${Tab[1_5]} 更改while。逻辑if检查甚至不是奇数。但如果你故意反对它,那就好了。我应该改变它。

inputNum%2==0

答案 2 :(得分:1)

问题在于以下代码行

string = input("Enter a sting: ")
pos = int(input("Enter the position to be modified: "))

try:
    b = string.split()
    b[pos] = 'k'
    b = "".join(b)
    print(b)

except IndexError as e:
    if string == "":
        print("Error: Need to enter a valid string.")

    if pos not in range(len(string)):
        print("Error: Need to enter a valid position to be modified.")

您不会对while (inputNum % 2 == 0) countOdd++; while (inputNum % 2 != 0) countEven++; 条件使用while语句。而是使用这个

if