新・明解 Java 入門 演習 7-9, 7-10 解答
Hello, Terminal!swaponQです!
今回は演習 7-9, 7-10 に取り組んでいこうと思います。
- 演習 7-9
「正の整数値:」と表示してキーボードから正の整数値を読み込んで。その値を返却するメソッドreadPlusIntを作成せよ。0や負の値が入力されたら再入力させること。
import java.util.Scanner; class ex07_9 { static Scanner stdIn = new Scanner(System.in); static int readPlusInt() { int ans; do { System.out.print("正の整数値:" ); ans = stdIn.nextInt(); } while (ans < 1); return ans; } public static void main(String[] args) { System.out.println(readPlusInt()); } }
・実行結果
正の整数値:6 6
- 演習 7-10
List7-11を拡張して、以下の四つの問題をランダムに出題するプログラムを作成せよ。
import java.util.Random; import java.util.Scanner; class ex07_10 { static Scanner stdIn = new Scanner(System.in); static boolean confirmRetry() { int cont; do { System.out.print("もう一度?<Yes…1/No…0>:"); cont = stdIn.nextInt(); } while (cont != 0 && cont != 1); return cont == 1; } public static void main(String[] args) { Random rand = new Random(); System.out.println("暗算力トレーニング!!"); do { int x = rand.nextInt(900) + 100; int y = rand.nextInt(900) + 100; int z = rand.nextInt(900) + 100; while (true) { System.out.print(x + " + " + y + " + " + z + " = "); int k = stdIn.nextInt(); if (k == x + y + z) { break; } System.out.println("違いますよ!!"); } while (true) { System.out.print(x + " + " + y + " - " + z + " = "); int k = stdIn.nextInt(); if (k == x + y - z) { break; } System.out.println("違いますよ!!"); } while (true) { System.out.print(x + " - " + y + " + " + z + " = "); int k = stdIn.nextInt(); if (k == x - y + z) { break; } System.out.println("違いますよ!!"); } while (true) { System.out.print(x + " - " + y + " - " + z + " = "); int k = stdIn.nextInt(); if (k == x - y - z) { break; } System.out.println("違いますよ!!"); } } while (confirmRetry()); } }
・実行結果
暗算力トレーニング!! 513 + 469 + 669 = 1651 513 + 469 - 669 = 313 513 - 469 + 669 = 713 513 - 469 - 669 = -625 もう一度?<Yes…1/No…0>:0
今回は以上です。お疲れ様でした!
次回は演習 7-11, 7-12, 7-13, 7-14 です。
Goodbye, Terminal… swaponQでした!