How to calculate circumference with random numbers? - java

I need to print the circumference with Math.random() * Math.Pi; but i'm doing something wrong or missing something. Each random generated number equals the radius of the circle. My idea was to calculate Pi in the getRandomNumberInRange method but when I do, I get error:
Bad operand for type double
import java.util.Random;
import java.util.Scanner;
final static double PI = 3.141592564;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
//ask the player to enter a number less than or equal to 18 and higher to 9.
System.out.println(" Please enter a number less than or equal to 18 and above 9: ");
int random = sc.nextInt ();
//send error message if bad input
if (random < 9 || random > 18) {
System.out.println(" Error. Unauthorized entry . You need to enter a number less than or equal to 18 and above 9 ");
} else
//If the answer is yes , generate nine different random numbers from 0.
for (int i = 0; i < 9; i++) {
double surface = PI * (random * 2);
System.out.println(getRandomNumberInRange(9, 18) + " : " + " The circumference is : " + surface );
}}
The method called:
private static int getRandomNumberInRange(int min, int max) {
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}

You call getRandomNumberInRange() in the for loop, but don't assign it to anything, or use it.
This is probably closer to what you want:
for (int i = 0; i < 9; i++) {
int r2 = getRandomNumberInRange(9, 18);
double surface = PI * (r2 * 2);
System.out.println(r2 + " : " + " The circumference is : " + surface);
}

Related

How to speed up the efficiency of my code?

Essentially I'm trying to create a program that counts up the sum of the digits of the number, but every time a number that is over 1000 pops up, the digits don't add up correctly. I can't use % or division or multiplication in this program which makes it really hard imo. Requirements are that if the user inputs any integer, n, then I will have to be able to compute the sum of that number.
I've already tried doing x>=1000, x>=10000, and so forth a multitude of times but I realized that there must be some sort of way to do it faster without having to do it manually.
import java.util.Scanner;
public class Bonus {
public static void main(String[] args) {
int x;
int y=0;
int u=0;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number:");
x = s.nextInt();
int sum = 0;
{
while(x >= 100) {
x = x - 100;
y = y + 1;
}
while(x>=10) {
x = x - 10;
u = u + 1;
}
sum = y + u + x;
System.out.println("The sum of the digits in your number is" + " " + sum);
}
}
}
So if I type in 1,000 it displays 10. And if I type in 100,000 it displays 100. Any help is appreciated
Convert the number to a string, then iterate through each character in the string, adding its integer value to your sum.
int sum = 0;
x = s.nextInt();
for(char c : Integer.toString(x).toCharArray()) {
sum += Character.getNumericValue(c);
}

Java loop to ask 10 maths questions

Im currently trying to create a program thats asks the user to answer 10 multiplication questions and then output if the answer is correct or incorrect and then keep score of how many answers the user has got correct. My current code is shown below but I'm having trouble getting the score to increase as whenever I run it the score always stays at 1. I was wondering if anyone could help me with a solution to this
package Assignment1;
import java.util.Scanner;
import static java.lang.System.in;
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 11; i++) {
int number1 = (int) (Math.random() * 10) + 10;
int number2 = (int) (Math.random() * 10) + 10;
Scanner input = new Scanner(in);
System.out.print("What is " + number1 + " * " + number2 + " ?");
int answer = input.nextInt();
while ((number1 * number2) != answer) {
System.out.print("Incorrect");
answer = input.nextInt();
}
if ((number1 * number2) == answer) {
System.out.println("Correct");
int score = 0;
score = score + 1;
System.out.println("Score is currently: " + score);
}
}
}
}
In order to solve your problem, you need to understand the variable scope. The scope of a variable is in plain simple english: its lifecycle. And its lifecycle is defined between curly brackets, and by that I mean if the variable is created after "{", it only lives until "}". There are other cases, but don't mind them for now.
With this in mind, let's analyse what's the problem here. In your program you want the 'score' variable to live under all calculations and keep changing by adding the previous score to the new result, therefore producing a new score on every iteration. NOT to create a 'score' on every iteration.
Notice that you are creating the variable 'score' on every loop - resulting on its value being erased from memory (actually, its reference is what's being erased making its value lost in memory) at the end of every loop (when it dies) and a new 'score' variable is created over the next iteration.
So, I guess you'd know how to change your code now. You just change the creation of the variable 'score' to before the loop - so it's created before the "{" from the for loop instead of being erased and created on every iteration.
public class Main {
public static void main(String[] args) {
int score = 0;
for (int i = 0; i < 11; i++) {
int number1 = (int) (Math.random() * 10) + 10;
int number2 = (int) (Math.random() * 10) + 10;
Scanner input = new Scanner(in);
System.out.print("What is " + number1 + " * " + number2 + " ?");
int answer = input.nextInt();
while ((number1 * number2) != answer) {
System.out.print("Incorrect");
answer = input.nextInt();
}
if ((number1 * number2) == answer) {
System.out.println("Correct");
score = score + 1;
System.out.println("Score is currently: " + score);
}
}
}
}
You have declared score variable in the if block. So everytime there is a correct answer, the score is initialized with 0, then set to 1. Declare the score as an instance variable, or a local variable in main method (before the for loop)
If you want only 10 questions, the for loop should go from i = 1 to i < 11, not from i = 0. Also, you need to move the score outside the for loop, otherwise it will be declared as 0 every time the loop starts again. As Telmo Vaz correctly said, this is due to the scope of the variable. One other thing I noticed is that you can just use score++ to add 1 to score, instead of score = score + 1. I'll leave you to optimise your further.
import java.util.Scanner;
import static java.lang.System.in;
public class Main {
public static void main(String[] args) {
int score = 0;
for (int i = 1; i < 11; i++) { // 1 -> 10
int number1 = (int) (Math.random() * 10) + 10;
int number2 = (int) (Math.random() * 10) + 10;
Scanner input = new Scanner(in);
System.out.print("What is " + number1 + " * " + number2 + " ?");
int answer = input.nextInt();
while ((number1 * number2) != answer) {
System.out.print("Incorrect");
answer = input.nextInt();
}
if ((number1 * number2) == answer) {
System.out.println("Correct");
score++; // == (score = score + 1)
System.out.println("Score is currently: " + score);
}
}
}
}

Printing the amount of digits to the right and left of a decimal place

I'm having trouble getting the number of digits to the left of the decimal place. I've got the digits to the right of the decimal point working and able to print out but not to the left. Can anyone help?
import java.lang.Math;
import java.util.Scanner;
import java.text.DecimalFormat;
public class FormulaCalculation
{
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
double x;
//Prompt user for value.
System.out.print("Enter a value for x: ");
x = userInput.nextDouble();
double result = (Math.sqrt(7 * Math.pow(x, 4) - 5 * Math.pow(x, 2) + Math.abs(98 * x)) + 13) * (3 * Math.pow(x, 5) + 4 * Math.pow(x, 3) + 1);
String resultString = Double.toString(result);
int integerPlaces = resultString.indexOf('.');
int digitsLeft = resultString.length();
int digitsRight = resultString.length() - integerPlaces - 1;
//Output
System.out.println("Result: " + result);
System.out.println("# digits to left of the decimal point: " + digitsLeft);
System.out.println("# digits to right of the decimal point: " + digitsRight);
System.out.println("Formatted Result: ");
}
}
Either print integerPlaces (which is the number you seek) or assign it to digitsLeft. Something like this,
int integerPlaces = resultString.indexOf('.');
int digitsLeft = integerPlaces; // <-- from 0 to the '.'
// resultString.length();
int digitsRight = resultString.length() - integerPlaces - 1;
or eliminate digitsLeft altogether,
System.out.println("# digits to left of the decimal point: " + integerPlaces);

How do I calculate factorial and show working?

Hey I am really new to java and need a little help with this please.
I have some basic code that works fine it calculates the factor of a number lets say 5 and it gives the output answer of in this case "Factorial = 120.00"
That's great but I want it to give me the output like this "5 * 4 * 3 * 2 * 1 = 120.00" but I just can't figure out how to do it.
Thanks for any help
public static void main(String[] args)
{
Scanner kboard = new Scanner(System.in);
int nos1=0;
int total=1;
DecimalFormat df = new DecimalFormat("#.00");
System.out.print("Please enter number to factor ");
nos1 = kboard.nextInt();
for (int x=1;x<=nos1;x++)
{
total = total *x;
}
System.out.println("Factorial = "+df.format(total));
}
This will only get you part of the way there.
this code will print
1 * 2 * 3 * 4 * 5 * = 120
for (int x=1;x<=nos1;x++)
{
System.out.print(x + " * ");
total = total *x;
}
System.out.println(" = " + df.format(total));
I'll let you figure out a way to print it in the order you want and get rid of the last * at the end. there are a few ways.
String s = "";
for (int x = nos1; x >= 1; x--) {
total = total * x;
// print here it will work
if(!s.isEmpty())
s+="*";
s += x;
}
System.out.println(s + "=" + df.format(total));

Write a program which reads two non-negative integers 'x' and 'y' (where x < y) and then prints three random integers in the range x...y

import java.util.Scanner;
import java.util.Random;
public class Lab04b
{
public static void main(String []args)
{
Random generator = new Random ();
Scanner scan = new Scanner(System.in);
int num1;
int num2;
int num3;
System.out.println("Enter X:");
num1 = scan.nextInt();
System.out.println("Enter Y:");
num2 = scan.nextInt();
num3 = generator.nextInt(num2) + num1;
System.out.println("3 random integers in the range " + num1 + ".." + num2 + " are: " + num3);
}
}
I am stuck on how to get 3 random integers between the x and y range. Y being the biggest integer.
The trick is finding the difference between x and y. Here is what you need to do -
int diff = Math.abs(num1 - num2);
num3 = generator.nextInt(diff) + Math.min(num1, num2);
Just do it 3 times and you get your 3 numbers.
From the docs
nextInt(int n)
Returns a pseudorandom, uniformly distributed int value between 0
(inclusive) and the specified value (exclusive), drawn from this
random number generator's sequence.
so random.nextInt(Y) would give you numbers 0..Y, I guess you are missing how to get the lower bound correctly.
X + random.nextInt(Y-X) does the trick.
Read the documentation. The nextInt(n) function returns an Integer in [0, n). So, in your case, you can use the formula min + nextInt(max-min), which will give you a number in [min, max).
Random generator = new Random();
int max = (x >= y ? x : y);
int min = (x < y ? x : y);
int aRandomNumber = min + generator.nextInt(max-min);
Firstly have a loop which will run 3 times, to generate 3 random numbers(as you said you need 3 random numbers, but you're just generating only 1).
Next, the pattern you've used to generate a random number seems to be flawed. You can use the below type 1 pattern to accomplish that.
min + Math.random() * ((max - min) + 1));
Or this type 2 pattern
rand.nextInt((max - min) + 1) + min;
So you can do something like this:-
for (int i = 0; i < 3; i++) {
// Type 1
num3 = num1 + (int)(Math.random() * ((num2 - num1) + 1));
// Type 2
// num3 = generator.nextInt((num2 - num1) + 1) + num1;
System.out.println("3 random integers in the range " + num1 + ".." + num2 + " are: " + num3);
}
P.S:- You need to first determine the max and min, yourself. I've just given the pattern and a sample.
import java.util.Scanner;
public class GenerateRandomX_Y_numbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the numbers x and y: ");
int x = Math.abs(sc.nextInt()), y = Math.abs(sc.nextInt());//we need //non-negative integers, that is why we use here Math.abs. which means the //absolute value
print3RandomNumbers_between_x_and_y(x, y);
}
public static void print3RandomNumbers_between_x_and_y(int x, int y) {//here //I create a method with void type that takes two int inputs
boolean isTrue = (x < y);//according to our conditions X should less //than Y
if (isTrue) {//if the condition is true do => generate three int in the //range x .... y
int rand1 = (int) (Math.random() * (y - x) + 1);// y - x means our //range, we then multiply this substraction by Math.random()
int rand2 = (int) (Math.random() * (y - x) + 1);//the productof this //multiplication we cast to int type that is why we have
int rand3 = (int) (Math.random() * (y - x) + 1);//(int) before //(Math.random() * (y - x));
System.out.println("rand1 = " + rand1);//
System.out.println("rand2 = " + rand2);//
System.out.println("rand3 = " + rand3);//here print our result
} else
System.out.println("Error input: X should be less than Y. Try it again!");//if the condition is not true, i mean if x is not less than or equal //to Y, print this message
}
}

Categories

Resources