Skip to content

Instantly share code, notes, and snippets.

@sezemiadmin
Last active March 28, 2021 23:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sezemiadmin/1a6dc5c7385728bac0ee7e2d9803bae0 to your computer and use it in GitHub Desktop.
Save sezemiadmin/1a6dc5c7385728bac0ee7e2d9803bae0 to your computer and use it in GitHub Desktop.
practice_java_programming
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello, world");
}
}
// サンプル1 入力、演算、出力
import java.util.Scanner;
public class Sample1 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
double a, b, wa, sa, seki, sho;
// キーボードから2つの数値を入力する
System.out.print("1つ目の値を入力してください = ");
a = scn.nextDouble();
System.out.print("2つ目の値を入力してください = ");
b = scn.nextDouble();
// 2つの数値の四則演算を行う
wa = a + b;
sa = a - b;
seki = a * b;
sho = a / b;
// 演算結果を画面に表示する
System.out.println("加算結果 = " + wa);
System.out.println("減算結果 = " + sa);
System.out.println("乗算結果 = " + seki);
System.out.println("除算結果 = " + sho);
}
}
// サンプル10 mainメソッドの引数と1次元配列
public class Sample10 {
public static void main(String[] args) {
int max, min, i, num;
// コマンドライン引数の中から最大値と最小値を求める
max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;
for (i = 0; i < args.length; i++) {
num = Integer.parseInt(args[i]);
if (max < num) {
max = num;
}
if (min > num) {
min = num;
}
}
// 最大値と最小値を表示する
System.out.println("最大値 = " + max);
System.out.println("最小値 = " + min);
}
}
// サンプル11 for文による多重ループと2次元配列
import java.util.Scanner;
public class Sample11 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String[][] table = {
{ "曜日", "1", "2", "3", "4", "5" },
{ "月(1)", "国語", "算数", "理科", "社会", "英語" },
{ "火(2)", "算数", "英語", "体育", "国語", "保健" },
{ "水(3)", "社会", "英語", "算数", "技家", "技家" },
{ "木(4)", "理科", "算数", "理科", "体育", "社会" },
{ "金(5)", "国語", "算数", "理科", "美術", "美術" },
{ "土(6)", "英語", "数学", "国語" }
};
int day, time;
// 時間割表全体を表示する
for (day = 0; day < table.length; day++) {
for (time = 0; time < table[day].length; time++) {
System.out.print(table[day][time] + "\t");
}
System.out.println();
}
System.out.println();
// 曜日と時間を指定して科目を表示する
System.out.print("曜日(月~土を1~6で指定) = ");
day = scn.nextInt();
System.out.print("時間(1~5で指定) = ");
time = scn.nextInt();
System.out.println("科目 = " + table[day][time]);
}
}
// サンプル12 拡張for文による繰り返し
public class Sample12 {
public static void main(String[] args) {
String[] fruit = { "リンゴ", "バナナ", "ミカン", "メロン", "イチゴ" };
String[][] pet = {
{ "いぬ", "ねこ", "うさぎ", "りす", "うま" },
{ "錦鯉", "金魚", "めだか", "亀" },
{ "インコ", "オウム", "ハト" },
};
// 拡張for文で1次元配列の要素を取り出す
for (String f : fruit) {
System.out.print(f + "\t");
}
System.out.println();
System.out.println();
// 拡張for文で2次元配列の要素を取り出す
for (String[] pArray : pet) {
for (String p : pArray) {
System.out.print(p + "\t");
}
System.out.println();
}
}
}
// サンプル13 メソッドの作成
import java.util.Scanner;
public class Sample13 {
// 台形の面積を求めるdaikeiメソッド
public static double daikei(double joutei, double katei, double takasa) {
double menseki;
menseki = (joutei + katei) * takasa / 2.0;
return menseki;
}
// daikeiメソッドを呼び出すmainメソッド
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
double a, b, c, ans;
// 台形の上底、下底、高さを入力する
System.out.print("上底を入力してください = ");
a = scn.nextDouble();
System.out.print("下底を入力してください = ");
b = scn.nextDouble();
System.out.print("高さを入力してください = ");
c = scn.nextDouble();
// daikei関数を呼び出して台形の面積を求める
ans = daikei(a, b, c);
// 台形の面積を表示する
System.out.println("面積 = " + ans);
}
}
// サンプル14 参照型
import java.util.Scanner;
public class Sample14 {
// 配列の値を表示するshowArrayメソッド
public static void showArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print("[" + a[i] + "]");
}
System.out.println();
}
// 指定された要素を入れ替えるswapArrayメソッド
public static void swapArray(int[] a, int pos1, int pos2) {
int temp;
temp = a[pos1];
a[pos1] = a[pos2];
a[pos2] = temp;
}
// showArrayメソッドとswapArrayメソッドを呼び出すmainメソッド
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int pos1, pos2;
// 入れ替え前の配列を表示する
showArray(a);
// 入れ替える位置を指定する
System.out.print("pos1 = ");
pos1 = scn.nextInt();
System.out.print("pos2 = ");
pos2 = scn.nextInt();
// pos1とpos2を入れ替える
swapArray(a, pos1, pos2);
// 入れ替え後の配列を表示する
showArray(a);
}
}
// サンプル15 例外処理
public class Sample15 {
public static void main(String[] args) {
int a, b, ans;
try {
a = Integer.parseInt(args[0]);
b = Integer.parseInt(args[1]);
ans = a / b;
System.out.println(ans);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("2つのパラメータを指定してください!");
}
catch (NumberFormatException e) {
System.out.println("2つの整数を入力してください!");
}
catch (ArithmeticException e) {
System.out.println("ゼロ除算が行われました!");
}
catch (Exception e) {
System.out.println("その他の例外が発生しました!");
}
}
}
// サンプル16 クラスの定義とインスタンスの生成
// 社員を表すEmployeeクラスの定義
class Employee {
private String name; // 名前を保持するフィールド
private int salary; // 給与を保持するフィールド
// フィールドの値を表示するメソッド
public void show() {
System.out.print("私の名前は、" + this.name + "です。");
System.out.println("私の給与は、" + this.salary + "円です。");
}
// コンストラクタ
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
}
// Employeeクラスをテストするクラス
public class Sample16 {
public static void main(String[] args) {
// Employeeクラスのインスタンスを2つ生成する
Employee tanaka = new Employee("田中一郎", 250000);
Employee suzuki = new Employee("鈴木花子", 300000);
// それぞれのインスタンスのshowメソッドを呼び出す
tanaka.show();
suzuki.show();
}
}
// サンプル17 メソッドのオーバーロード
// 社員を表すEmployeeクラスの定義
class Employee {
private String name; // 名前
private int salary; // 給与
// 引数のないメソッド(すべてのフィールドの値を表示する)
public void show() {
System.out.print("私の名前は、" + this.name + "です。");
System.out.println("私の給与は、" + this.salary + "円です。");
}
// 引数が1つあるメソッド(引数で指定したフィールドの値を表示する)
public void show(String fieldName) {
if (fieldName.equals("名前")) {
System.out.println("私の名前は、" + this.name + "です。");
}
else if (fieldName.equals("給与")) {
System.out.println("私の給与は、" + this.salary + "円です。");
}
else {
this.show();
}
}
// コンストラクタ
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
}
// Employeeクラスをテストするクラス
public class Sample17 {
public static void main(String[] args) {
// Employeeクラスのインスタンスを生成する
Employee tanaka = new Employee("田中一郎", 250000);
// 引数のないメソッドを呼び出す
tanaka.show();
// 引数が1つあるメソッドを呼び出す
tanaka.show("給与");
tanaka.show("名前");
tanaka.show("出身地");
}
}
// サンプル18 コンストラクタのオーバーロード
// 社員を表すEmployeeクラスの定義
class Employee {
private String name; // 名前
private int salary; // 給与
// フィールドの値を表示するメソッド
public void show() {
System.out.print("私の名前は、" + this.name + "です。");
System.out.println("私の給与は、" + this.salary + "円です。");
}
// 引数がないコンストラクタ
public Employee() {
this("未設定", 0);
}
// 引数が1つあるコンストラクタ(その1)
public Employee(String name) {
this(name, 0);
}
// 引数が1つあるコンストラクタ(その2)
public Employee(int salary) {
this("未設定", salary);
}
// 引数が2つあるコンストラクタ
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
}
// Employeeクラスをテストするクラス
public class Sample18 {
public static void main(String[] args) {
// Employeeクラスのインスタンスを生成する
Employee empA = new Employee();
Employee empB = new Employee("田中一郎");
Employee empC = new Employee(250000);
Employee empD = new Employee("鈴木花子", 300000);
// フィールドの値を表示する
empA.show();
empB.show();
empC.show();
empD.show();
}
}
// サンプル19 クラスメンバとインスタンスメンバ
// 社員を表すEmployeeクラスの定義
class Employee {
private static int number = 0; // 社員数
private String name; // 名前
private int salary; // 給与
// 名前と給与の値を表示するインスタンスメソッド
public void show() {
System.out.print("私の名前は、" + this.name + "です。");
System.out.println("私の給与は、" + this.salary + "円です。");
}
// コンストラクタ
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
Employee.number++;
}
// 社員数を表示するクラスメソッド
public static void showNumber() {
System.out.println("現在の社員数は、" + Employee.number + "人です。");
}
}
// Employeeクラスをテストするクラス
public class Sample19 {
public static void main(String[] args) {
// 初期状態の社員数を表示する
Employee.showNumber();
// 1つ目のインスタンス生成し、社員数を表示する
Employee tanaka = new Employee("田中一郎", 250000);
tanaka.show();
Employee.showNumber();
// 2つ目のインスタンス生成し、社員数を表示する
Employee suzuki = new Employee("鈴木花子", 300000);
suzuki.show();
Employee.showNumber();
}
}
// サンプル2 データ型と算術演算子
import java.util.Scanner;
public class Sample2 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
// 台形の面積を計算する
double jotei, katei, takasa, menseki;
System.out.print("上底を入力してください = ");
jotei = scn.nextDouble();
System.out.print("下底を入力してください = ");
katei = scn.nextDouble();
System.out.print("高さを入力してください = ");
takasa = scn.nextDouble();
menseki = (jotei + katei) * takasa / 2.0;
System.out.println("面積 = " + menseki);
System.out.println();
// お菓子の余りを求める
int okasi, kodomo, amari;
System.out.print("お菓子の数を入力してください = ");
okasi = scn.nextInt();
System.out.print("子供の人数を入力してください = ");
kodomo = scn.nextInt();
amari = okasi % kodomo;
System.out.println("余り = " + amari);
System.out.println();
// 残金の計算をする
int zankin, nyukin;
System.out.print("先月の残金を入力してください = ");
zankin = scn.nextInt();
System.out.print("今月の入金を入力してください = ");
nyukin = scn.nextInt();
zankin += nyukin;
System.out.println("更新後の残金 = " + zankin);
}
}
// サンプル20 クラスの継承とメソッドのオーバーライド
// 社員を表すEmployeeクラスの定義
class Employee {
protected String name; // 名前
protected int salary; // 給与
// フィールドの値を表示するメソッド
public void show() {
System.out.print("私の名前は、" + this.name + "です。");
System.out.println("私の給与は、" + this.salary + "円です。");
}
// コンストラクタ
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
}
// 管理者を表すManagerクラスの定義(Employeeクラスを継承する)
class Manager extends Employee {
private String post; // 役職名
// フィールドの値を表示するメソッド
public void show() {
System.out.print("私の役職は、" + this.post + "です。");
super.show();
}
// コンストラクタ
public Manager(String post, String name, int salary) {
super(name, salary);
this.post = post;
}
}
// Managerクラスをテストするクラス
public class Sample20 {
public static void main(String[] args) {
// Managerクラスのインスタンスを生成し、フィールドの値を表示する
Manager sato = new Manager("課長", "佐藤二郎", 500000);
sato.show();
}
}
// サンプル21 カプセル化とアクセサメソッド
// 社員を表すEmployeeクラスの定義
class Employee {
private String name; // 名前
private int salary; // 給与
// フィールドの値を表示するメソッド
public void show() {
System.out.print("私の名前は、" + this.name + "です。");
System.out.println("私の給与は、" + this.salary + "円です。");
}
// コンストラクタ
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
// 名前を書き込むメソッド
public void setName(String name) {
this.name = name;
}
// 名前を読み出すメソッド
public String getName() {
return this.name;
}
// 給与を書き込むメソッド
public void setSalary(int salary) {
// マイナスの給与は受け付けない
if (salary >= 0) {
this.salary = salary;
}
}
// 給与を読み出すメソッド
public int getSalary() {
return this.salary;
}
}
// Employeeクラスをテストするクラス
public class Sample21 {
public static void main(String[] args) {
// Employeeクラスのインスタンスを生成する
Employee emp = new Employee("未設定", 0);
// フィールドに適切な値を書き込む
emp.setName("田中一郎");
emp.setSalary(250000);
// フィールドの値を読み出す
System.out.println(emp.getName() + "さんの給与は、"
+ emp.getSalary() + "円です。");
// フィールドに不適切な値を書き込む
emp.setSalary(-100000);
// フィールドの値を表示する
emp.show();
}
}
// サンプル22 抽象クラスと多態性
// ペットを表すPetクラスの定義(抽象クラス)
abstract class Pet {
protected String name; // 名前
// 名前を表示するメソッド
public void showName() {
System.out.println(this.name);
}
// 鳴くメソッド(抽象メソッド)
public abstract void speak();
// コンストラクタ
public Pet(String name) {
this.name = name;
}
}
// 犬を表すDogクラスの定義
class Dog extends Pet {
// 鳴くメソッドの実装
public void speak() {
System.out.println("ワン!");
}
// コンストラクタ
public Dog(String name) {
super(name);
}
}
// 猫を表すCatクラスの定義
class Cat extends Pet {
// 鳴くメソッドの実装
public void speak() {
System.out.println("ニャン!");
}
// コンストラクタ
public Cat(String name) {
super(name);
}
}
// DogクラスとCatクラスをテストするクラス
public class Sample22 {
public static void main(String[] args) {
// Petクラスの配列を用意する
Pet[] p = new Pet[5];
// 配列にDogクラスとCatクラスのインスタンスを格納する
p[0] = new Dog("ポチ");
p[1] = new Cat("タマ");
p[2] = new Dog("シロ");
p[3] = new Cat("ミー");
p[4] = new Cat("ミケ");
// メソッドを呼び出す
for (int i = 0; i < p.length; i++) {
p[i].showName();
p[i].speak();
}
}
}
// サンプル23 インターフェイスと多態性
// 図形を表すFigureインターフェイスの定義
interface Figure {
// 描画メソッドの定義
void draw();
}
// 三角形を表すTriangleクラスの定義
class Triangle implements Figure {
// 描画メソッドの実装
public void draw() {
System.out.println("△");
}
}
// 四角形を表すRectangleクラスの定義
class Rectangle implements Figure {
// 描画メソッドの実装
public void draw() {
System.out.println("□");
}
}
// 円を表すCircleクラスの定義
class Circle implements Figure {
// 描画メソッドの実装
public void draw() {
System.out.println("○");
}
}
// 図形クラスをテストするクラス
public class Sample23 {
public static void main(String[] args) {
// Figureクラスの配列を用意する
Figure[] fig = new Figure[5];
// 配列に図形クラスのインスタンスを格納する
fig[0] = new Triangle();
fig[1] = new Rectangle();
fig[2] = new Circle();
fig[3] = new Rectangle();
fig[4] = new Triangle();
// メソッドを呼び出す
for (int i = 0; i < fig.length; i++) {
fig[i].draw();
}
}
}
// サンプル24 集約
// 社員を表すEmployeeクラスの定義
class Employee {
protected String name; // 名前
protected int salary; // 給与
// フィールドの値を表示するメソッド
public void show() {
System.out.print("私の名前は、" + this.name + "です。");
System.out.println("私の給与は、" + this.salary + "円です。");
}
// コンストラクタ
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
}
// 会社を表すCompanyクラスの定義(Employeeクラスを集約する)
class Company {
private String name; // 会社名
private int capital; // 資本金(万円)
private Employee[] emp; // 社員
// 会社の情報を表示するメソッド
public void showCompanyInfo() {
System.out.print("会社名は、" + this.name + "です。");
System.out.println("資本金は、" + this.capital + "万円です。");
}
// 社員の情報を表示するメソッド
public void showEmployeeInfo() {
for (int i = 0; i < this.emp.length; i++) {
this.emp[i].show();
}
}
// コンストラクタ
public Company(String name, int capital, Employee[] emp) {
this.name = name;
this.capital = capital;
this.emp = emp;
}
}
// Companyクラスをテストするクラス
public class Sample24 {
public static void main(String[] args) {
// Employeeクラスのインスタンスの配列を作成する
Employee[] emp = {
new Employee("田中一郎", 250000),
new Employee("鈴木花子", 300000),
new Employee("佐藤二郎", 500000)
};
// Companyクラスのインスタンスを作成する
Company cmp = new Company("翔泳商事", 1000, emp);
// 会社の情報を表示する
cmp.showCompanyInfo();
// 社員の情報を表示する
cmp.showEmployeeInfo();
}
}
// サンプル25 オブジェクトの比較とキャスト
// 点を表すPointクラス
class Point {
private int x; // x座標
private int y; // y座標
// equalsメソッドをオーバーライドする
public boolean equals(Object obj) {
return this.x == ((Point)obj).x && this.y == ((Point)obj).y;
}
// コンストラクタ
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
// Pointクラスをテストするクラス
public class Sample25 {
public static void main(String[] args) {
// 同じ座標でPointクラスのインスタンスを生成する
Point p1 = new Point(123, 456);
Point p2 = new Point(123, 456);
// p3が参照するインスタンスをp1と同じにする
Point p3 = p1;
// ==演算子で比較する
System.out.println("p1 == p2 は、" + (p1 == p2) + "です。");
System.out.println("p1 == p3 は、" + (p1 == p3) + "です。");
// equalsメソッドで比較する
System.out.println("p1.equals(p2) は、" + p1.equals(p2) + "です。");
System.out.println("p1.equals(p3) は、" + p1.equals(p3) + "です。");
}
}
// サンプル26 オブジェクトを引数に渡す、オブジェクトを戻り値として返す
// 点を表すPointクラス
class Point {
private int x; // x座標
private int y; // y座標
// equalsメソッドをオーバーライドする
public boolean equals(Object obj) {
return this.x == ((Point)obj).x && this.y == ((Point)obj).y;
}
// コンストラクタ
public Point(int x, int y) {
this.x = x;
this.y = y;
}
// 2つの点の座標を加えた点を生成するメソッド
public static Point add(Point p1, Point p2) {
return new Point(p1.x + p2.x, p1.y + p2.y);
}
// フィールドの値を表示するメソッド
public void show() {
System.out.println("x = " + this.x + ", y = " + this.y);
}
}
// Pointクラスをテストするクラス
public class Sample26 {
public static void main(String[] args) {
// 2つの点を生成する
Point p1 = new Point(10, 20);
Point p2 = new Point(30, 40);
// 2つの点の座標を加えた点を生成する
Point p3 = Point.add(p1, p2);
// 点の座標を表示する
p1.show();
p2.show();
p3.show();
}
}
// サンプル27 例外クラスの作成と例外のスロー
// 独自の例外クラスの定義
class InvalidateYearException extends Exception {
// コンストラクタ
public InvalidateYearException(String message) {
super(message);
}
}
// 便利なメソッドを提供するMyUtilityクラスの定義
class MyUtility {
// うるう年の判定をするメソッド
public static boolean isLeapYear(int year) throws InvalidateYearException {
// 西暦がマイナスの場合は例外をスローする
if (year < 0) {
throw new InvalidateYearException("西暦にマイナスが指定されました!");
}
// 例外がスローされた場合は、以下の処理が行われずにメソッドが終了する
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return true;
}
else {
return false;
}
}
}
// MyUtilityクラスをテストするクラス
public class Sample27 {
public static void main(String[] args) {
try {
System.out.println("2012年 = " + MyUtility.isLeapYear(2012));
System.out.println("2013年 = " + MyUtility.isLeapYear(2013));
System.out.println("2014年 = " + MyUtility.isLeapYear(2014));
System.out.println("-100年 = " + MyUtility.isLeapYear(-100));
}
catch (Exception e) {
System.out.println(e);
}
}
}
// サンプル28 ジェネリクスとボクシング
// 任意のデータ型で3次元座標を表すクラス
class Point3D<T> {
private T x; // x座標
private T y; // y座標
private T z; // z座標
// フィールドの値を表示するメソッド
public void show() {
System.out.println("x = " + this.x + ", y = " + this.y + ", z = " + this.z);
}
// コンストラクタ
public Point3D(T x, T y, T z) {
this.x = x;
this.y = y;
this.z = z;
}
}
// Point3Dクラスをテストするクラス
public class Sample28 {
public static void main(String[] args) {
// Integer型のPoint3Dクラスのインスタンスを生成する
// int型の10, 20, 30が、Integerクラスにボクシングされる
Point3D<Integer> intP = new Point3D<Integer>(10, 20, 30);
intP.show();
// Double型のPoint3Dクラスのインスタンスを生成する
// double型の1.23, 4.56, 7.89が、Doubleクラスにボクシングされる
Point3D<Double> dblP = new Point3D<Double>(1.23, 4.56, 7.89);
dblP.show();
}
}
// サンプル29 列挙型(enum)
// 列挙型Directionの定義
enum Direction {
North, West, South, East
}
// 列挙型Directionをテストするクラス
public class Sample29 {
public static void main(String[] args) {
// 道順を格納する
Direction[] dir = new Direction[5];
dir[0] = Direction.East;
dir[1] = Direction.North;
dir[2] = Direction.West;
dir[3] = Direction.North;
dir[4] = Direction.South;
// 道順を表示する
int n = dir.length - 1;
int i;
for (i = 0; i < n; i++) {
System.out.print(dir[i] + "->");
}
System.out.println(dir[i]);
}
}
// サンプル3 文字と文字列
public class Sample3 {
public static void main(String[] args) {
String s1, s2, s3;
char c1, c2, c3;
// 文字列を格納する
s1 = "ABCDEFG";
s2 = "あいうえお";
// 文字列を連結する
s3 = s1 + s2;
System.out.println(s3);
// 文字列の長さを表示する
System.out.println("s1の長さ = " + s1.length());
System.out.println("s2の長さ = " + s2.length());
System.out.println("s3の長さ = " + s3.length());
// 文字列の中から1文字を取得する
c1 = s1.charAt(0);
c2 = s2.charAt(3);
c3 = s3.charAt(8);
System.out.println("s1の先頭の文字 = " + c1);
System.out.println("s2の4番目の文字 = " + c2);
System.out.println("s3の9番目の文字 = " + c3);
}
}
// サンプル30 ガベージコレクション
// メモリを大量に消費するHighCapacityクラスの定義
class HighCapacity {
private static int instanceNum = 0; // 現在のインスタンス数
private int[] data; // 大容量の配列
// コンストラクタ
public HighCapacity() {
data = new int[100000];
instanceNum++;
}
// finalizeメソッドをオーバーライドする
protected void finalize() {
instanceNum--;
}
// 現在のインスタンス数を表示するメソッド
public static void showInstanceNum() {
System.out.println("現在のインスタンス数 = "
+ HighCapacity.instanceNum + "個");
}
}
// ガベージコレクションが行われていることを確認するクラス
public class Sample30 {
public static void main(String[] args) {
HighCapacity.showInstanceNum();
for (int i = 1; i <= 100; i++) {
HighCapacity obj = new HighCapacity();
HighCapacity.showInstanceNum();
}
HighCapacity.showInstanceNum();
}
}
//サンプル4 キャスト(型変換)
public class Sample4 {
public static void main(String[] args) {
double a, b, c;
int x, y, z;
char moji;
int code;
// double型の演算結果をint型の変数に格納する
a = 10.0;
b = 3.0;
z = (int)(a / b); // キャストが必要
System.out.println("z = " + z);
// int型の演算結果をdouble型の変数に格納する
x = 10;
y = 3;
c = (double)(x / y); // キャストは不要だが、キャストした方がよい
System.out.println("c = " + c);
// char型のデータをint型の変数に格納する(文字Aの文字コードを表示する)
moji = 'A';
code = (int)moji; // キャストは不要だが、キャストした方がよい
System.out.println("文字コード = " + code);
// int型のデータをchar型の変数に格納する(文字コード70の文字を表示する)
code = 70;
moji = (char)code; // キャストが必要
System.out.println("文字 = " + moji);
}
}
// サンプル5 if文による条件分岐と比較演算子
import java.util.Scanner;
public class Sample5 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int year;
// 西暦をキーボード入力する
System.out.print("西暦を入力してください = ");
year = scn.nextInt();
// うるう年かどうかを判定する
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println("うるう年です");
}
else {
System.out.println("うるう年ではありません。");
}
}
}
// サンプル6 switchによる条件分岐
import java.util.Scanner;
public class Sample6 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int month;
// 月をキーボード入力する
System.out.print("月を入力してください = ");
month = scn.nextInt();
// 季節を判定する
switch (month) {
case 3:
case 4:
case 5:
System.out.println("春です。");
break;
case 6:
case 7:
case 8:
System.out.println("夏です。");
break;
case 9:
case 10:
case 11:
System.out.println("秋です。");
break;
case 12:
case 1:
case 2:
System.out.println("冬です。");
break;
default:
System.out.println("入力エラーです!");
break;
}
}
}
// サンプル7 while文による繰り返し
import java.util.Scanner;
public class Sample7 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int a, b;
// 2つの整数をキーボード入力する
System.out.print("1つ目の整数を入力してください = ");
a = scn.nextInt();
System.out.print("2つ目の整数を入力してください = ");
b = scn.nextInt();
// 最大公約数を求める
while (a != b) {
if (a > b) {
a -= b;
}
else {
b -= a;
}
}
// 最大公約数を表示する
System.out.println("最大公約数 = " + a);
}
}
// サンプル8 do~while文による繰り返し
import java.util.Scanner;
public class Sample8 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int num, ans, count;
// 乱数で1~100の数を選ぶ
num = (int)(Math.random() * 100) + 1;
// 数を当てるまで繰り返す
count = 0;
do {
count++;
System.out.print("いくつだと思います? = ");
ans = scn.nextInt();
if (num > ans) {
System.out.println("もっと大きいです。");
}
else if (num < ans) {
System.out.println("もっと小さいです。");
}
} while (ans != num);
// 正解と、当てるまでの回数を表示する
System.out.println("正解は、" + num + "です。");
System.out.println("あなたは、" + count + "回で正解しました!");
}
}
// サンプル9 for文による繰り返しと1次元配列
import java.util.Scanner;
public class Sample9 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int[] score = new int[5];
int i, sum;
double ave;
// 配列にテストの得点を格納する
for (i = 0; i < score.length; i++) {
System.out.print("得点を入力してください = ");
score[i] = scn.nextInt();
}
// テストの得点の合計値を求める
sum = 0;
for (i = 0; i < score.length; i++) {
sum += score[i];
}
// テストの得点の平均値を求める
ave = sum / (double)score.length;
// テストの得点の平均値を表示する
System.out.println("平均値 = " + ave);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment