while文の書き方は以下です。
while(条件式) {
繰り返し処理
}
こちらはシンプルです。繰り返し処理
}
条件式が満たされている間は繰り返される。です。
例として以下のように書くことができます。
int index = 0; int pointArray[] = new int[5]; System.out.println("while開始"); while(index < pointArray.length) System.out.println("pointArray["+index+"] = " + pointArray[index]); index++; } System.out.println("while終了");
while開始
pointArray[0] = 0
pointArray[1] = 0
pointArray[2] = 0
pointArray[3] = 0
pointArray[4] = 0
while終了
上記の例では、while文の最後にindexの値を1増やしているがこれは絶対に欠かさないこと。pointArray[0] = 0
pointArray[1] = 0
pointArray[2] = 0
pointArray[3] = 0
pointArray[4] = 0
while終了
これが抜けると、いつまでも「index < pointArray.length」が満たされ続けるので、無限ループに突入します。
また、意図的に無限ループにしたい時は以下のようにwhile文の条件式に「true」と書いてもできます。
int index = 0; System.out.println("while開始"); while(true) { System.out.println(index); index++; }