変数と型
変数は「型 変数名 = 値;」で宣言します。変更しない値にはfinalを使います。
型の例JAVA
String name = "Mity";
int age = 20;
double height = 170.5;
boolean student = true;
System.out.println(name + "さんは" + age + "歳です");実行結果OUTPUT
Mityさんは20歳ですキーボード入力
Scannerで1行を読み、Integer.parseInt()で整数へ変換します。
InputExample.javaJAVA
import java.util.Scanner;
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("年齢を入力してください: ");
int age = Integer.parseInt(scanner.nextLine());
System.out.println("来年は" + (age + 1) + "歳です");
}実行例OUTPUT
年齢を入力してください: 20
来年は21歳です条件分岐
if、else if、elseで処理を切り替えます。文字列の内容はequals()で比較します。
点数を判定JAVA
int score = 82;
if (score >= 80) {
System.out.println("合格(よくできました)");
} else if (score >= 60) {
System.out.println("合格");
} else {
System.out.println("再挑戦");
}実行結果OUTPUT
合格(よくできました)繰り返し
forは回数が分かる処理、whileは条件が真の間の処理に向きます。
for文JAVA
for (int i = 1; i <= 3; i++) {
System.out.println(i + "回目");
}for文の実行結果OUTPUT
1回目
2回目
3回目while文と制御JAVA
int count = 2;
while (count > 0) {
System.out.println("残り" + count);
count--;
}
for (int i = 1; i <= 5; i++) {
if (i == 2) continue;
if (i == 4) break;
System.out.println(i);
}while文と制御の実行結果OUTPUT
残り2
残り1
1
3while内で条件が変わらないと終了しません。breakは途中終了、continueは今回だけ飛ばします。