How to update multiple variables in a loop - java

I'm a beginner Java student faced with the following question: W"rite a program that inputs an integer that will be the number of times (n) that you will read a random number."
The program is then supposed to calculate the sum and product of those random numbers.
I understand how to generate a random number and I set up a For loop to generate the n random numbers per user input.
import java.util.Scanner;
import java.util.Random;
public class Example {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n;
System.out.println("Enter a number:");
n = input.nextInt();
for (int i = 0; i < n; i++){
double randomNumber = Math.random();
System.out.println(randomNumber);
}
}
}
My first attempt had shoehorned
System.out.println(randomNumber * randomNumber);
System.out.println(randomNumber + randomNumber);
at the bottom of the code which did not work for reasons that are probably obvious to anyone else.
I'm stuck on the concept of storing n random numbers for long enough to do the required arithmetic on them.

You should be able to just maintain some state for the sum and product:
int n = input.nextInt();
double sum = 0d;
double product = 0d;
for (int i=0; i < n; i++) {
double randomNumber = Math.random();
sum += randomNumber;
product = i == 0 ? randomNumber : product*randomNumber;
}
System.out.println("sum = " + sum);
System.out.println("product = " + product);
The line:
product = i == 0 ? randomNumber : product*randomNumber;
is equivalent to:
if (i == 0) {
product = randomNumber;
}
else {
product = product*randomNumber;
}
The version I used is called a ternary expression, and is a concise way of writing if else logic. The idea here is that we want to initialize the product with the first random number. Otherwise, we just multiply the product with the latest random number.

Related

For loop in prime factorization calculator displays composite numbers as well as the loop does not restart

When the for loop detects a number that is less than the positive integer inputted by the user and perfectly divisible, it prints it and that is because the for loop just continues counting through each number. However, I need it to prime factorize the positive integer inputted by the user.
import java.util.Scanner;
public class PrimeFactor {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int Number = console.nextInt();
for (int counter =2; counter < Number; counter++) {
if (Number % counter == 0) {
System.out.print(" "+counter);
}
}
}
}
What you need to do to print all factors is to divide Number by counter when you've determined that counter is a factor. You also need to try counter again, in case there is more than one copy of a factor in a number, e.g. 12 is 2 * 2 * 3. Don't forget to print whatever Number is at the end, in case it didn't drop all the way to 1.
for (int counter = 2; counter <= Math.sqrt(Number); counter++) {
while (Number % counter == 0) {
Number /= counter;
System.out.print(" " + counter);
}
}
// Print what's left.
if (Number > 1) {
System.out.println(" " + Number);
}
As an aside, I've also changed the for loop condition to stop at the square root of Number, because for prime factor trials, if you've found a factor greater than the square root, then you should have found the corresponding factor that is less than the square root first.
Additionally, normal Java naming conventions would have you name the variable number in lowercase, to avoid confusion with classes such as java.lang.Number.
Your on the right track you just need to divide Number (num in the below code) by counter in the loop:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int num = console.nextInt();
console.close();
System.out.printf("Prime factors of %d: %s%n", num, getPrimeFactors(num));
}
public static List<Integer> getPrimeFactors(int num) {
List<Integer> primeFactors = new ArrayList<>();
for (int counter = 2; counter <= num; counter++) {
while (num % counter == 0) {
primeFactors.add(counter);
num /= counter;
}
}
if (num > 1) primeFactors.add(num);
return primeFactors;
}
}
Example Usage:
Enter a positive integer: 12
Prime factors of 12: [2, 2, 3]

My code runs, but the if statements are not printing their contents when I compare contents of two arrays

I am trying to write a simple mastermind game where a 4 digit number will be randomly selected by the computer and the user inputs a number over and over again until the correct number is found. I am trying to do this by passing the guessed number and the random number to their own separate arrays and then comparing them, position by position to see if they are similar. If two numbers are in the exact same spot
Example:
if guessArray[0] == numsArray[0] then the computer will print a *.
If two numbers are present but not in the exact same spot (eg. you made a guess of 2056 but the actual number is 1203) then one + should be printed. This cycle repeats until the number is guessed.
I've already asked a friend in person what the problem was and he couldn't figure it out. He knows the most code out of my friends so this was my next place to go.
Here is the full project. I did not write the ConvertInt2Array method. I found it on the internet.
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class Mastermind {
public static Random numGen = new Random();
public static void main(String [] args) {
Scanner Input = new Scanner (System.in);
int x = 0;
int number = 0;
int random = 0;
int guess = 0;
int y = 0;
int numArray[] = new int[4];
int guessArray[] = new int[4];
boolean isGuessed = false;
//Generate Random Number
for(x=0; x<=3; x++) {
int rand = Math.abs(numGen.nextInt());//Get the absolute value
random = (rand % 999 + 1);
numArray[x] = random;
number+=random;
}
while(isGuessed == false){
System.out.println("Guess a four digit random number");
guess = Input.nextInt();
guessArray = convertInt2Array(guess);
for(y=0; y<=3; y++) {
if(numArray[y] == guessArray[y]) {
System.out.print("*");
}
else if(Arrays.equals(numArray, y, y, guessArray, 0, guessArray.length) == true) {
System.out.print("+");
}
else {
}
if(guess==number) {
isGuessed = true;
}
}
}
System.out.println("You guessed it correctly!");
}
public static int[] convertInt2Array(int guess) {
String temp = Integer.toString(guess);
String temp2;
int temp3;
int [] gArray = new int[temp.length()];
for(int i=0;i<temp.length();i++) {
if (i!=temp.length()) {
temp2 = temp.substring(i, i+1);
} else {
temp2 = temp.substring(i);
}
temp3 = Integer.parseInt(temp2);
gArray[i] = temp3;
}
return gArray;
}
}
There may be more than one issue here, but here's a potential problem:
int rand = Math.abs(numGen.nextInt()); // Get the absolute value
random = (rand % 999 + 1);
This will usually result in random being a three-digit number. You mentioned you want this to be a four-digit number. Random.nextInt() can return any of the possible 232 integer numbers (from -2147483648 to 2147483647). To fix this, use a different Random.nextInt and specify your bounds:
int lowerBound = 1000;
int upperBound = 10000;
random = numGen.nextInt(upperBound - lowerBound) + lowerBound;
Let's break this down: numGen.nextInt(upperBound - lowerBound) evaluates to numGen.nextInt(9000), which will return a number between 0 (inclusive) and 9000 (exclusive), i.e. anything in the range 0-8999. You then add the lower bound of 1000 to ensure that random will be at least 1000 and up to 9999.
See the documentation for Random.nextInt(int bound).
Hopefully this gets you pointed in the right track.

How to do an addition from random numbers by the user?

I am new to Java and I would like some help. I have to solve this problem and I have it almost 90% solved:
Prompt the user to enter number of students. It must be a number that is perfectly divisible by 10 i.e. (number % 10) = 0
Check user input. If user input is not divisible by 10, keep asking the user for input until he enter a right number.
Accept user input and generate that many random numbers in the range from 0 to 100.
Print a matrix of random numbers and calculate the sum and average of all these random numbers and print them to the user.
Format sum and average to three decimal points.
This is my code so far:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Calculator10 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num;
do {
System.out.print("Enter a number: ");
num = user_input.nextInt();
} while(num % 10 != 0);
double numb;
DecimalFormat dec = new DecimalFormat("0.00");
for (int i=0; i<num; i++){
numb = Math.abs(Math.random() * ( 0 - 100 ));
System.out.print(" " +dec.format(numb) + " ");
}
}
}
As you can see, I have solved until the first part of # 4. I am not sure how I could sum all those random numbers displayed on the screen after user input. Of course, we have to store them in an array but I tried to do that but couldn't. So, how could I complete step #4 and 5? I would appreciate any help. Thanks a lot guys.
Here is how you should do it:
import java.text.DecimalFormat;
import java.util.Scanner;
public class Calculator10 {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int num;
do {
System.out.print("Enter a number: ");
num = user_input.nextInt();
} while(num % 10 != 0);
double numb;
double sum=0;
DecimalFormat dec = new DecimalFormat("0.00");
for (int i=0; i<num; i++){
numb = Math.random() * ( 100 - 0));
System.out.print(" " + dec.format(numb) + " ");
sum += numb;
}
System.out.println("The sum is: " + dec.format(sum));
System.out.println("The average is:" + dec.format(sum/num));
}
}
Please note that I have slightly changed the way you were generating the random numbers which obviates the need to use Math.abs(). Also see the following answer to see how to generate random numbers between two different values:
Generating random numbers with Java
You do not need to store them in an array. Just declare int sum = 0 at the start and do sum += numb each time you generate a random number. Also, you are generating random numbers in a strange way. Take a look at the java.util.Random class.

Why doesn't my "While Loop" print the computation of finding the average "score"?

I am writing a program that reads a sequence of positive integers input by the user. User will only enter one integer at a time.Then it will compute the average of those integers. The program will end when user enters 0. (0 is not counted in the average).The program will print out the average once the program ends.
Question: My code stops working when I gets to the while loop hence it doesn't compute the input by user, hence prints out nothing. Why doesn't my while loop compute the average from the user's inputs? Appreciate your guidance :)
import java.util.Scanner;
public class AverageOfIntegers {
public static void main(String[] args) {
int integer;
double sum;
sum = 0;
double average;
Scanner input = new Scanner(System.in);
int count; count = 0;
average = 0;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
System.out.println("Average = " + average);
}
}
This is because you are never actually summing over more than one integer. The user only ever enters one number. As a result your loop is essentially acting on just the one number. You need to put the input inside the while loop and save a running sum and count there. Something more like this
while (integer != 0) {
count += 1;
sum += integer;
average = sum / count;
integer = input.nextInt();
}
Explanation
First of all, when you define data types, you can set their default value in the definition. Ex:
double sum = 0;
vs
double sum;
sum = 0;
Secondly, sum = sum + integer; is the same as: sum += integer;
Thirdly, count = count + 1; is the same as: count += 1 OR (and better yet), count++;
As for your actual algorithm, there is one problem and one suggestion:
you are not changing integer's value after each loop. So, you can
either do that in the while condition: while ((integer =
input.nextInt()) != 0) { or, at the end of each loop:
while (integer != 0) {
count ++;
sum += integer;
average = sum / count;
integer = input.nextInt();
}
This is a suggestion for technically better code (in my opinion), but it looks better, is more intuitive and requires less calculations to calculate the average after the while loop is done instead of during. That way, you only calculate it once, where needed, vs. every loop, which is not needed.
________________________________________________________________________________
The Code (complete class)
public class AverageOfIntegers {
public static void main(String[] args) {
int integer;
double sum = 0;
double average = 0;
Scanner input = new Scanner(System.in);
int count = 0;
System.out.println("Please enter an integer: ");
// set integer = to the nextInt() while looping so it calculates properly
while ((integer = input.nextInt()) != 0) {
count ++;
sum += integer;
}
average = sum / count; // calculate the average after the while-loop
System.out.println("Average = " + average);
}
}
________________________________________________________________________________
Example input/output:
Please enter an integer:
5
10
15
0
Average = 10.0
So it did 5 + 10 + 15 = 30 (which is the sum), and then the average is 30 / 3 (30 is the sum, 3 is the count), and that gave you Average = 10.0.
You need to move integer = input.nextInt(); inside the loop, so your program will collect inputs in a loop. See the corrected version:
import java.util.Scanner;
public class AverageOfIntegers {
public static void main(String[] args) {
int integer = 0, count = 0;
double sum = 0.0, average = 0.0;
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
}
average = sum / count;
System.out.println("Average = " + average);
}
}
The problem is that the input.nextInt() should be part of the loop. The way you wrote it, the code gooes into an infinite loop whenever the first input is non-zero. Instead, do:
while ((integer = input.nextInt()) != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
In the loop:
while (integer != 0) {
count = count + 1;
sum = sum + integer;
average = sum / count;
}
This will only stops when integer is 0, but this variable is not changing in the loop, so it will never be 0 if it wasn't already in the first place.
According to what you said you want to do, you should probably repeat the call to integer = input.nextInt(); inside your loop, lke this:
System.out.println("Please enter an integer: ");
integer = input.nextInt();
while (integer != 0) {
count = count + 1;
sum = sum + integer;
System.out.println("Please enter an integer: ");
integer = input.nextInt();
}
average = sum / count;
Also, as others have said, you only need to compute the average once after the loop, so I moved it too.

binarySearch in Java, Mastermind Game

Right now for a Java course I'm trying to build a Mastermind-like game. In this game a 4-digit random number is generated, and the user tries to guess the number. With each guess the computer states how many correct digits are in the right order, and how many correct digits are in the wrong order.
For some reason, everything works up to my binary search for this program, which is really the heart of the program. I've spent hours tweaking it and I still cant get it. Any ideas?
In this example I'm trying to guess 9935, I realize that's not a random number though.
Thanks so much!
EDIT: When I run this program and use the guess "9875", it does not give me the right results.
The guesses and results I'm required to find are:
Please enter a four-digit number: 9874
The number of correct digits but in the wrong place: 0
The number of correct digits in the right place: 1
Please enter a four-digit number: 9899
The number of correct digits but in the wrong place: 1
The number of correct digits in the right place: 1
Please enter a four-digit number: 9593
The number of correct digits but in the wrong place: 3
The number of correct digits in the right place: 1
Please enter a four-digit number: 9935
The number of correct digits but in the wrong place: 0
The number of correct digits in the right place: 4
You are correct!
public class Mastermind {
public static void main(String[] args) {
Random randomGenerator = new Random();
Scanner input = new Scanner(System.in);
int randomNumber = 9935;
int[] randomArray = new int[4];
int temp = randomNumber;
for (int i = 3; i >= 0; i--){
int n = temp%10;
randomArray[i] = n;
temp /= 10;
}
boolean found = false;
while (found == false){
System.out.print(Arrays.toString(randomArray));
int[] guessArray = new int[4];
System.out.print("Please enter a four-digit number: ");
int guessTemp = input.nextInt();
for (int i = 3; i >= 0; i--){
int n = guessTemp%10;
guessArray[i] = n;
guessTemp /= 10;
}
if (Arrays.equals(randomArray, guessArray)){
System.out.println("You are correct!");
found = true;
} else {
int numberRightRight = 0;
int numberRightWrong = 0;
int indexFound = 0;
for(int i = 0; i < guessArray.length; i ++){
System.out.println(randomArray[i]);
indexFound = Arrays.binarySearch(guessArray, randomArray[i]);
System.out.println(indexFound);
if (indexFound >= 0){
if(indexFound == i){
numberRightRight++;
} else {
numberRightWrong++;
}
}
}
System.out.println("The number of correct digits but in the wrong place: " + numberRightWrong);
System.out.println("The number of correct digits in the right place: " + numberRightRight);
}
}
}
If you are not required to use Arrays.binarySearch(int[], int) you could use your own simple lookup method for an unsorted Array:
public static int findInArray(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
}
now instead of calling Arrays.binarySearch(guessArray, randomArray[i]); just call findInArray(guessArray, randomArray[i])

Categories