簡體   English   中英

Java for循環不會運行......?

[英]Java for loop won't run…?

我正在做家庭作業,而程序的關鍵循環給我帶來了麻煩。 我的老師告訴我,如果我使用while循環獲取一個反控制變量,她會取下積分,所以我很想把它弄好。

這就是我想要工作的東西,以及我內心的感受:

for ( int check = 0; check == value; check++ ) {
    int octal = getOctal();
    int decimal = convertOctal( octal );
    System.out.printf( "%d:%d", octal, decimal );
}

但是,此循環不會運行。 我嘗試使用while循環,它完美地工作!

int check = 0;
while ( check < value )
{
    int octal = getOctal();
    int decimal = convertOctal( octal );
    System.out.printf( "%d:%d", octal, decimal );
    check++;
}

以下是主要方法的其余部分:

public static void main ( String args[] )
{
    int value = getCount();

    while ( value < 0 )
    {
        System.out.print( "\nYou must enter a positive number" );
        value = getCount();
    }

    if ( value == 0 )
    {
        System.out.print( "\n\nNo numbers to convert.\n\n" );
    }
    else
    {   
        int check = 0;
        while ( check < value )
        {
            int octal = getOctal();
            int decimal = convertOctal( octal );
            System.out.printf( "%d:%d", octal, decimal );
            check++;
        }
    }
}

是的,這是一個八進制到十進制的轉換器。 我自己從頭開始編寫轉換器方法,並為此感到非常自豪。

編輯:我的問題是,這里有什么問題? EDIT part deux:感謝大家幫忙解決我的誤解。 繼續方法文檔!

for ( int check = 0; check == value; check++ )

這只會在check == value運行。 修改為:

for ( int check = 0; check < value; check++ )

嘗試for ( int check = 0; check <= value; check++ )而不是for ( int check = 0; check == value; check++ )

來自Oracle網站 (我的重點):

for語句提供了一種迭代一系列值的簡潔方法。 程序員經常將其稱為“for循環”,因為它反復循環直到滿足特定條件的方式。 for語句的一般形式可表示如下:

for (initialization; termination; increment) {
statement(s) 
} 

使用此版本的for語句時,請記住:

初始化表達式初始化循環; 循環開始時,它執行一次。

當終止表達式求值為false時,循環終止。

每次迭代循環后調用increment表達式; 這個表達式增加或減少一個值是完全可以接受的。

獲得與以下相同的效果:

int check = 0;
while (check < value) {
  // something
}

for應該是這樣的:

for (int check = 0; check < value; check++) {
  // something
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM