JAvaシロまとめ1--ループ文

16360 ワード

do-whileループ文


フォーマットdo{}while(判断条件);
whileループ文とdo-whileループ文の違い:whileループ文は、先に判断した後に実行するループ文do-while文は先に実行し、後で判断する.条件が満たされているかどうかにかかわらず、少なくとも1回実行されます.
public class day04_do_while  {
	public static void main(String args[]) {
		// HELLO;
		 int a=0;
		 
		do {
			System.out.print("HELLO!");
			a++;
		}while(a<5);
		}
		}

do-whileを用いて1~100偶数の総和を計算する
public class day04_do_while  {
	public static void main(String args[]) {
//  do-while 1-100 
		int num=0;
		int sum=0;
		do {
			if(num%2==0) {
			sum+=num;}
			num++;
		}while(num<101 );
		System.out.print(sum);
	}

}


whileループ文


書式設定
 while( ){}

whileループ文で注意すべき点:1.whileループ文は、一般に、1つの変数によってループ回数を制御する.whileループ文のループ体コードは1つの文しかない場合は括弧を省略できますが、省略はお勧めしません.
public class day04_for  {
	public static void main(String args[]) {
		// : 5 HELLO!
        int a=0;
		while(a<5) {
			System.out.print("HELLO!");
			a++;	
		}
	}
	}
// :HELLO!HELLO!HELLO!HELLO!HELLO!
import java.util.*;
public class day04_while  {
	public static void main(String[] args){
		Random random = new Random();
		int randomNum =random.nextInt(11);// 1~10 
		Scanner scanner = new Scanner(System.in);
		while(true) {
			System.out.println(" :");
			int guess =scanner.nextInt();
			if(guess>randomNum) {
				System.out.println(" !");
			}else if(guess<randomNum) {
				System.out.println(" !");
			}else {
				System.out.println("right!");
				break;
		}
	}
}
}

forループ文


書式設定
  for( ; ; ){}

**forループ文注意事項:**1:for{;;この書き方は、while(true)に相当するデッドループ文です.2:forループ文の初期化文は一度しか実行されず、最初のループのときに実行されるだけです.3:forループ文のループ体文が1文しかない場合は、括弧を省略して書かないことができますが、省略はお勧めしません.
public class day04_for  {
	public static void main(String args[]) {
		// : 5 HELLO!
		for(int count=0;count<5;count++) {
			System.out.print("HELLO!");	
		}
	}
	}

需要:コンソールに5行5列の長方形を印刷する
public class day04_for  {
	public static void main(String args[]) {
		for(int a=0;a<5;a++) {
			System.out.println("*****");
		} 
		}
	}
/* :
*****
*****
*****
*****
*****
*/

コンソールに直角三角形を印刷
public class day04_for  {
	public static void main(String args[]) {
		for(int a=0;a<5;a++) {  // 
			for(int j=0;j<=a;j++) {  // 
				System.out.print("*");
			}
			System.out.println();// 
		}
	}
	}
/*
 :
*
**
***
****
*****
 */