Discussion:
[問題] 同樣程式碼 執行結果怎麼會不一樣
(时间太久无法回复)
風雨同路共送呂布
2007-04-27 08:21:47 UTC
Permalink
class Miracle
{
public static void main(String args[])
{
int Graph[][]={{0,1,1,1,0,0,0,0,0,0,0,0,1},{1,0,1,1,0,0,0,0,0,0,0,0,0},
{1,1,0,1,0,0,0,0,0,0,0,0,0},{1,1,1,0,1,1,0,0,0,0,0,0,1},
{0,0,0,1,0,1,1,0,0,0,0,0,0},{0,0,0,1,1,0,1,1,1,0,0,0,0},
{0,0,0,0,1,1,0,1,0,0,0,0,0},{0,0,0,0,0,1,1,0,1,0,0,0,0},
{0,0,0,0,0,1,0,1,0,1,0,0,0},{0,0,0,0,0,0,0,0,1,0,1,0,0},
{0,0,0,0,0,0,0,0,0,1,0,1,0},{0,0,0,0,0,0,0,0,0,0,1,0,0},
{1,0,0,1,0,0,0,0,0,0,0,0,0}
};
//執行這段程式碼 會跑出ArrayIndexoutOfBoundsexception
/*int i,j;
for(i=0;i<13;i++)
{
for(j=0;j<13;j++);
System.out.print(Graph[i][j]);
System.out.println();
}
*/

//若採用這段程式碼 卻是順利執行
//但這兩段程式明明是一模一樣的 怎麼會結果差很多
//這可以算是奇蹟嗎? 還是這兩段程式有不同之處?希望有人能解惑 謝謝
int i,j;
for(i=0;i<13;i++)
{
for(j=0;j<13;j++)
System.out.print(Graph[i][j]);
System.out.println();
}

}
}

--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.139.145.85
風~
2007-04-27 08:45:02 UTC
Permalink
※ 引述《Happyboy101 (風雨同路共送呂布)》之銘言:
: class Miracle
: {
: public static void main(String args[])
: {
: int Graph[][]={{0,1,1,1,0,0,0,0,0,0,0,0,1},{1,0,1,1,0,0,0,0,0,0,0,0,0},
: {1,1,0,1,0,0,0,0,0,0,0,0,0},{1,1,1,0,1,1,0,0,0,0,0,0,1},
: {0,0,0,1,0,1,1,0,0,0,0,0,0},{0,0,0,1,1,0,1,1,1,0,0,0,0},
: {0,0,0,0,1,1,0,1,0,0,0,0,0},{0,0,0,0,0,1,1,0,1,0,0,0,0},
: {0,0,0,0,0,1,0,1,0,1,0,0,0},{0,0,0,0,0,0,0,0,1,0,1,0,0},
: {0,0,0,0,0,0,0,0,0,1,0,1,0},{0,0,0,0,0,0,0,0,0,0,1,0,0},
: {1,0,0,1,0,0,0,0,0,0,0,0,0}
: };
: //執行這段程式碼 會跑出ArrayIndexoutOfBoundsexception
: /*int i,j;
: for(i=0;i<13;i++)
: {
: for(j=0;j<13;j++);
^^^你這裡多了分號@@
: System.out.print(Graph[i][j]);
: System.out.println();
: }
: */
: //若採用這段程式碼 卻是順利執行
: //但這兩段程式明明是一模一樣的 怎麼會結果差很多
: //這可以算是奇蹟嗎? 還是這兩段程式有不同之處?希望有人能解惑 謝謝
: int i,j;
: for(i=0;i<13;i++)
: {
: for(j=0;j<13;j++)
: System.out.print(Graph[i][j]);
: System.out.println();
: }
: }
: }

--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 203.204.69.75
..
2007-04-28 10:33:49 UTC
Permalink
※ 引述《Happyboy101 (風雨同路共送呂布)》之銘言:
: class Miracle
: {
: public static void main(String args[])
: {
: int Graph[][]={{0,1,1,1,0,0,0,0,0,0,0,0,1},{1,0,1,1,0,0,0,0,0,0,0,0,0},
: {1,1,0,1,0,0,0,0,0,0,0,0,0},{1,1,1,0,1,1,0,0,0,0,0,0,1},
: {0,0,0,1,0,1,1,0,0,0,0,0,0},{0,0,0,1,1,0,1,1,1,0,0,0,0},
: {0,0,0,0,1,1,0,1,0,0,0,0,0},{0,0,0,0,0,1,1,0,1,0,0,0,0},
: {0,0,0,0,0,1,0,1,0,1,0,0,0},{0,0,0,0,0,0,0,0,1,0,1,0,0},
: {0,0,0,0,0,0,0,0,0,1,0,1,0},{0,0,0,0,0,0,0,0,0,0,1,0,0},
: {1,0,0,1,0,0,0,0,0,0,0,0,0}
: };
: //執行這段程式碼 會跑出ArrayIndexoutOfBoundsexception
產生exception的原因:
因為你的內層迴圈直接在最後加上分號,表示迴圈並沒有執行任何程式
就一直累加直到j=13才跳出迴圈,執行System.out.println(Graph[i][j])
因為j=13,而你index的合法範圍為0~12,所以產生了exception
以上,就是問題所在
: /*int i,j;
: for(i=0;i<13;i++)
: {
: for(j=0;j<13;j++); //這段程式碼是會產生exception的地方
: System.out.print(Graph[i][j]);
: System.out.println();
: }
: */
: //若採用這段程式碼 卻是順利執行
: //但這兩段程式明明是一模一樣的 怎麼會結果差很多
: //這可以算是奇蹟嗎? 還是這兩段程式有不同之處?希望有人能解惑 謝謝

--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 210.209.174.174

继续阅读narkive:
Loading...