2016-03-25 4 views
2

ここに私がやろうとしていることがあります: ユーザーから2つの入力を取得し、それらを検証します。 1は1から20の間の乱数で、もう1つは掛け算するべき累乗(累乗によって表現した1から10までの数字)です。どのように適切にmath.pow Java関数を使用するには?

私が理解できないもの - math.powは二倍?また、ユーザーが「間違った」値を入力し、終了する代わりに、プログラムが入力を再度要求する可能性はありますか?

私はこれを持っている:

import java.util.Scanner; 

public class P01Multiplicador { 

public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    System.out.println("insert number and how many times it will multiply itself over"); 
    Scanner in = new Scanner(System.in); 
    int n = in.nextInt(); 
    int nReps = in.nextInt(); 

    if(n<1 || n>20 || nReps<1 || nReps>10){ 
     System.out.println("values are not accepted, please insert again"); 
    } 
    else{ 
     do Math.pow(n, nReps); 
     while(n>1 && n<20 && nReps>1 && nReps<20); 

    } 
    in.close(); 

} 

それが値を要求したが(あるいは、まったくそのことについては)、私は間違っている文または間違ったのいずれかを使用して私は推測している正常に実行されません。可変型。ここのjava初心者。提案?

+0

'math.powのみダブルスで動作します?' 'yesのユーザ入力は、「間違った」値、代わりに終了するのは、プログラムが入力を要求することも可能ですもう一度yes –

+2

あなたはMath.powリターンを割り当てていません。だから私はそれが永遠に実行されると思います。 "double power = Math.pow(n、nReps);"のようなやり方をして、whileステートメントで使用するか、nとnRepsの値を更新してください。 –

+2

これは無限ループです。 nReps' – QBrute

答えて

1

Math.powダブルスを受け入れ、docごとにダブル返しますが。

誤った番号を入力したときに新しい入力を行うコードには、while(true)というループを追加できます。

while(true){ 
    if(n<1 || n>20 || nReps<1 || nReps>10){ 
     System.out.println("values are not accepted, please insert again"); 
     n = in.nextInt(); 
     nReps = in.nextInt(); 
    } 
    else{ 
     System.out.println(Math.pow(n, nReps)); 
     break; 
    } 
} 

私は正しい値が与えられたときにループを終了するbreakを使用しているが、(それはあなたのコードから思えるよう)あなたの代わりに破壊の新しい入力を得ることができます。他のブレーク条件がなければ、無限ループに戻ります。あなたの主なメソッド内のコードの下

+0

は「while(true)」の提案を保持し、自分の調整を行いました。 – TwistedMaze

3

有効なコードになるようにコードを修正する必要があります。

Math.powは、入力に応じて大きな数字と小さな数字の両方を生成するため、倍音を使用します。例えばたとえ4^20でもintに収まりません。

あなたは、このようなMath.round(x)

3

何か使用することができますlongに結果を丸めるしたい場合:

boolean accepted = false; 
do{ 
System.out.println("insert number .... 

if(n<1 || n>20 || nReps<1 || nReps>10){ 
    System.out.println("values are not accepted, please insert again"); 
}else{ 
    accepted = true; 
} 
}while(!accepted) 
-1

使用

System.out.println("insert number and how many times it will multiply itself over"); 
    Scanner in = new Scanner(System.in); 
    int n = in.nextInt(); 
    int nReps = in.nextInt(); 

    while (true) { 
     if (n < 1 || n > 20 || nReps < 1 || nReps > 10) { 
      System.out.println("values are not accepted, please insert again"); 
      System.out.println("insert number and how many times it will multiply itself over"); 
      n = in.nextInt(); 
      nReps = in.nextInt(); 
     } else { 
      System.out.println("" + Math.pow(n, nReps)); 
      break; 
     } 

    } 
関連する問題