キーワード辞典
物凄く乱暴なJava for全商1級+

登録日 14/09/22   更新日 16/10/14



物凄く乱暴なJavaに関する用語(基本文法)

詳しくは公式マニュアルをお読みください。
Javaって、こんな風にも書ける、とか、こうとも言う、とか、色々有るので、 以下は雰囲気だけのざっくりとした説明です。
作成中です。ミス有ったら後免。


反復処理


for()

{ と } の間で、条件が成り立つ間、繰り返しの処理をする。
繰り返したい回数が判っている時などによく使用する。
処理を行う前に( )の中の終了判断をするため、 場合によっては1度も処理を行わない場合も有り得る。


キーボードから入力した5つの値を加算する。エラー処理なし。
import java.util.Scanner;

// For_Sample.java			by Ryn	2016.10.15

public class For_Sample {
	public static void main(String[] args) {

		int total = 0;
		Scanner sc = new Scanner(System.in);

		for( int i = 0; i < 5; i++){
			total += sc.nextInt();
		}

		sc.close();

		System.out.print("合計は " + total + "です。\n");
	}
}

反復する処理が1文しかない場合は、{ }は省略出来る。
import java.util.Scanner;

// For_Sample.java			by Ryn	2016.10.15

public class For_Sample {
	public static void main(String[] args) {

		int total = 0;
		Scanner sc = new Scanner(System.in);

		for( int i = 0; i < 5; i++)
			total += sc.nextInt();

		sc.close();

		System.out.print("合計は " + total + "です。\n");
	}
}


while()

{ と } の間で、条件が成り立つ間、繰り返しの処理をする。
件数が不定なレコードを読み込むなど、繰り返したい回数が判っていない時などに使用する。
処理を行う前に( )の中の終了判断をするため、 場合によっては1度も処理を行わない場合も有り得る。


キーボードから入力した値を加算する。0で終了。エラー処理なし。
import java.util.Scanner;

// While_Sample.java			by Ryn	2016.10.15

public class While_Sample {
	public static void main(String[] args) {

		int total = 0, atai = 0;
		Scanner sc = new Scanner(System.in);

		while((atai = sc.nextInt()) != 0) {
			total += atai;
		}

		sc.close();

		System.out.print("合計は " + total + "です。\n");
	}
}

反復する処理が1文しかない場合は、{ }は省略出来る。
import java.util.Scanner;

// While_Sample.java			by Ryn	2016.10.15

public class While_Sample {
	public static void main(String[] args) {

		int total = 0, atai = 0;
		Scanner sc = new Scanner(System.in);

		while((atai = sc.nextInt()) != 0) 
			total += atai;

		sc.close();

		System.out.print("合計は " + total + "です。\n");
	}
}


do~while();

{ と } の間で、条件が成り立つ間、繰り返しの処理をする。
件数が不定なレコードを読み込むなど、繰り返したい回数が判っていない時などに使用する。
処理の後で終了判定をするので、必ず1回は処理をする。
while() の最後の ; に注意。


キーボードから入力した値を加算する。0で終了。エラー処理なし。
import java.util.Scanner;

// Do_Sample.java		by Ryn	2016.10.15

public class Do_Sample {
	public static void main(String[] args) {

		int total = 0, atai = 0;
		Scanner sc = new Scanner(System.in);

		do{
			total += atai;
		}while(( atai = sc.nextInt()) != 0 );

		sc.close();
		System.out.print("合計は " + total + "です。\n");
	}
}

反復する処理が1文しかない場合は、{ }は省略出来る。
import java.util.Scanner;

// Do_Sample.java		by Ryn	2016.10.15

public class Do_Sample {
	public static void main(String[] args) {

		int total = 0, atai = 0;
		Scanner sc = new Scanner(System.in);

		do
			total += atai;
		while(( atai = sc.nextInt()) != 0 );

		sc.close();
		System.out.print("合計は " + total + "です。\n");
	}
}




[ 黒板消しとチョーク受けの画像 ]