How do I calculate factorial and show working? - java

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

Related

Balut dice game Java

I'm making a game for an extra assignment for my college and I have to create a dice game known as "balut" I'm having some issues with assigning values to an array, and having the dice values stored within this array.
I'm in week 9 of 11 of my course we've covered arrays and methods however this is a new concept for me. The goal is as follows:
Balut = all five dice have the same number.
Straight = a total of 15 Or 20.
Sixes = 1 or more sixes.
Fives = 1 or more fives.
Fours = 1 or more fours.
10 rounds.
Total scoring of categories.
total of scores.
If no category is met "none" is printed.
I've put at least 14 hours into this and it was intended to be a 6 to 8 hour program and I still am struggling, questioning if I have the intelligence for the course and am hoping someone here can explain what I'm doing wrong or even what I should be studying.
I've tried creating a single array and assigning all dice values to this array, I run into the problem of when it comes to comparing the values I don't know how to do dice 1 == dice 2 == dice 3 etc.
I've then attempted to make 5 arrays 1 for each dice and use the compare array method which again I can only seem to get it to compare 2 arrays or variables I can't get it to compare all 5 like I'm attempting.
public static void main(String[] args) {
int[] Dicearraytotal1 = new int[10];
int[] Dicearraytotal2 = new int[10];
int[] Dicearraytotal3 = new int[10];
int[] Dicearraytotal4 = new int[10];
int[] Dicearraytotal5 = new int[10];
for (int i = 0; i < Dicearraytotal1.length; i++) {
Integer dice1 = (int) (Math.random() * 6 + 1);
Integer dice1val = dice1;
Integer dice2 = (int) (Math.random() * 6 + 1);
Integer dice2val = dice2;
Integer dice3 = (int) (Math.random() * 6 + 1);
Integer dice3val = dice3;
Integer dice4 = (int) (Math.random() * 6 + 1);
Integer dice4val = dice4;
Integer dice5 = (int) (Math.random() * 6 + 1);
Integer dice5val = dice5;
Dicearraytotal1[i] = (dice1val);
Dicearraytotal2[i] = (dice2val);
Dicearraytotal3[i] = (dice3val);
Dicearraytotal4[i] = (dice4val);
Dicearraytotal5[i] = (dice5val);
Integer total = (dice1val+dice2val+dice3val+dice4val+dice5val);
System.out.println("Total Of Numbers Generated1: " + Arrays.toString(Dicearraytotal1));
System.out.println("Total Of Numbers Generated2: " + Arrays.toString(Dicearraytotal2));
System.out.println("Total Of Numbers Generated3: " + Arrays.toString(Dicearraytotal3));
System.out.println("Total Of Numbers Generated4: " + Arrays.toString(Dicearraytotal4));
System.out.println("Total Of Numbers Generated5: " + Arrays.toString(Dicearraytotal5));
System.out.println("Total: " + total);
You are missing an end bracket to stop the for loop, so I assume you were attempting to print the arrays each iteration of the loop. I cleaned up your code a lot and you should take note on some of the changes in order to organize your code better which will make it easier to understand.
public static void main(String[] args) {
int[] diceArrayTotal1 = new int[10];
int[] diceArrayTotal2 = new int[10];
int[] diceArrayTotal3 = new int[10];
int[] diceArrayTotal4 = new int[10];
int[] diceArrayTotal5 = new int[10];
int[] totals = new int[10];
for (int i = 0; i < diceArrayTotal1.length; i++) {
diceArrayTotal1[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal2[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal3[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal4[i] = (int) (Math.random() * 6 + 1);
diceArrayTotal5[i] = (int) (Math.random() * 6 + 1);
totals[i] = (diceArrayTotal1[i] + diceArrayTotal2[i] + diceArrayTotal3[i] + diceArrayTotal4[i] + diceArrayTotal5[i]);
}
System.out.println("Total Of Numbers Generated1: " + Arrays.toString(diceArrayTotal1));
System.out.println("Total Of Numbers Generated2: " + Arrays.toString(diceArrayTotal2));
System.out.println("Total Of Numbers Generated3: " + Arrays.toString(diceArrayTotal3));
System.out.println("Total Of Numbers Generated4: " + Arrays.toString(diceArrayTotal4));
System.out.println("Total Of Numbers Generated5: " + Arrays.toString(diceArrayTotal5));
System.out.println("Totals: " + Arrays.toString(totals));
}
Additionally I added a totals array that keeps the total for each index instead of printing it every loop like you were doing. You did not add your compare code, so I cannot assist you with that. Let me know if you need any clarification on any changes. I ran this code and it successfully generated the arrays you need and the totals.
public static void main(String[] args) {
int[] results = new int[6]; // This array will hold the number of time each dice was rolled, so for example results[0] is how many 1 s you have results[5] is how many 6 you have
Random random = new Random();
for (int i = 0; i < 5; i++) { // roll the dice 5 times
results[random.nextInt(6)]++; //increase the counter of the appropriate value
}
boolean balut = false;
for (int i = 0; i < 6; i++) {
System.out.println("Number of " + (i+1) + ": " + results[i]);
if (results[i] == 5) {
balut = true;
}
}
if (balut) {
System.out.println("Balut!");
}
}
Here I implemented only the check for the Balut, but the main point is how I am couting the dices results. Hope it helps.

Writing a method that accepts an integer parameter n and returns as a the sum of the first n terms of the sequence

∑i=1n1i
In other words, the method should generate the following sequence:
1+12+13+14+15+⋯
I've been stumped on this problem for quite a bit. Having a tough time understand what "n" stands for in the equation and applying it to my for loop.
Would a for loop be optimal for solving this? Or should I just use a formula and somehow solve it then?
public static void main(String[] args) {
//Chapter 4 Exercise 1
System.out.println("--Chapter 4, Exercise 1");
System.out.println("How many integers do you want?:");
Scanner console = new Scanner(System.in);
int numb = console.nextInt();
fractionSum(numb)
public static double fractionSum(int numb) {
for(int i = 1; i <numb; i++) {
if (i !=1)
System.out.print("1 + 1" + i);
else
System.out.print("1");
}
return(numb);
}
1+12+13+14+15+⋯
Should be the output.
My output is coming out as:
11 + 121 + 131 + 141 + 15
Answering the first part of your question:
∑i=1n1i is known as the Harmonic Sum - the output you give in your question is wrong, harmonic sum can be described as the sum of reciprocals of the positive integers - for example:
H1 = 1
H2 = 1 + 1/2 = 1.5
H3 = 1 + 1/2 + 1/3 = 1.8333
H4 = 1 + 1/2 + 1/3 + 1/4 = 2.0833
H(n) = 1 + 1/2 + 1/3 + 1/4 ... + 1/n = answer ---> see what n is now?
You should use a for-loop for this, and its not very complex. Hopefully, this answer will clear up the task for you (I assume homework from Chapter 4 Exercise 1) and you can try again.
Here:
class Harmonic {
public static void main(String… s) {
int n, i;
float sum = 0;
n = Integer.parseInt(s[0]);
for (i = 1; i <= n; i++) {
sum = sum + (float) 1 / i;
}
System.out.println(“nSum = ”+sum);
}
}

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

How to calculate circumference with random numbers?

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

What to put as condition in while loop?

I am writing a method that prints guesses = [random number here from 1-50 inclusive] multiple times on a new line until the value is larger than 48. Once it is larger than 48 I try to print the number of guesses it took (No scanner used though, the 'guesses' are the number produced by the Math.random).
Here is example output:
guess = 43
guess = 47
guess = 45
guess = 27
guess = 49
total guesses = 5
and this is my output:
guess = 44
guess = 47
guess = 45
guess = 27
total guesses = 4
The reason I am getting almost the same random numbers is because it's in Practice-It.
Here is my code:
public static void makeGuesses(){
int totalGuesses = 0;
double randomNumber = (Math.random() * 50 + 1);
while(randomNumber < 48){
System.out.print("guess = ");
System.out.println(randomNumber + 1);
randomNumber = (int)(Math.random() * 51);
totalGuesses++;
}
System.out.print("total guesses = " + totalGuesses);
}
Currently, I am not getting the last line of required output. What do I need to make the condition on my while loop?
You're on the right track in that you need to cast to int, but you need to cast to int when you generate the number.
Furthermore, if you use your current implementation, you are generating numbers from 0-50, inclusive. You want to generate from 1-50, inclusive. You can fix this by multiplying by 50, then simply adding 1.
int randomNumber = (int) (Math.random() * 50 + 1);
Your first random isn't an int because you forgot the cast
double randomNumber = (int) (Math.random() * 51);
I suggest you make the type an int as well
int randomNumber = (int) (Math.random() * 51);
The problem is that the condition on your while checks a number you have not yet printed. If you use a debugger and step through the code, you will notice this.
int totalGuesses = 0;
int randomNumber;
while (true) {
randomNumber = 1 + (int)Math.floor(Math.random() * 50);
totalGuesses += 1;
System.out.print("guess = ");
System.out.println(randomNumber);
if (randomNumber > 48) break;
}
System.out.print("total guesses = " + totalGuesses);
Sorry I can't format code well on my phone.
When you need to generate random numbers again and again, you should use java.util.Random for this.
public static void makeGuesses() {
int totalGuesses = 0;
Random rdm = new Random();
int randomNumber;
do {
randomNumber = rdm.nextInt(50) + 1;
System.out.println("guess = " + randomNumber);
totalGuesses++;
} while (randomNumber < 48);
System.out.println("total guesses = " + totalGuesses);
}
}
Output :
guess = 15
guess = 29
guess = 26
guess = 14
guess = 3
guess = 1
guess = 49
total guesses = 7

Categories

Resources