Java 一方のクラスで乱数を発生させ、もう一方のクラスで使用する方法

実現したいこと

オブジェクト指向を理解し、BigOrSmall(与えられた数字が、次に表示される数字より大きいか小さいか当てるゲーム)を実装したい

発生している問題・分からないこと

1つのクラスで乱数を発生させ、そのクラスで作成した変数をほかのクラスで回す方法がわかりません。

[現状]
RandomNumberGenerator.javaで生成した変数now,nextをBigOrSmall.javaにもってきてwhile文でまわしゲームを何回戦か行って10回でゲームを終わらせるように実装中。
しかし、while文の2回目からも1回目と同じ乱数(現在の数値、次の数値のところ)(変数名now,next)になってしまい初期化して再設定するためにはどうすればいいか困っています。

[エラーの例]
Big or Small をプレイします。
残りプレイ回数:10
スコア:0
現在の数値:9
次の数値は Big or Small?(Big: 0 Small: 1)
1
あなたの答え:Small
Small現在の数値:9 次の数値:1
当たり!
残りプレイ回数:9
スコア:100
現在の数値:9
次の数値は Big or Small?(Big: 0 Small: 1)
1
あなたの答え:Small
Small現在の数値:9 次の数値:1
当たり!
残りプレイ回数:8
スコア:300
現在の数値:9
次の数値は Big or Small?(Big: 0 Small: 1)

助言をいただければ幸いです。よろしくお願いいたします。

該当のソースコード

java

1import java.util.Random;2 3public class RandomNumberGenerator extends BigOrSmall {4 Random random = new Random();5 int now = random.nextInt(9)+1;6 int next = random.nextInt(9)+1;7 8 9 }10

java

1public void introduce() {2 RandomNumberGenerator random = new RandomNumberGenerator();3 4 while (playtimes != 0) {5 System.out.println("残りプレイ回数:" + this.playtimes);6 System.out.println("スコア:" + this.score);7 8 System.out.println("現在の数値:" + random.now);9 System.out.println("次の数値は Big or Small?(Big: 0 Small: 1)");10 int check =0;11 int yourselect =0;12 while (check != 1) {13 yourselect = scanner.nextInt();14 try {15 if (yourselect < 0 || yourselect > 1) {16 throw new NumberOutOfRangeException("0または1で入力してください");17 }else {18 check=1;19 }20 21 } catch (InputMismatchException e) {22 System.out.println("不正な入力です。");23 } catch (NumberOutOfRangeException e) {24 // TODO 自動生成された catch ブロック25 e.printStackTrace();26 }27 }28 29 if (yourselect == 0) {30 this.bigorsmall = "Big ";31 } else {32 this.bigorsmall = "Small ";33 }34 35 if (random.now < random.next) {36 this.answer = "Big";37 } else if (random.now > random.next) {38 this.answer = "Small";39 }40 41 System.out.println("あなたの答え:" + this.bigorsmall);42 if (random.now == random.next) {43 System.out.println("Draw!");44 } else if (random.now < random.next && yourselect == 0 ||45 random.now > random.next && yourselect == 1) {46 System.out.print(this.answer);47 System.out.print("現在の数値:" + random.now);48 System.out.println(" 次の数値:" + random.next);49 System.out.println("当たり!");50 this.winCount++;51 this.score += (this.winCount * 100);52 this.playtimes--;53 } else {54 System.out.print(this.answer);55 System.out.print("現在の数値:" + random.now);56 System.out.println("次の数値:" + random.next);57 System.out.println("はずれ!");58 this.winCount = 0;59 this.playtimes--;60 }61 }

試したこと・調べたこと

上記の詳細・結果

ゲッターとセッターのことなど無知ゆえに調べて改善してみたりしましたが解決に至らませんでした。

補足

特になし

コメントを投稿

0 コメント