how to properly use math.pow java function? - java

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?

You need to fix your code so it is valid code.
Math.pow uses doubles as it produces both large and tiny numbers depending on the inputs. e.g. even 4^20 will not fit in an int.
If you want to round the result to a long you can use Math.round(x)

Something like this:
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 )

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.

Use below code inside your main method
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;
}
}

Related

Product of Number input by user, program stops when user inputs 0

i want to make a program reads integers from the user one by one, multiply them and shows the product of the read integers. The loop for reading the integers
stops when the user presses 0. If the user enters a 0 as the first number, then user would not be able to provide any other numbers (Not adding the last 0 in the product). In this case, the program should display “No numbers entered!”
Heres my code right now
ProductNumbers.java
package L04b;
import java.lang.reflect.Array;
import java.util.Scanner;
public class ProductNumbers {
public static void main(String[] args) {
int num = -1;
boolean isValid = true;
int numbersEntered = 0;
int product = -1;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter number = ");
int curNum = scnr.nextInt();
if (curNum == 0)
break;
numbersEntered++;
product *= num;
}
if (numbersEntered == 0) {
System.out.println("No numbers entered!");
} else {
System.out.println(product);
}
}
}
I know this is completely wrong, i usually setup a template, try to figure out what needs to be changed, and go by that way, i also need to start thinking outside the box and learn the different functions, because i dont know how i would make it end if the first number entered is 0, and if the last number is 0, the program stops without multiplying that last 0 (so that the product doesnt end up being 0)... i need someone to guide me on how i could do this.
Heres a sample output of how i want it to work
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
0
No numbers entered!
and
This program reads a list of integers from the user
and shows the product of the read integers
Enter the number:
2
Enter the number:
-5
Enter the number:
8
Enter the number:
0
The product of the numbers is: -80
You have a nested for loop, why?
You only need the outer while loop that gets the user's input until the input is 0.Also this line:
product *= i;
multiplies i, the for loop's counter to product and not the user's input!
Later, at this line:
if (isValid = true)
you should replace = with ==, if you want to make a comparison, although this is simpler:
if (isValid)
Your code can be simplified to this:
int num = -1;
int product = 1;
int counter = 0;
Scanner scnr = new Scanner(System.in);
System.out.println(
"This program reads a list of integers from the user\r\n"
+ "and shows the product of the read integers");
while (num != 0) {
System.out.print("Enter a number: ");
num = scnr.nextInt();
scnr.nextLine();
if (num != 0) {
counter++;
product *= num;
System.out.println(product);
}
}
if (counter == 0)
System.out.println("No numbers entered");
else
System.out.println("Entered " + counter + " numbers with product: " + product);
One way to solve this is to utilize the break; keyword to escape from a loop, and then you can process the final result after the loop.
Something like this:
int numbersEntered = 0;
while (num != 0) {
int curNum = // read input
if (curNum == 0)
break;
numbersEntered++;
// do existing processing to compute the running total
}
if (numbersEntered == 0)
// print "No numbers entered!
else
// print the result
I think the key is to not try and do everything inside of the while loop. Think of it naturally "while the user is entering more numbers, ask for more numbers, then print the final result"

JAVA: if statement inside a for loop and exiting from a for loop

Good day guys, I am new in this. I am doing an assignment for my prog unit, so please bear with me.
So what I have to do is to write up a code that can input people's ages, from integers between 1 to 120 inclusive. The user then have to calculate the average age, and should be calculated as a real number. But the user has to input age values until the user enters 0, which is to stop the program then output the average. If the user enters an age that is invalid, then the program should continue to re-prompt the user until they enter a valid age.
So I did my part. I created a code and I come up with this:
public static void main(String[] args)
{
int ageValue = 0;
double getAge;
getAge = inputAge();
System.out.println("Average age is: " + getAge);
}
public static double inputAge()
{
int ageValue = 0;
double avgAge = 0;
Scanner sc = new Scanner(System.in);
for (int i = 1; i <= 120; i++)
{
System.out.println("Enter age");
ageValue += sc.nextInt();
avgAge = ageValue / (double) i;
if (ageValue == 0)
{
System.out.println("Average age is: " + avgAge);
System.exit(0);
}
while (ageValue < 0 || ageValue > 120)
{
System.out.println("Invalid input. Try again!");
ageValue = sc.nextInt();
}
}
return avgAge;
}
Now I laid down my code and I got my average formula somehow working. Now, the problem is that when I press 0, it doesn't prompt the "if" statement. However, when the first "Enter your age" prompt comes up and I pressed 0, the "if" statement worked. But for each iteration, the program won't let me execute the statement.
On the other hand, I am also struggling to figure out how to exit a loop without using break or System.exit() because that will give me zero marks. What I wanted is when I press 0, it should exit the loop and output the average, like what the task said.
I don't know if you guys can get it.. Is the code right? Am I on the right track? Am I missing something???
Cheers
You could consider a do while loop approach. This would allow your code to naturally run once, and exit once the user enters 0:
int ageValue = 0, numOfAges = 0, sumOfAges = 0;
do {
System.out.println("Enter age");
ageValue = sc.nextInt();
if (ageValue < 0 || ageValue > 120)
System.out.println("Bad value... try again");
else if (ageValue != 0) {
sumOfAges += ageValue;
numOfAges++;
}
} while (ageValue != 0);
return ((double)sumOfAges / numOfAges);
On the other hand, I am also struggling to figure out how to exit a loop without using break or System.exit() because that will give me zero marks.
You can have another condition in your for loop like this
boolean finished = false;
for (int i = 1; i <= 120 && finished == false; i++)
and replace
System.exit(0)
with
finished = true;
However, I would question why using "break" will score you zero marks. This is exactly the sort of scenario break was intended for.
you can try this approach.
i've corrected a bit the exit condition and the way averaging is done.
the "for" loop you show in your code is limiting the number of sample to 120, but the question don't say so, so i took the liberty to generalise you question to any number of sample to average.
first thing is you should look up "if-else" conditionnal structure, as that was the main point missing in your code.
https://en.wikipedia.org/wiki/Conditional_(computer_programming)
you can think the way the problem is expressed as :
calculate the average in a serie
the serie is keyboard inputted
when zero is inputted, exit the loop and return the current average
when any value out of bound [0,120] is inputted, give a message and continue the loop without changing anything to the serie
when any value inside the bound [1,119] is inputted add the value to the serie and recalculate the average
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
System.out.println("Final Average age is: "+inputAge());
}
private static double inputAge()
{
int ageValue=0;
double avgAge=0;
boolean shouldExit=false;
Scanner sc=new Scanner(System.in);
List<Integer> samples=new ArrayList<Integer>();
// loop until flag is true
while(!shouldExit)
{
System.out.println("Enter age");
ageValue=sc.nextInt();
if(ageValue==0)
{
shouldExit=true;
}
else if(ageValue<0||ageValue>120)
{
System.out.println("Invalid input. Try again!");
}
else
{
// add current input in the samples and calculate average over all the samples
samples.add(ageValue);
avgAge=getAvg(samples);
System.out.println("Current Average age is: "+avgAge);
}
}
sc.close();
return avgAge;
}
private static double getAvg(List<Integer> samples)
{
double avgAge=0;
for(Integer tmp:samples)
{
avgAge+=tmp;
}
return avgAge/(double) samples.size();
}
}

Making loops in order to test values [duplicate]

This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 7 years ago.
I need help making a loop that looks at each value from 1 to number-1.
Also how to test each value to see if it is a
divisor of number, and if it is, adding it to the sum.
This is what I have so far:
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Please enter a positive integer: ");
int n = input.nextInt();
while (n < 0) {
System.out.println(n + " is not positive.");
System.out.print("Please enter a positive integer: ");
n = input.nextInt();
}
}
You can use this as a starting block for your application:
package Testers;
import java.io.Console;
public class Application {
public static void main(String[] args)
{
Console console = System.console();
if (console == null)
{
System.err.println("No console.");
System.exit(1);
}
boolean keepRunning = true;
while (keepRunning)
{
String name = console.readLine("Type your positive integer");
try{
int integer = Integer.parseInt(name);
if(integer < 0){
System.out.println("You must specify a positive integer!");
}
for(int i = 1; i<integer; i++){
// our variable "i" is smaller than "integer". This will parse all the numbers between one and "integer" -1.
if(i % 2 == 0){
//"i" IS divisible by 2. Of course, you can change this value to what you want to change it to.
//Here you can add it to a sum
}else{
//"i" is not divisible by 2. Of course, you can change this value to what you want to change it to.
}
}
}catch(NumberFormatException e){
System.out.println("You must specify a positive integer!");
}
}
}
}
If you want to do something for a known number of times, it is mostly a good idea to use a for loop. If you want to do something for number 1 to n-1, the loop could look like
for(int i = 1; i < n; i++) { // do stuff }
Note that it starts counting from 1 and stops as soon as i is greater or equal than n.
In order to know whether a number, say n, is divisible by some number, say k, the modulo-operator % could be used. If n % k == 0 this means that n is divisible by k. With an if-statement this can be tested and when you have some sum variable you can add whatever you want to that variable to sum things up.
Hope that helps

How can you check user input validation in Java?

I'm making a simple program that asks the user to input five numbers between 0-19. I would like to add something (like an if statement) after every number to make sure it's within that range. If not, the program should say "please read instructions again" and will then System.exit(0). This is the piece of the code that is relevant:
System.out.println("Please enter 5 numbers between 0 and 19");
System.out.print("1st Number: ");
userNum1 = scan.nextInt();
System.out.print("2nd Number: ");
userNum2 = scan.nextInt();
System.out.print("3rd Number: ");
userNum3 = scan.nextInt();
System.out.print("4th Number: ");
userNum4 = scan.nextInt();
System.out.print("5th Number: ");
userNum5 = scan.nextInt();
Any help would be greatly appreciated.
You can put this after each of your inputs, but you might want to think about putting this logic into its own method, then you can reuse the code and just call it with something like validateInput(userNum1);.
Replace val with your actual variable names.
if (val < 0 || val > 19) {
System.out.println("please read the instructions again");
System.exit(0);
}
First of all, I would create a for-loop that iterates N times, with N being the number of numbers you want to ask for (in your case, 5). Imagine your example with 50 numbers; it would be very repetitive.
Then, when you get each number with scan.nextInt() within your for-loop, you can validate however you want:
if (userNum < 0 || userNum > 19) {
// print error message, and quit here
}
Also, instead of just exiting when they input a number outside the range, you could have your logic inside a while loop so that it re-prompts them for the numbers. This way the user doesn't have to restart the application. Something like:
boolean runApplication = true;
while(runApplication) {
// do your for-loop with user input scanning
}
Then set the runApplication flag as needed based on whether or not the user put in valid numbers.
This code will do the trick for you, i added some securities :
public static void main(String[] args) {
int count = 1;
Scanner scan = new Scanner(System.in);
List<Integer> myNumbers = new ArrayList<Integer>();
System.out.println("Please enter 5 numbers between 0 and 19");
do {
System.out.println("Enter Number "+count+" ");
if(scan.hasNextInt()){
int input = scan.nextInt();
if(input >= 0 && input <= 19){
myNumbers.add(input);
count++;
}else{
System.out.println("Please read instructions again");
System.exit(0);
}
}else{
scan.nextLine();
System.out.println("Enter a valid Integer value");
}
}while(count < 6);
/* NUMBERS */
System.out.println("\n/** MY NUMBERS **/\n");
for (Integer myNumber : myNumbers) {
System.out.println(myNumber);
}
}
Hope it helps
Since you already know how many numbers you want the user to input, I suggest you use a for loop. It makes your code more elegant and you can add as many more entries as you want by changing the end condition of the loop. The only reason it looks long is because number 1, 2, 3 all end in a different format i.e firST secoND thiRD, but the rest of the numbers all end with TH. This is why I had to implement some if else statements inside the loop.
To explain the code, every time it loops it first tells the user the count of the number he/she is entering. Then numEntry is updated every time the loop loops, therefore you do not need to assign multiple inputs to multiple variables. It is more efficient to update the same variable as you go on. If the input the user inputs is less than 0 OR it is more than 19, the system exits after an error message.
System.out.println("Please enter a number between 0 and 19");
Scanner scan = new Scanner(System.in);
for(int i = 1; i <=5; i++){
if(i == 1)
System.out.println("1st Number");
else if(i == 2)
System.out.println("2nd Number");
else if(i == 3)
System.out.println("3rd Number");
else
System.out.println(i + "th Number");
int numEntry = scan.nextInt();
if(numEntry < 0 || numEntry > 19){
System.out.println("Please read instructions again.");
System.exit(1);
}

Validate, inform if invalid, return to loop

I am having problems with this section of my code. The program asks for a couple inputs (name, ID, grade, etc.) and will then print the results back.
I decided to break away from the tutorial and have now been smacking my head on a proverbial wall -
Pseudocode for what I want here:
Ask user for grade between 9 and 12
If input is less than 9 or greater than 12, return failed message and -return to loop-
If input acceptable, continue to next question.
Current code is as follows:
do {
System.out.print("Grade (9-12): ");
while (!keyboard.hasNextInt()) {
System.out.printf("message saying you're wrong");
keyboard.next();
}
userGrade = keyboard.nextInt();
} while (userGrade >= 9 || userGrade <= 12);
Try with something like this:
boolean correct = true;
do {
System.out.print("Grade (9-12): ");
userGrade = keyboard.nextInt();
if (userGrade < 9 || userGrade > 12) {
correct = false;
System.out.println("message saying you're wrong");
} else {
correct = true;
}
} while (!correct);
I think the problem is on the logic...
Change
while (userGrade >= 9 || userGrade <= 12);
to:
while (userGrade >= 9 && userGrade <= 12);
The || accept anything higher and equal to 9 and below and equal to 12. The two condition make finally that any integer will be true in the condition.
You can split your task in smaller ones. For instance create helper methods which
will read from Scanner until it will find integer which then will be returned
public static int getInt(Scanner scanner, String errorMessage){
while (!scanner.hasNextInt()) {
System.out.println(errorMessage);
scanner.nextLine();
}
return scanner.nextInt();
}
or will check if number is in range (but that is just for readability)
public static boolean isInRange(int x, int start, int end){
return start <= x && x <= end;
}
So with this methods your code can look like
Scanner scanner = new Scanner(System.in);
int x;
System.out.println("Please enter a number in range 9-12:");
do {
x = getInt(scanner, "I said number. Please try again: ");
if (!isInRange(x, 9, 12))
System.out.println("I said number in range 9-12. Please try again: ");
} while (!isInRange(x, 9, 12));
System.out.println("your number is: " + x);

Categories

Resources