RollingDice Java Program Longest Streak - java

Can someone help me figure out how to make this program display the longest streak. I'm rolling two dice, and recording the percent each dice sum. Now I need something that will tell me what dice sum came up in the longest streak for example "The longest run was a run of 8 7's that began at roll 1479966."
import java.util.Scanner;
import java.text.DecimalFormat;
public class RollThoseDice {
/* Author: Name
* Assignment: Third Program
*/
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int timesRolled, randomOutSum;
DecimalFormat df = new DecimalFormat ("#.###");
System.out.println("Name: "
+ "\nAssignment: Third Program"
+"\nExtra Credit: Percentage is displayed in three decimal places");
int[] d = new int[13];
for (int i = 2; i < 13; i++) d[i] = 0;
int N=0;
boolean againA = true;
while(againA) {
try{
System.out.print("\nHow Many Rolls? ");
N =kbd.nextInt();
againA = false;
} catch(Exception e) {
System.out.println("Invalid Input");
kbd.next();
}
}
for (int k = 0; k < N; k++) {
int diceOut1 = (int) (Math.random()*6+1);
int diceOut2 = (int) (Math.random()*6+1);
int diceSum = diceOut1 + diceOut2;
d[diceSum]++;
}
for (int i = 2; i < 13; i++)
System.out.println("Total " + i + " happened "
+ df.format((double) (d[(int) i] / (double) N) * 100)
+ "% of the time.");
}
}

The longest run was a run of 8 7's that began at roll 1479966.
So, what are the parameters in that output?
Looks like roll, run length or roll count, and roll number.
Hmm, what can keep multiple variables, so we can treat them as one thing?
I know, we'll create a model class.
public class RollStreak {
private final NumberFormat NF = NumberFormat.getInstance();
private int roll;
private int rollCount;
private long rollNumber;
public RollStreak(int roll, long rollNumber, int rollCount) {
this.roll = roll;
this.rollNumber = rollNumber;
this.rollCount = rollCount;
}
public int getRoll() {
return roll;
}
public int getRollCount() {
return rollCount;
}
public long getRollNumber() {
return rollNumber;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("The computer rolled a ");
builder.append(roll);
builder.append(" ");
builder.append(rollCount);
builder.append(" times in a row starting at roll number ");
builder.append(NF.format(rollNumber));
builder.append(".");
return builder.toString();
}
}
A model class allows you to treat a group of fields as one object.
I don't want to give away the whole answer. You still have to determine how to create these model class instances and get the longest streaks. Hint: There can be more than one longest streak.

Related

Why does my Mooc.fi ski jumping programm not print the correct score? Is it overwritten?

I am working on mooc.fi week 8, the last exercise: ski jumping. At the very bottomt of the page. Here is the link: https://materiaalit.github.io/2013-oo-programming/part2/week-8/
All tests are succesfull, except for the calculation of the output.
When the jumpers jump twice, the scores of the first and second jump are meant to be added. If the user decides to terminate the programm at this point, the jumpers are meant to be printed out, winner first, with their final scores assigned to them.
As the actual final scores printed can (based on the number) only be the result of one jump, I suspect that the programm overwrites the first jump with the second instead of adding them, but I am not sure.
The error message says, that the actual final score is supposed to be 275 but was actually 158, which with two rounds and therefore two executed jumps is just not a possible score if the jumper had actually been assigned the score of two jumps and not just one.
But it is difficult for me to assess that as the jump length and the points assigned by the judges (which together make up the jumper's score) are generated randomly.
The error message I receive when testing is the following:
"twoRoundsOneJumperCalculationCorrect Failed: Jumper Arto's points are printed incorrectly in the tournament results your programm prints.
I have tested the calculation in the programm while it is running and the points the jumpers receive while jumping are accurate. Only the final results seem to be off. I am not sure why that is the case though. They appear to be overwritten with new scores.
I have gone through the code again to find what I am doing wrong, but I just cannot see where the mistake is.
I have divided the programm in four classes:
-Main to execute the UserInterface
-UserInterface for the organizing and printing the programm
-Jumper for creating jumpers for the ski tournament and to execute everything related to them such as jumping and the calculation of the scores
-SortAgainstPoints to sort the jumpers in ascending order by score
Here is my code:
//Main:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
UserInterface ui = new UserInterface();
ui.start(reader);
}
}
//UserInterface:
import java.util.*;
import java.util.Set;
import java.util.TreeMap;
public class UserInterface {
private HashMap<String,Jumper> participants;
private Jumper participant;
public UserInterface()
{
this.participants = new HashMap<String,Jumper>();
}
public void start(Scanner reader)
{
System.out.println("Kumpula ski jumping week");
System.out.println("");
System.out.println("Write the names of the participants one at a time; an empty string brings you to the jumping phase.");
while(true)
{
System.out.print(" Participant name: ");
String name = reader.nextLine();
if(!name.isEmpty())
{
this.participant = new Jumper(name);
this.participants.put(name, participant);
}
if(name.isEmpty())
{
System.out.println("");
break;
}
}
System.out.println("The tournament begins!\n");
rounds(reader);
}
public void sortAgainstPoints(ArrayList<Jumper> list)
{
Collections.sort(list, new SortAgainstPoints());
}
public void rounds(Scanner reader)
{
int roundCounter = 0;
ArrayList<Jumper> list = new ArrayList<Jumper>(this.participants.values());
while(true)
{
sortAgainstPoints(list);//does that even work????
System.out.print("Write \"jump\" to jump; otherwise you quit: ");
String input = reader.nextLine();
System.out.println("");
roundCounter ++;
if(!input.equals("jump"))
{
break;
}
System.out.println("Round " + roundCounter + "\n");//Round 1 ...
System.out.println("Jumping order:");
int counter = 0;
for(Jumper p : list)
{
counter++;
System.out.println(" " + counter + ". " + p);
}
System.out.println("");
System.out.println("Results of round " + roundCounter);
for(Jumper p : list)
{
int jumpLength = p.jump();
p.addJumpLength(jumpLength);
int[] judgesScores = new int[5];
judgesScores = p.judgeScores();
int score = 0;
score += p.jumpScore(jumpLength, judgesScores);
p.setPoints(score);
System.out.print(" " + p.getName() + "\n" +
" length: " + jumpLength + "\n" +
" judge votes: " + p.printJudgesScores(judgesScores) +"\n"
);
}
sortAgainstPoints(list);
System.out.println("");
}
Collections.reverse(list);//highest scored jumper should now be first
System.out.println("Thanks!\n");
System.out.println("Tournament results:");
System.out.println("Position Name");
for(int i = 0; i < list.size(); i++)
{
System.out.println((i +1) + " " + list.get(i).getName() + " (" + list.get(i).getPoints() + ")\n"
+ " jump lengths: " + list.get(i).printJumpLengths());
}
//tournament result does not equal acutal points and jump lengths, assignment is most likely overwritten with each new jump
}
}
//Jumper:
import java.util.*;
public class Jumper {
private String name;
private int points;
private Random random;
private int[] judges;
private ArrayList<Integer> jumpLengths;
public Jumper(String name)
{
this.name = name;
this.points = 0;
this.jumpLengths = new ArrayList<Integer>();
}
#Override
public String toString()
{
return this.name + " (" + this.points + " points)";
}
public int getPoints()
{
return this.points;
}
public int jump()
{
this.random = new Random();
int jumpLength = random.nextInt(120 - 60 +1) + 60;
return jumpLength;
}
public int[] judgeScores()
{
this.judges = new int[5];
for(int i = 0; i< judges.length; i++)
{
int judgeScore = random.nextInt(20 - 10 +1) + 10;
judges[i] = judgeScore;//scores, unsorted
}
return judges;
}
//smallest and largest judge score are meant to be skipped as specified //by task
public int jumpScore(int jumpLength, int[] judges)
{
sort(judges);//sorted
//skip first and last:
int score = jumpLength;
for(int i = 1; i < judges.length-1; i++)//skips first and last index
{
score += judges[i];
}
return score;
}
public String printJudgesScores(int[] judges)
{
String judgesScores = "[";
for(int i = 0; i < judges.length-1; i++)
{
judgesScores += judges[i] + ", ";
}
judgesScores += judges[judges.length-1] +"]";
return judgesScores;
}
public String getName()
{
return this.name;
}
public void setPoints(int points)
{
this.points = points;
}
public int[] sort(int[] judges)
{
for(int i = 0; i < judges.length; i ++)
{
for(int j = i+1; j < judges.length; j++)
{
if(judges[i] > judges[j])
{
int temp = judges[i];
judges[i] = judges[j];
judges[j] = temp;
}
}
}
return judges;
}
public void addJumpLength(int jumpLength)
{
this.jumpLengths.add(jumpLength);
}
public String printJumpLengths()
{
String jumps = "jump lengths: ";
for(int i = 0; i < this.jumpLengths.size()-1; i++)
{
jumps += this.jumpLengths.get(i) + " m, ";
}
jumps += this.jumpLengths.get(this.jumpLengths.size()-1) + " m";
return jumps;
}
}
//SortAgainsPoints:
import java.util.Comparator;
public class SortAgainstPoints implements Comparator<Jumper> {
public int compare(Jumper jumper1, Jumper jumper2)
{
if(jumper1.getPoints() > jumper2.getPoints())
{
return 1;
}
else if(jumper1.getPoints() < jumper2.getPoints())
{
return -1;
}
else
return 0;
}
}
I would appreciate any help!
I have done my best to post a good question, I know there are many better ones out there. If there is anything I can do to make the question clearer, let me know!
Edit: In case anybody is wondering, it's because I did not update the points correctly, I just replaced the old score with the new. It should have been p.setPoints(p.getPoints() + score);
instead of p.setPoints(score);

Parameters, methods and inputs

I am a beginner in Java and I am wondering if there is a way to use one input from the user in more than one method? I am making a program that is supposed to take some inputs (integers) from the user and control the inputs, then calculate the average and lastly count the occurrence of the inputs?
I have one main method + 3 different methods (one calculates the average etc). I have tried a lot of different things, but haven't seemed to understand the point with parameters and how they work.
So this is just a quick overview.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int value = sc.nextInt(); //Number of how many elements the user want to enter
int[] input = new int[value]; //An array with all the values
}
public int secureInt(int number, int[] input, int value) {
if (!Integer.parseInt(number)) {
System.out.println("Invalid input");
} else {
for (int i = 0; i < value; i++) { //Add all the inputs in the array
input[i] = sc.nextInt();
}
}
public double averageCalculator (int value, int[] in){
double average; // The average
double sum = 0; // The total sum of the inputs
if (int i = a; i < value; i++) {
sum = sum + in[i];
}
average = sum / value;
return average;
}
//Count the occurence of inputs that only occure once
public static int countOccurence(//what parameter should i have here?) {
int count = 0;
}
}
Here is some code that may be helpful to you. The idea is to try to emulate or imitate the style & best practices in this excerpt:
import java.util.Scanner;
public class ArrayFiller {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many elements do you want to enter");
int input_element_count = sc.nextInt(); //Number of how many elements the user want to enter
int element_count = input_element_count;
int[] array = new int[element_count]; //An array with all the values
enter_elements_of_array(array, element_count, sc);
double average = averageCalculator(array, element_count);
printArray(array);
System.out.println("The average of the entered numbers is " + average);
}
public static void printArray(int[] array) {
System.out.print("The array you entered is : [");
for (int element : array) {
System.out.print(" " + element + " ");
}
System.out.print("]" + "\n");
}
public static void enter_elements_of_array( int[] array, int element_count, Scanner sc) {
for (int i = 0; i < element_count; i++) { //Add all the inputs in the array
System.out.println("Please enter element " + (i+1) + " of " + element_count + ":");
array[i] = sc.nextInt();
}
}
public static double averageCalculator ( int[] array, int element_count){
double average; // The average
double sum = 0; // The total sum of the inputs
for (int i = 0; i < element_count; i++) {
sum = sum + array[i];
}
average = sum / element_count;
return average;
}
//Count the occurence of inputs that only occur once
public static int countOccurence(int[] array) {
int count = 0;
// algorithm for counting elements with cardinality of 1
return count;
}
}

Factorial of a number display issues

I know how to code to find the factorial of a number:
public static void factorialcalculations()
{
int usernumber, calculation, fact = 1;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);
usernumber = in.nextInt();
if ( usernumber < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( calculation = 1 ; calculation <= usernumber ; calculation++ )
fact = fact*calculation;
System.out.println("Factorial of "+usernumber+" is = "+fact);
{
But what I need is for is to display what numbers it is being multiplied by for example if it was 5
I need it to display the factorial is: 5*4*3*2*1=120
Use recursion. The value you want to display for n=1 is "1=". For any other n, it's "n*" + display(n-1).
display(2) => "2*" + display(1) => "2*1="
display(3) => "3*" + display(2) => "3*2*1="
and so on.
There is lot of ways to do it. With your existing code you can print it within your existing loop. Recursive will be the elegant way to find the factorial.
public static int factorial(int n) {
System.out.print("factorial is : ");
int result = 1;
for (int i = n; i >= 1; i--) {
result = result * i;
System.out.print(i!=1 ? (i+"*"): (i+"="));
}
System.out.println(result);
return result;
}
PS: As a best practice you need to handle the all scenarios in here. (String/negative/.. inputs)
Here is what you seem to be looking for man:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number whose factorial is to be found: ");
int n = scanner.nextInt();
int result = factorial(n);
System.out.println(getFactString(n,result));
}
public static int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
public static String getFactString(int n, int result){
String output= "";
int count = n;
for (int i = count; i > 0; i--) {
if (n==1) {
output = output + n +" = ";
break;
}
output = output + n+" * ";
n--;
}
return output + result;
}
It's also possible to do this will StringBuilder as well. With the getFactorString() method, it doesn't matter what n is, you will get the correct string returned to display.

Finding unique numbers

I am trying to use a set to find the unique numbers and get the sum from user entered numbers. I heard that arrays are easier but a set might just do for me. I don't know much about sets or what they do so any input would be fantastic. Much appreciated everybody!
import java.util.Scanner;
public class getdistinct
{
int dialr;
Scanner scan = new Scanner(System.in);
public double go()
{
double a = 0
counter = 10;
int total = 0;
for (counter != 0)
{
int thisisnewnumber = scan.nextInt();
System.out.println("Enter number that you want to add: ");
if(newInteger < 0)
{
n = n + 1
dial = dial - 1;
}
else
{
System.out.println("wrong");
}
}
System.out.println("the total is ";
return a;
}
}
java.util.HashSet stores unique values. Made minor changes to your program to use Set to store unique values and calculate sum of unique values using for loop
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class quiz_assignment {
int counter;
Scanner scan = new Scanner(System.in);
public int go() {
int a = 0;
int n = 0;
counter = 10;
Set<Integer> unValues = new HashSet<Integer>();
while (counter != 0) {
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if (newInteger < 0) {
unValues.add(new Integer(newInteger));
n += newInteger;
counter = counter - 1;
a = a + newInteger;
} else {
System.out
.println("Must be negative integer, please try again");
}
}
int unSum = 0;
for (Integer value : unValues) {
unSum += value;
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("The sum of unique integers is: " + unSum);
return n;
}
public static void main(String[] args) {
quiz_assignment o = new quiz_assignment();
o.go();
}
}
Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. Following is an example to explain Set functionality
I used here (HashSet).
import java.util.Scanner;
public class quiz_assignment
{
int counter;
Scanner scan = new Scanner(System.in);
Set<Integer> ditinctSet = new HashSet<Integer>();
public int go()
{
int a=0;
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(!ditinctSet.contains(newInteger)){
ditinctSet.add(newInteger);
}
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
a=a+newInteger;
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
System.out.println("The sum of all ten integers is: " + a);
System.out.println("Distinct numbers are: ");
System.out.println(ditinctSet);
return n;
}
}
And here a link to start knoing more about sets.
Hashsets are useful because they don't store duplicate entries. You can use them to store your set of unique numbers that the user inputs. I also removed the variable "a" from your code because its purpose seemed identical to variable n's.
import java.util.Scanner;
public class quiz_assignment{
int counter;
Scanner scan = new Scanner(System.in);
public int go()
{
HashSet<Integer> distinctNumbers = new HashSet<>();
int n=0;
counter = 10;
int total = 0;
while (counter != 0)
{
System.out.println("Enter Integer: ");
int newInteger = scan.nextInt();
if(newInteger < 0)
{
n+=newInteger;
counter = counter - 1;
distinctNumbers.add(newInteger);
}
else
{
System.out.println("Must be negative integer, please try again");
}
}
int size = distinctNumbers.size();
System.out.println("The sum of all ten integers is: " + n);
System.out.println("You inputed " + size + " numbers.");
System.out.println("Your numbers are:");
for(Integer i: distinctNumbers){
System.out.println(i);
}
return n;
}
}

How to return two values in Java

I know that java can't normally return two values, but I'm trying to return the value as a method.. From there I want to use the values of score1 and maxScore1 in a string in the main method. getHwGrades is the method I'm having issues with. I get "error: cannot find symbol". I'm not allowed to use arrays for this program. On another note, I'm also not supposed to use any if/else statements, but I could not find any other way to limit the value of discussionGrade to 20. Any help is appreciated
import java.util.Scanner;
public class Grades
{
public static void main(String[] args)
{
Scanner getG = new Scanner(System.in);
int weight1;
int weight2;
int weight3;
int score2 = 0;
int maxScore2 = 0;
int sections;
int discussionGrade;
System.out.println("What is the weight for the HW and Exam 1?");
weight1 = getG.nextInt();
weight2 = getG.nextInt();
weight3 = getWeight(weight1, weight2);
System.out.println("Using weights of " + weight1 + " " + weight2 + " " + weight3);
getHwGrades();
sections = numberSections();
discussionGrade = calcDGrade(sections);
System.out.println("What is your grade for exam1?"); //move under hw total points and final grade, add curve
score2 = getG.nextInt();
maxScore2 = getG.nextInt();
System.out.println("Total Points =" + (score1+ discussionGrade) + "/ "(maxScore1 + 20));
}
public static int getHwGrades()//method for asking and storing hw grades
{
int score1;
int maxScore1;
int nOfA;
Scanner getG = new Scanner(System.in);
System.out.println("How many HW assignments are there?");
nOfA = getG.nextInt();
for (int i = 1; i <= nOfA; i++) //loop that asks for the grades corresponding to the amount of hw assignments there were
{
System.out.println("What is your grade and then the max grade for assignment " + i + "?");
score1 += getG.nextInt();
maxScore1 += getG.nextInt();
}
return new getHwGrade(score1, maxScore1); //returns results of inputs into method holding the 2 variables
}
public static int numberSections() //finds out how many sections the student attended
{
Scanner getG = new Scanner(System.in);
System.out.println("How many sections did you attend?");
return getG.nextInt();
}
public static int calcDGrade(int sections) //method to calculate the grade for the students sections
{
int maxDGrade = ((sections*4)); if (maxDGrade > 20) //limits total score to 20
{
return 20;
}
else
{
return maxDGrade;
}
}
public static int getWeight(int weight1, int weight2)//returns the weight that will be used for weight3
{
return (100-(weight1 + weight2));
}
public static double round2(double number)
{
return Math.round(number * 100.0) / 100.0;
}
}
Since you can only return a single value, you need to return a single value. :-) Normally if a method needs to return complex information, the way you have it do that is either:
Return a newly-created instance of a class that has fields for the individual pieces of information
Have the method fill in an instance of such a class that's passed to it (usually not ideal barring a good reason for doing it)
So for instance:
class HwGrades {
private int score1;
private int maxScore1;
ScoreInfo(int _score1, int _maxScore1) {
this.score1 = _score1;
this.maxScore1 = _maxScore1;
}
// ...accessors as appropriate, presumably at least getters...
}
Then return an instance of HwGrades from getHwGrades:
public static int getHwGrades()//method for asking and storing hw grades
{
int score1;
int maxScore1;
// ...
return new HwGrades(score1, maxScore1);
}
If you needed, you could further decouple things by making HwGrades an interface, which you then implement with a private class, so that the API isn't tied to a specific class. Almost certainly overkill for a small school project.
getHwGrade is expected to be a class.
Have a class like this
class getHwGrade{
int a;
int b;
public getHwGrade(int a,b){
this.a=a;this.b=b;
}

Categories

Resources