2016-04-28 12 views
0

一緒に追加したときに7で割り切れる2つの数字(1〜99)のランダムなセットを選択して表示するwhileループを作成します。ユーザーが「完了」と言うまで続行します。Loopの提案はありますか?

私はこれらの2つの乱数を7で割り切れるようにする方法がわかりません 私はif文を試しましたが、それでも動作しません。

これは私がこれまでに得たものである:

public static void main(String []args) 
{ 
    Scanner scan= new Scanner (System.in); 
    String answer="Yes"; 

    System.out.println("Run the program?"); 
    answer= scan.nextLine(); 


    while(!answer.equalsIgnoreCase("done")) 
    { 
     int a=1; 
     int b=1; 
     a=(int) (Math.random()*99) + 1; 
     b=(int) (Math.random()*99) + 1; 
     if ((a + b) % 7 == 0) 
     { 
      System.out.println(a + " + " + b + "= " +(a+b)); 
     } 

     System.out.println("Do you want to continue?"); 
     answer= scan.nextLine(); 
    } 

答えて

1

まずそれを読んで(および使用)する方が簡単ですので、私はRandom.nextInt(int)を好むだろう。次に、ba + bモジュロ7の結果で調整することができます(これは残りの部分です)。何かのように、

Random rand = new Random(); 
while (!answer.equalsIgnoreCase("done")) { 
    int a = 1 + rand.nextInt(99); 
    int b = 1 + rand.nextInt(99); 
    // Updated based on @JimGarrison's comment. 
    if (b < 7) { 
     b = 7 - a; 
    } else if (b > 93) { 
     b = 98 - a; 
    } else { 
     b -= (a + b) % 7; 
    } 
    System.out.println(a + " + " + b + " = " + (a + b)); 
    System.out.println("Do you want to continue?"); 
    answer = scan.nextLine(); 
} 
+1

初期ランダム生成の後に 'a == 2'と' b == 1 'となると、 'b'は' -1'に終わり、要件を満たさなくなります。無作為に選択された最初の「b」が「7」未満であればいつでも失敗する可能性があります。もう片方の問題( 'b> 93') –

+0

@JimGarrison私はエッジのケースを考慮していませんでした。ありがとう! –

0

ランダムなので、(a + b)%7!= = 0の場合は多くかかる場合があります。

だから私は、これは少し効率になると思う。

 Scanner scan = new Scanner(System.in); 
     String answer = "Yes"; 

     System.out.println("Run the program?"); 
     answer = scan.nextLine(); 
     int LIMIT = 99; 
     List<Integer> divisible7List = new ArrayList<Integer>(); 

     // Generate elements that divisible by 7 that less than 99 + 99 
     int count = 1; 
     int divisible7 = 7 * count; 
     int maxDivisible7 = LIMIT + LIMIT; 
     while (divisible7 < maxDivisible7) { 
      divisible7List.add(divisible7); 
      divisible7 = 7 * (++count); 
     } 

     int size = divisible7List.size(); 
     StringBuilder sb = new StringBuilder(); 
     Random rand = new Random(); 
     while (!answer.equalsIgnoreCase("done")) { 
      int idx = rand.nextInt(size - 1); 
      int sumab = divisible7List.get(idx); 
      int a = 1 + rand.nextInt(sumab); 
      int b = sumab - a; 

      sb.append(a); 
      sb.append(" + "); 
      sb.append(b); 
      sb.append(" = "); 
      sb.append(sumab); 
      System.out.println(sb.toString()); 
      sb.setLength(0); 
      System.out.println("Do you want to continue?"); 
      answer = scan.nextLine(); 
     } 

ちょうど必要性を事前に生成し、aとbを見つけ、あなたのニーズに合うB +待つために。

関連する問題