how to properly use math.pow java function?

TwistedMaze

here's what I'm trying to do: get two inputs from user and validate them. 1 is a random number between 1 and 20, the other is the times it should multiply itself over ( a number between 1 and 10 which I expressed through exponentiation)

what I don't understand - math.pow only works with doubles? Also, is it possible that the user inputs "wrong" values and instead of terminating, the program asks for inputs again?

I have this:

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();

}

it asks for the values but doesn't run properly(or, at all for that matter), i'm guessing I'm either using the wrong statements or wrong variable type. java newbie here. suggestions?

Atri

Math.pow accepts doubles and returns double as per the doc.

For your code to take new inputs when wrong numbers are entered, you can add a while(true) loop.

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;
    }
}

I have used break to end the loop when correct values are given, but you could get new inputs instead of breaking (as it seems from your code). You need to then have some other break condition otherwise it will be an infinite loop again.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related