Store random number and score - java

I just started programming for few days.
I want to ask the user different questions and if they type in the right question then I will give them a score of 5 marks for getting the question right, plus bonus marks which are given by using Random, this bonus(Random) is then added to the total score(score(5) + random) which is stored and used to add the next score of the following question and the process repeats with all the questions[5].
This is what I have done so far, but it keeps printing the same result for every question and I want to keep adding to the previous score.
for (int attempts = 1; attempts <= 3; attempts++);
{
Random dice = new Random();
for(int n = 0; n <QArray.length; n++)
{
System.out.println("Question" + (n+1));
System.out.println(QArray[n]);
for(int m =0; m<3; m++)
{
String ans = scanner.nextLine();
int t = dice.nextInt(9) + 1;
int scoremarks = 5;
if (ans.equalsIgnoreCase(AArray[n]))
{
System.out.println("That is correct!\nYour score is:" + scoremarks + "\nWith virtual dice your total score is:" + (scoremarks +t));
break;
}
else
{
System.out.println("That is incorrect!\nYou got 0 Marks\nYour score is 0!");
}

You need to maintain the score outside the loop. You can print totalScore after all the questions and will have the total score of all the right answers.
int totalScore = 0;
for (int n = 0; n < QArray.length; n++) {
System.out.println("Question" + (n + 1));
System.out.println(QArray[n]);
for (int m = 0; m < 3; m++) {
String ans = scanner.nextLine();
Random dice = new Random();
int t = dice.nextInt(9) + 1;
int scoremarks = 5;
if (ans.equalsIgnoreCase(AArray[n])) {
totalScore += (scoremarks + t);
System.out.println("That is correct!\nYour score is:" + scoremarks + "\nWith bonus your total score is:" + (scoremarks + t));
// correct = false;
break;
} else {
System.out.println("That is incorrect!\nYou got 0 Marks\nYour score is 0!");
}
}
}
With a few optimizations as mentioned in the comments:
int totalScore = 0;
Random dice = new Random();
int scoremarks = 5;
for (int n = 0; n < QArray.length; n++) {
System.out.println("Question" + (n + 1));
System.out.println(QArray[n]);
for (int m = 0; m < 3; m++) {
String ans = scanner.nextLine();
int t = dice.nextInt(9) + 1;
if (ans.equalsIgnoreCase(AArray[n])) {
totalScore += (scoremarks + t);
System.out.println("That is correct!\nYour score is:" + scoremarks + "\nWith bonus your total score is:" + (scoremarks + t));
break;
} else {
System.out.println("That is incorrect!\nYou got 0 Marks\nYour score is 0!");
}
}
}
You can print totalScore in the condition when the answer is correct to see score increase each time the answer is correct. Also for the case when the answer is not correct, you can still show the total score to see how many points you might have from the previous questions. Not sure if there are 3 tries for getting the answer right but that's what the inside for loop seems to be doing so the message for incorrect guess seems inappropriate.

Related

Finding best subarray sum and returning it and the subarray

I am relatively new to Java and to coding as well and am currently trying to solve a subset problem.
The goal is to have the user input the amount of numbers and then input every number up to the amount specified, with the computer asking for every n-th number accordingly.
Afterwards the computer should calculate the sum of all subsets, and return the one closest to pi, as well as the subset in this form [x,y,z] within the same line.
I managed the first part just fine, although it might have been improved with a switch-case for convenience. It adds the input numbers into the array
But I struggle with the second part of this problem, and I have no idea how to progress/arrange the code so that it outputs the desired result. The suggestion I got was that, a for-loop for a set with n elements :
for a from 0 to 2^n
for i from 0 to n
when the binary representation of x on has a 1 at the i-th position
add data[i] to solution.
This should supposedly find all subsets of an array. After that I should add each element, check if the distance from pi decreases and add the element to the solution set. Or at least that is the goal, but my code is not functional as I don't know where to start arranging it. I also don't know what to initialize bestsum with, or how the binary representation algorithm works, or how to add elements to the solution array in order.
Edit : I have made progress, the code below outputs all the subarrays, and it properly calculates the closest sum, but I have no idea how to 'save' the best subarray (subarray with the closest sum) so that I can output it at the end with the sum. I am quite new so I haven't learned about lists or even methods, but this problem in this book at this chapter and I would like to solve it with the suggested method and possibly only simple loops.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers should be read? ");
int count = input.nextInt();
double[] data = new double[count];
double [] solution = new double[count];
double bestsum = 0.0;
for (int i = 0; i < count; i++) {
if ((i + 1) % 10 == 1) {
System.out.println("Enter " + (i + 1) + "st number: ");
data[i] = input.nextDouble();
} else if ((i + 1) % 10 == 2) {
System.out.println("Enter " + (i + 1) + "nd number: ");
data[i] = input.nextDouble();
} else if ((i + 1) % 10 == 3) {
System.out.println("Enter " + (i + 1) + "rd number: ");
data[i] = input.nextDouble();
} else {
System.out.println("Enter " + (i + 1) + "th number: ");
data[i] = input.nextDouble();
}
}
for (int j = 0; j <(1 << count); j++) {
System.out.print("{ ");
double sum = 0.0;
for (int x = 0; x < count; x++) {
if ((j & (1 << x)) > 0) {
System.out.print(data[x] + " ");
sum = sum + data[x];
}
solution[x] = data[x];
}
System.out.println("}");
if (Math.abs(sum - Math.PI) < Math.abs(bestsum - Math.PI)) {
bestsum = sum;
}
}
System.out.println(bestsum);
System.out.println(Arrays.toString(solution));
}
}
Here's my solution to this problem.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("How many numbers should be read? ");
int count = input.nextInt();
Double data[] = new Double[count];
Double bestsum = 0.0;
List<Double> bestArray= Collections.emptyList();
Set<List<Double>> possibleArrays = new LinkedHashSet<>();
for (int i = 0; i < count; i++) {
if (i == 0) {
System.out.println("Enter " + (i+1) + "st number: ");
data[i] = input.nextDouble();
} else if (i == 1) {
System.out.println("Enter " + (i+1) + "nd number: ");
data[i] = input.nextDouble();
} else if (i == 2) {
System.out.println("Enter " + (i+1) + "rd number: ");
data[i] = input.nextDouble();
} else {
System.out.println("Enter " + (i+1) + "th number: ");
data[i] = input.nextDouble();
}
}
input.close();
for (int i = 0; i < (1<<count); i++)
{
int m = 1; // m is used to check set bit in binary representation.
List<Double> currentArray = new ArrayList<>();
for (int j = 0; j < count; j++)
{
if ((i & m) > 0)
{
currentArray.add(data[j]);
}
m = m << 1;
}
possibleArrays.add(currentArray);
}
Iterator<List<Double>> iterator = possibleArrays.iterator();
iterator.next();
for (int i = 1; i < possibleArrays.size(); i++) {
Double sum=0.0;
List<Double> currentArray = iterator.next();
sum = currentArray.stream().collect(Collectors.summingDouble(Double::doubleValue));
if(Math.abs(sum-Math.PI)<Math.abs(bestsum-Math.PI)) {
bestArray = currentArray;
bestsum = sum;
}
}
System.out.println("possibleArrays: " + possibleArrays);
System.out.println("solution: " + bestArray);
System.out.println("bestsum: " + bestsum);
}

Is there perhaps a way of finding the above and below average

I'm creating a program to find the average of all the numbers entered by the user and storing those numbers to check whether the number entered falls below or above the average that was calculated.
My program outputs all numbers entered as below average. i have check on stack overflow for similar problems i have tried all that but my output still displays below the average only
This is what i have tried
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
//The loop for calculating the average
for (int i = 1; i <= 5; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
double aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <=5; j++)
{
if(aboveAvg > avg)
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
}
This is a possible solution for your problem:
Note that you need to store the user inputs, calculate the average once (not inside the for loop), and finally compare the numbers stored with the average calculated before.
public void newspaper() {
Scanner in = new Scanner(System.in);
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int[] youths = new int[5];
// The loop for calculating the average
for (int i = 0; i < youths.length; i++) {
System.out.println("Youth " + (i + 1) + " How many was delivered?");
youths[i] = in.nextInt();
sum = sum + youths[i];
}
// Note that the average can be calculated once, not every iteration
avg = sum / youths.length;
System.out.println("Average is: " + avg + "\n");
// The loop for checking below of above average
for (int i = 0; i < youths.length; i++) {
if (youths[i] > avg) {
System.out.println("Youth " + (i + 1) + " is above average");
} else {
System.out.println("Youth " + (i + 1) + " below average");
}
}
}
Try to use array instead of variable
see below code
import java.util.Scanner;
public class Stackoverflow {
public void newspaper() {
System.out.println("Question 4 \n");
double avg = 0;
int sum = 0;
int numYouth = 5;
int youth[] = new int[numYouth];
Scanner sc = new Scanner(System.in);
// The loop for calculating the average
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + i + " How many was delivered?");
youth[i] = sc.nextInt();
sum = sum + youth[i];
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
double aboveAvg = 0;
// The loop for checking below of above average
for (int j = 0; j < 5; j++) {
if (youth[j] > avg) {
System.out.println("Youth " + j + " is above average");
} else {
System.out.println("Youth " + j + " below average");
}
}
}
public static void main(String[] args) {
new Stackoverflow().newspaper();
}
}
You need to store the numbers in a temporary list and use counter 'ctr' for incrementing the values of the matched case. I have used for each loop for simplicity.
public void newspaper() {
System.out.println("Question 4 \n");
int youth;
double avg = 0;
int sum = 0;
int numYouth = 5;
List<Integer> number = new ArrayList<>();
// The loop for calculating the average
int ctr = 0;
for (int i = 0; i < 5; i++) {
System.out.println("Youth " + ++ctr + " How many was delivered?");
youth = in.nextInt();
number.add(youth);
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg + "\n");
ctr = 0;
// The loop for checking below of above average
for (int j : number) {
if (j > avg) {
System.out.println("Youth " + ++ctr + " is above average");
} else {
System.out.println("Youth " + ++ctr + " below average");
}
}
}
Assuming that you're trying to 'find the average of all the numbers entered by the user, storing those numbers to check whether each of the numbers entered falls below or above the average that was calculated', below are the things you need to fix:
The "storing those numbers" part
Compare the calculated average against the stored number.
A possible solution:
Use a list or an array to store the numbers entered by the user.
You can use an array as long as you know the number of elements to store before starting to read the numbers.
Read values from the list/array when you want to compare the entered value with the calculated average.
public void newspaper()
{
System.out.println("Question 4 \n");
int youth;
double avg =0;
int sum = 0;
int numYouth = 5;
// Create a list to store the entered values
// List<Integer> enteredNumbers = new ArrayList<Integer>();
// Using an array of '5' elements - this 5 comes from numYouth
int[] enteredNumbers = new int[numYouth]; // better not to 'hardcode'
//The loop for calculating the average
for (int i = 1; i <= numYouth; i++)
{
System.out.println("Youth " + i + " How many was delivered?");
youth = in.nextInt();
enteredNumbers[i-1] = youth; // array is 0-indexed
sum = sum + youth;
avg = sum / numYouth;
}
System.out.println("Average is: " + avg+ "\n");
// an int is enough to track the number of values above the average
int aboveAvg = 0;
//The loop for checking below of above average
for (int j = 1; j <= numYouth; j++)
{
// compare stored value against the average calculated above
if(enteredNumbers[j-1] > avg) // array is 0-indexed
{
System.out.println("Youth " + j + " is above average");
aboveAvg++;
}
else
{
System.out.println("Youth " + j + " below average");
}
}
System.out.println(aboveAvg + " Youths are above average");
}

This program should ask user for the max num to print out to and then calculate each number starting from 1 to the maximum along with it squared

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter the max number:");
int max = input.nextInt();
int[]arr1 = new int[max+1];
int[]arr2 = new int[max+1];
int[]arr3 = new int[max+1];
int i = 1;
// For-loop to calculate
for (i = 1;i <= max;i++)
arr1[i] = arr1[i-1] + i;
i = 1;
// While-loop to calculate
while (i <= max) {
arr2[i] = arr2[i-1] + i;
i++;
}
i = 1;
// Do-While-loop to calculate
do
arr3[i] = arr3[i-1] + i;
while (++i <= max);
for (i = 0; i <= max; i++)
System.out.println("Arr1 " + arr1[i] + " Arr2 " + arr2[i] + " Arr3 " + arr3[i]);
System.out.println("Sum of All is " + arr1[max]);
}
I have this for doing sums but I am stuck when it comes to getting it to square
You seem to have 3 identical array objects?
Anyway, it's pretty straightforward to print the square of all numbers from 1 to max:
for (int i = 1; i <= max; i++) {
System.out.println(i + ": " + i * i);
}
There are also some fun ways to sum up the numbers from 1 to max, such as:
System.out.println(IntStream.range(1, max + 1).sum());

Dice Roll Histogram with Loops

I have a problem in my class that I just can't figure out.
This is the question:
The purpose of this quiz is to reinforce the understanding of using loops and counting as well as reviewing the use of random numbers.
Modify the program below to print a histogram in which the total number of times the dice rolls equals each possible value is displayed by printing a character like # that number of times. Two dices will be used in each roll.
Example:
Histogram showing total number of dice rolls for each possible value.
Dice roll statistics (result varies):
2s: ######
3s: ####
4s: ###
5s: ########
6s: ###################
7s: #############
8s: #############
9s: ##############
10s: ###########
11s: #####
12s: ####
~~~~~~~~~~~~~~~~~~~~~
I haven't been able to get the program to print the histogram in the example above.
And this is what I have so far:
import java.util.Scanner;
import java.util.Random;
public class DiceStats {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Random randGen = new Random();
int seedVal = 11;
randGen.setSeed(seedVal);
// FIXME 1 and 2: Set the seed to the Random number generator
int i = 0; // Loop counter iterates numRolls times
int numRolls = 0; // User defined number of rolls
// FIXME 3: Declare and initiate cariables needed
int numOnes = 0;
int numTwos = 0;
int numThrees = 0;
int numFours = 0;
int numFives = 0;
int numSixes = 0; // Tracks number of 6s found
int numSevens = 0; // Tracks number of 7s found
int numEights = 0;
int numNines = 0;
int numTens = 0;
int numElevens = 0;
int numTwelves = 0;
int die1 = 0; // Dice 1 values
int die2 = 0; // Dice 2 values
int rollTotal = 0; // Sum of dice values
System.out.println("Enter number of rolls: ");
numRolls = scnr.nextInt();
if (numRolls >= 1) {
// Roll dice numRoll times
for (i = 0; i < numRolls; ++i) {
die1 = randGen.nextInt(6) + 1;
die2 = randGen.nextInt(6) + 1;
rollTotal = die1 + die2;
// FIXME 4: Count number of sixs and sevens; complete the same for all other possible values
if (rollTotal == 1) {
numOnes = numOnes + 1;
}
if (rollTotal == 2) {
numTwos = numTwos + 1;
}
if (rollTotal == 3) {
numThrees = numThrees + 1;
}
if (rollTotal == 4) {
numFours = numFours + 1;
}
if (rollTotal == 5) {
numFives = numFives + 1;
}
if (rollTotal == 6) {
numSixes = numSixes + 1;
}
if (rollTotal == 7) {
numSevens = numSevens + 1;
}
if (rollTotal == 8) {
numEights = numEights + 1;
}
if (rollTotal == 9) {
numNines = numNines + 1;
}
if (rollTotal == 10) {
numTens = numTens + 1;
}
if (rollTotal == 11) {
numElevens = numElevens + 1;
}
else if (rollTotal == 12) {
numTwelves = numTwelves + 1;
}
System.out.println("Debugging: Roll " + (i+1) + " is " + rollTotal + " (" + die1 +
"+" + die2 + ")");
}
// Print statistics on dice rolls
System.out.println("\nDice roll statistics:");
// FIXME 5: Complete printing the histogram
System.out.println("1s: " + numOnes);
System.out.println("2s: " + numTwos);
System.out.println("3s: " + numThrees);
System.out.println("4s: " + numFours);
System.out.println("5s: " + numFives);
System.out.println("6s: " + numSixes);
System.out.println("7s: " + numSevens);
System.out.println("8s: " + numEights);
System.out.println("9s: " + numNines);
System.out.println("10s: " + numTens);
System.out.println("11s: " + numElevens);
System.out.println("12s: " + numTwelves);
}
else {
System.out.println("Invalid rolls. Try again.");
}
return;
}
}
Any help would be very appreciated.
Have a loop like this where you have your print statements.
Modify your code so that instead of taking new variables every time have them in a array so that you can loop through them.
import java.util.Scanner;
import java.util.Random;
public class DiceStats {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Random randGen = new Random();
int seedVal = 11;
randGen.setSeed(seedVal);
// FIXME 1 and 2: Set the seed to the Random number generator
int i = 0; // Loop counter iterates numRolls times
int numRolls = 0; // User defined number of rolls
// FIXME 3: Declare and initiate cariables needed
int[] numValues=new int[12];
int die1 = 0; // Dice 1 values
int die2 = 0; // Dice 2 values
int rollTotal = 0; // Sum of dice values
System.out.println("Enter number of rolls: ");
numRolls = scnr.nextInt();
if (numRolls >= 1) {
// Roll dice numRoll times
for (i = 0; i < numRolls; ++i) {
die1 = randGen.nextInt(6) + 1;
die2 = randGen.nextInt(6) + 1;
rollTotal = die1 + die2;
// FIXME 4: Count number of sixs and sevens; complete the same for all other possible values
numValues[rollTotal]++;
System.out.println("Debugging: Roll " + (i+1) + " is " + rollTotal + " (" + die1 +
"+" + die2 + ")");
}
// Print statistics on dice rolls
System.out.println("\nDice roll statistics:");
// FIXME 5: Complete printing the histogram
for(int i=2;i<=12;i++)
{
System.out.print(i+"s: ");
for(int j=0;j<numVales[i];j++)
{
System.out.print("#");
}
System.out.println();
}
else {
System.out.println("Invalid rolls. Try again.");
}
return;
}
}
Let me know if you need clarification on the problem.
You can do something like this:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//You can directly set the seed during the object creation.
Random random = new Random(System.currentTimeMillis());
// This array is used to keep the value of your dice (2 - 12)
int [] histogram = new int[13];
while(true) {
System.out.println("Enter number of rolls: ");
int numberOfRolls = scanner.nextInt();
//If you enter 0, you can simply terminate the program
if(numberOfRolls == 0) break;
for(int i = 0; i < numberOfRolls; i++) {
int rolledValue = (random.nextInt(6) + 1) + (random.nextInt(6) + 1);
histogram[rolledValue]++;
}
//Print the result to your console.
for(int i = 2; i < histogram.length; i++) {
System.out.print("Total: " + i + " ");
for(int j = 0; j <histogram[i]; j++) {
System.out.print("#");
}
System.out.println();
}
}
}
That code will have a result as below:
Enter number of rolls: 7
Total: 2
Total: 3 #
Total: 4
Total: 5 ##
Total: 6
Total: 7 ###
Total: 8
Total: 9
Total: 10 #
Total: 11
Total: 12
Looks like you're really close. You just need to print the number of # for each int variable you have. The following will do that for the numTwos:
char[] chars = new char[numTwos];
Arrays.fill(chars, '#');
String result = new String(chars);
System.out.println(result);
You can put the whole thing in a loop of 12 to print it for all of them.

Combine for and while loop (Java)

I'm new to Java and I'm trying to make a program that allows the user to input 100 numbers and if the user writes '0', then the program is suppose to print the smallest, largest, sum and all the numbers. I got all that to work but not to exit and print it all. My teacher said something about using a while loop, but how is that possible when you have a for loop?
Regards
public static void main(String[] args) {
int[] list = new int[100];
int min = 0;
int max = 0;
int sum = 0;
boolean first = true;
Scanner scan = new Scanner(System.in);
while(list[i] != 0) {
for (int i = 0; i < list.length; i++) {
System.out.print("Enter number (0 to exit) " + (1 + i) + ":");
list[i] = scan.nextInt();
}
for (int i = 0; i < list.length; i++) {
if (first == true) {
min = list[i];
first = false;
}
if (list[i] < min) {
min = list[i];
}
else if (list[i] > max) {
max = list[i];
}
sum = list[i] + sum;
}
if (list[i] == 0) {
System.out.print("Numbers are: " + list[0] + ", ");
for (int i = 1; i < list.length; i++)
System.out.print(list[i] + ", ");
System.out.println();
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + min);
System.out.println("Sum is: " + sum);
}
}
}
}
You only need one while loop to do this and additionally a for loop just to print the array if you want:
Scanner scan = new Scanner(System.in);
int i = 0;
int sum = 0;
int maxValue = Integer.MIN_VALUE;
int[] history = new int[100];
System.out.println("INPUT:");
int option = scan.nextInt();
while (option != 0 && i <= 100)
{
if (option > maxValue)
maxValue=option;
sum += option;
history[i] = option;
option = scan.nextInt();
i++;
}
System.out.println("OUTPUT: \n" + "SUM: " + sum + "\n MAX VALUE: " + maxValue);
for (int x : history)
System.out.print(x + "");
Here's the body of the method which will do what you've been asked. I have not used a while loop (but in fact, a for-loop is a kind of a while-loop internally).
int size = 100; // Set the number of numbers to input.
int[] list = new int[size]; // Create an array with 'size' elements.
int min = Integer.MAX_VALUE; // Set the highest possible integer as start value.
int max = 0; // Set the minimum to zero, assuming that the user won't input negative numbers.
int sum = 0; // Initialize the sum of the numbers in the list.
Scanner scan = new Scanner(System.in);
for (int i = 0; i < size; i++) { // Run 'size' times the process of inputting a number.
System.out.print("Enter number (0 to exit) " + (i + 1) + ": ");
int number = scan.nextInt();
if (number == 0) { // Quit program if input equals '0'
System.out.println("Exiting...");
break;
}
list[i] = number; // Add the current number to the list
sum += number; // Add the number to the total
if (number < min) { // If the number is smaller than the previous one, set this number as the smallest
min = number;
}
if (number > max) { // If the number is greater than the previous smallest number, set this number as the greatest
max = number;
}
}
// Output all numbers in the list
for (int i = 0; i < list.length; i++) {
if (list[i] != 0) {
System.out.print((i == 0 ? "" : ", ") + list[i]);
}
}
// You see the snippet (i == 0 ? "" : ", ")
// That is a shorthand if-else statement:
// If i equals 0, then "" (empty string), else ", " (comma and space).
// The statement
// System.out.print((i == 0 ? "" : ", ") + list[i])
// is the same as
// if (i == 0) {
// System.out.println("") + list[i];
// }
// else {
// System.out.println(", ") + list[i];
// }
System.out.println("Smallest number is: " + min);
System.out.println("Largest numeber is: " + max);
System.out.println("Sum is: " + sum);
You have muddled code. Better to use a pattern like this:
while (true) {
// read next
if (input == 0)
break;
}

Categories

Resources