I am making a dice game, the rules are 2 dice are thrown randomly, if the sum of both dice are 7 or 11 in the first try, the user wins. if the sum is 2,3 or 12 in the first try, the user loses. if the sum is 4,5,6,8,9,10 then that sum is set as an establish point and continues to throw the dice till the sum matches the established point and the user wins, however if the establish point is 7 the user loses.
the game plays 3 times and records how many times I have won or lost. however, I am not able to get that part finished, help would be appreciated, my code is bellow.
package roll;
import java.util.Random;
public class RandomSumGame {
boolean start;
int d1;
int d2;
int sum = d1 + d2;
int valuepoint;
String plus = "+";
public void play(int d1, int d2) {
int win = 0;
int loss = 0;
sum = d1 + d2;
for (;;) {
if (sum == 2 || sum == 3 || sum == 12) {
start = false;
loss++;
System.out.println(" = " + sum + ";you lose");
break;
} else if (sum == 7 || sum == 11) {
start = true;
win++;
System.out.println(" = " + sum + ";you win ");
break;
}
valuepoint = sum;
if (valuepoint == 4 || valuepoint == 5 || valuepoint == 6 || valuepoint == 8 || valuepoint == 9
|| valuepoint == 10) {
System.out.print(" = " + valuepoint + " you establish a value point " + valuepoint + "\n");
break;
}
}
for (;;) {
if (sum == 7 || sum == 11) {
break;
} else {
Random rand = new Random();
for (int i = 0; i < 1; i++) {
d1 = 1 + rand.nextInt(6);
int f1 = d1;
System.out.print("\t" + "-you rolled again " + d1 + " " + plus);
for (int x = 0; x < 1; x++) {
d2 = 1 + rand.nextInt(6);
int f2 = d2;
int loda = f1 + f2;
System.out.print(" " + d2 + " = " + loda + "\n");
}
}
sum = d1 + d2;
if (sum == valuepoint) {
start = true;
win++;
System.out.print("\t" + "you win!" + "\n");
break;
} else if (sum == 7) {
loss++;
start = false;
System.out.print("\t" + "you lose " + "\n");
break;
}
}
}
System.out.print("wins: " + win + "\n");
System.out.print("Losses:" + loss);
}
public void play() {
for (int x = 0; x < 3; x++) {
rolldice();
play(d1, d2);
System.out.print("\n");
}
}
public void rolldice() {
Random rand = new Random();
for (int i = 0; i < 1; i++) {
d1 = 1 + rand.nextInt(6);
System.out.print("You rolled " + d1 + " " + plus);
}
for (int i = 0; i < 1; i++) {
d2 = 1 + rand.nextInt(6);
System.out.print(" " + d2 + " ");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RandomSumGame Teet = new RandomSumGame();
RandomSumGame d1counter = new RandomSumGame();
RandomSumGame d2counter = new RandomSumGame();
Teet.play();
}
}
What part are you not able to finish? Seems like the game is running 3 times? Is it the total number of wins and loses? To fix that, you could just move "int win" and "int lose" outside the play method to make them global variables.
EDIT:
If you don't want to use global variables, you could make a method that calls itself (recursive method)
import java.util.Random;
public class RandomSumGame {
boolean start;
int d1;
int d2;
int sum = d1 + d2;
int valuepoint;
String plus = "+";
public void play(int d1, int d2, int win, int loss) {
sum = d1 + d2;
for (;;) {
if (sum == 2 || sum == 3 || sum == 12) {
start = false;
loss++;
System.out.println(" = " + sum + ";you lose");
break;
} else if (sum == 7 || sum == 11) {
start = true;
win++;
System.out.println(" = " + sum + ";you win ");
break;
}
valuepoint = sum;
if (valuepoint == 4 || valuepoint == 5 || valuepoint == 6 || valuepoint == 8 || valuepoint == 9
|| valuepoint == 10) {
System.out.print(" = " + valuepoint + " you establish a value point " + valuepoint + "\n");
break;
}
}
for (;;) {
if (sum == 7 || sum == 11) {
break;
} else {
Random rand = new Random();
for (int i = 0; i < 1; i++) {
d1 = 1 + rand.nextInt(6);
int f1 = d1;
System.out.print("\t" + "-you rolled again " + d1 + " " + plus);
for (int x = 0; x < 1; x++) {
d2 = 1 + rand.nextInt(6);
int f2 = d2;
int loda = f1 + f2;
System.out.print(" " + d2 + " = " + loda + "\n");
}
}
sum = d1 + d2;
if (sum == valuepoint) {
start = true;
win++;
System.out.print("\t" + "you win!" + "\n");
break;
} else if (sum == 7) {
loss++;
start = false;
System.out.print("\t" + "you lose " + "\n");
break;
}
}
}
System.out.print("wins: " + win + "\n");
System.out.print("Losses:" + loss);
if (win < 2 && loss < 2) {
System.out.print("\n");
//Recursive
play(win, loss);
}
}
public void play(int win, int loss) {
rolldice();
play(d1, d2, win, loss);
}
public void rolldice() {
Random rand = new Random();
for (int i = 0; i < 1; i++) {
d1 = 1 + rand.nextInt(6);
System.out.print("You rolled " + d1 + " " + plus);
}
for (int i = 0; i < 1; i++) {
d2 = 1 + rand.nextInt(6);
System.out.print(" " + d2 + " ");
}
}
public static void main(String[] args) {
RandomSumGame test = new RandomSumGame();
test.play(0,0);
}
}
Related
I'm new to the programming world so I'd deeply appreciate if any of you could help me become better at this. My goal for this program is to simulate 3000 dice rolls and count the number of times doubles are rolled for each of the different possible pairs of doubles using a while loop. The results should be printed out in a dialog box.
Random random;
random = new Random();
diceRolls = 1;
snakeEyes = 1;
doubleTwos = 1;
doubleThrees = 1;
doubleFours = 1;
doubleFives = 1;
doubleSixes = 1;
while (diceRolls <= finalDiceRoll) {
int diceRolls = 1;
int die1 = random.nextInt(6) + 1;
int die2 = random.nextInt(6) + 1;
if (die1 == 1 && die2 == 1){
//snakeEyes = snakeEyes + 1;
snakeEyes++;
}
else if (die1 == 2 && die2 == 2 ) {
doubleTwos++;
}
else if (die1 == 3 && die2 == 3) {
doubleThrees++;
}
else if (die1 == 4 && die2 == 4) {
doubleFours++;
}
else if (die1 == 5 && die2 == 5) {
doubleFives++;
}
else if (die1 == 6 && die2 == 6) {
doubleSixes++;
}
JOptionPane.showMessageDialog (null, "You rolled snake eyes " + snakeEyes + " times\nYou rolled double twos " + doubleTwos + " times\nYou"
+ " rolled double threes " + doubleThrees + " times\nYou rolled double fours " + doubleFours + " times\nYou"
+ " rolled double fives " + doubleFives + " times\nYou rolled double sixes " + doubleSixes + " times");
}
The issue i'm having here is that the results i'm getting from the program don't seem "plausible". For example, out of 3000 dice rolls, I get 1 pair of each double. What am I doing wrong?
Few changes you have to make in your code,
1. Initialize all your variables by 0.
2. change while-loop condition to
while (diceRolls <= finalDiceRoll) // hoping that finalDiceRoll = 3000
3 remove int diceRolls = 1; from while-loop and add diceRolls++; at end of while-loop.
4. Put your JOptionPane outside while-loop. if not you have to close 3000 time your JOptionPane dailog.
After applying these changes to your code you will learn what have you done wrong and your code will run fine.
Move the showMessageDialog outside of the while loop and increment the diceRolls variable. Initialize all other integer variables with 0.
A better (cleaner and shorter) approach would be to use a two-dimensional array or a map.
Random random = new Random();
int snakeEyes = 0;
int doubleTwos = 0;
int doubleThrees = 0;
int doubleFours = 0;
int doubleFives = 0;
int doubleSixes = 0;
int diceRolls = 1;
while (diceRolls <= 3000) {
int die1 = random.nextInt(6) + 1;
int die2 = random.nextInt(6) + 1;
if (die1 == 1 && die2 == 1) {
snakeEyes++;
} else if (die1 == 2 && die2 == 2) {
doubleTwos++;
} else if (die1 == 3 && die2 == 3) {
doubleThrees++;
} else if (die1 == 4 && die2 == 4) {
doubleFours++;
} else if (die1 == 5 && die2 == 5) {
doubleFives++;
} else if (die1 == 6 && die2 == 6) {
doubleSixes++;
}
diceRolls++;
}
JOptionPane.showMessageDialog(null, "You rolled snake eyes " + snakeEyes + " times\nYou rolled double twos " + doubleTwos + " times\nYou"
+ " rolled double threes " + doubleThrees + " times\nYou rolled double fours " + doubleFours + " times\nYou"
+ " rolled double fives " + doubleFives + " times\nYou rolled double sixes " + doubleSixes + " times");
The above-mentioned shorter version:
Random random = new Random();
int[] doubled = new int[6];
for (int diceRolls = 0; diceRolls < 3000; diceRolls++) {
int die1 = random.nextInt(6);
int die2 = random.nextInt(6);
if (die1 == die2)
doubled[die1]++;
}
JOptionPane.showMessageDialog(null, "You rolled snake eyes " + doubled[0] + " times\nYou rolled double twos " + doubled[1] + " times\nYou"
+ " rolled double threes " + doubled[2] + " times\nYou rolled double fours " + doubled[3] + " times\nYou"
+ " rolled double fives " + doubled[4] + " times\nYou rolled double sixes " + doubled[5] + " times");
The counting logic should go as follows:
doubleTwos = 0;
doubleThrees = 0;
doubleFours = 0;
doubleFives = 0;
doubleSixes = 0;
finalDiceRoll = 3000;
int diceRolls = 0;
while (diceRolls < finalDiceRoll) {
++diceRolls;
With any message after the loop.
With an array you may save typing:
int[] doubleCounts = new int[6]; // By 0 based dice values
for (int i = 0; i < finalDiceRoll; ++i) {
int die1 = random.nextInt(6); // With dice values 0-5
int die2 = random.nextInt(6);
if (die1 == die2) {
++doubleCounts[die1];
}
}
int snakeEyes = doubleCounts[0];
int doubleTwos = doubleCounts[1];
...
Simplify. Eliminate duplications. Don't use multiple variables when you can use an array.
int[] doubles = new int[7]; // make the index the number rolled (ignore index 0)
int diceRolls = 0;
while (diceRolls++ < 3000) {
int die1 = random.nextInt(6) + 1;
int die2 = random.nextInt(6) + 1;
if (die1 == die2)
doubles[die1]++;
}
String output = "";
for (int i = 1; i <= 6; i++)
output += "You rolled double " + i + "'s " + doubles[i] + " times\n";
JOptionPane.showMessageDialog (null, output);
That's all you need.
How do I show the amount of True and falses. For example:
True - 8 is divisible by 2.
True - 42 is divisible by 2.
False - 11 is not divisible by 2.
(What I Want to it to show...)
True: 2
False: 1
Random r = new Random();
int[] num = new int[3]; // same as "= {0,0,0,0,0}
boolean gameResult = true;
for (int i = 0; i < num.length; i++) {
num[i] = r.nextInt(100) + 1;
if (num[i] % 2 == 0) {
System.out.println("TRUE - " + num[i] + " is divisible by 2.");
} else {
System.out.println("FALSE - " + num[i]
+ " is not divisible by 2.");
gameResult = false;
}
}
if (gameResult) {
System.out.println("You Won");
} else {
System.out.println("You Lost");
}
}
}
Random r = new Random();
int[] num = new int[3]; // same as "= {0,0,0,0,0}
int tCount = 0, fCount = 0;
boolean gameResult = true;
for (int i = 0; i < num.length; i++) {
num[i] = r.nextInt(100) + 1;
if (num[i] % 2 == 0) {
System.out.println("TRUE - " + num[i] + " is divisible by 2.");
tCount++;
} else {
System.out.println("FALSE - " + num[i]
+ " is not divisible by 2.");
fCount++;
gameResult = false;
}
}
System.out.println("True:" + tCount + "False:" + fCount);
if (gameResult) {
System.out.println("You Won");
} else {
System.out.println("You Lost");
}
}
}
The above code returns true and false counts. You can now use them as you want.
Here is the java code:
import java.util.Random;
public class DivisibleTest{
public static void main(String []args){
Random r = new Random();
int counterTrue=0;
int counterFalse=0;
int[] num = new int[3]; // same as "= {0,0,0,0,0}
boolean gameResult = true;
for (int i = 0; i < num.length; i++) {
num[i] = r.nextInt(100) + 1;
if (num[i] % 2 == 0) {
System.out.println("TRUE - " + num[i] + " is divisible by 2.");
counterTrue++;
counterTrue=counterTrue+1;
} else {
System.out.println("FALSE - " + num[i]
+ " is not divisible by 2.");
gameResult = false;
System.out.println(counterFalse);
counterFalse++;
counterFalse=counterFalse+1;
}
}
if (gameResult) {
System.out.println("You Won");
System.out.println("True:" +counterTrue );
System.out.println("False:" +counterTrue );
} else {
System.out.println("You Lost");
System.out.println("True:" +counterTrue );
System.out.println("False:" +counterTrue );
}
}
}
Let me know if you have any questions
My project is about finding the average, minimum and maximum of students' grades and their standing, but it keeps showing me an error on the output.
Here are the names and the grades:
Students:
Alia Nahid Eiman Suad Lamia Salma Mai Wedad Haya Sanaa
Quiz:
10 20 50 70 80 50 30 90 60 40
Midterm:
30 80 100 40 80 70 70 80 50 30
Final Exam:
40 80 70 100 90 60 70 50 40 80
And here is the Java code:
package java_final_project;
import java.util.*;
public class Java_Final_Project {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
// Declare inputs:
String letter1, letter2, letter3;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
// Declare the four array structures
int[] quiz = new int[10];
int[] midterm = new int[10];
int[] finalexam = new int[10];
String[] students = new String[10];
// Input elements to the arrays
int counter, sum1 = 0;
int sum2 = 0;
int sum3 = 0;
double ave1, ave2, ave3;
int max1, max2, max3;
int min1, min2, min3;
for (counter = 0; counter < 10; counter++) {
System.out.println ("Enter student names and grades of quiz, midterm "
+ "and final with space between them");
students[counter] = console.next();
quiz[counter] = console.nextInt();
sum1 = sum1 + quiz[counter];
midterm[counter]= console.nextInt();
sum2 = sum2 + midterm[counter];
finalexam[counter]= console.nextInt();
sum3 = sum3 + finalexam[counter];
}
ave1 = sum1 / 10;
ave2 = sum2 / 10;
ave3 = sum3 / 10;
// min and max values
max1 = Math.max(quiz[counter], max);
max2 = Math.max(midterm[counter], max);
max3 = Math.max(finalexam[counter], max);
min1 = Math.min(quiz[counter], min);
min2 = Math.min(midterm[counter], min);
min3 = Math.min(finalexam[counter], min);
// if statement for the standing
// ave1
if (ave1 >= 90 && ave1 <= 100) {
letter1 = "E";
} else if (ave1 >= 70 && ave1 <= 80) {
letter1 = "G";
} else if (ave1 >= 50 && ave1 <= 60) {
letter1 = "S";
} else {
letter1 = "P";
}
// ave2
if (ave2 >= 90 && ave2 <= 100) {
letter2 = "E";
} else if (ave2 >= 70 && ave2 <= 80) {
letter2 = "G";
} else if (ave2 >= 50 && ave2 <= 60) {
letter2 = "S";
} else {
letter2 = "P";
}
//ave3
if (ave3 >= 90 && ave3 <= 100) {
letter3 = "E";
} else if (ave3 >= 70 && ave3 <= 80) {
letter3 = "G";
} else if (ave3 >= 50 && ave3 <= 60) {
letter3 = "S";
} else {
letter3 = "P";
}
// Display the elements of the four arrays
System.out.println("Here is the elements of the four arrays");
System.out.println("students" + "\t" + "quiz" + "\t" + "midterm" + "\t" + "finalexam");
for (counter = 0; counter < 10; counter++) {
System.out.println(students[counter] + "\t" + quiz[counter] + "\t" + midterm[counter] + "\t" + finalexam[counter]);
}
System.out.println("Summary Report:");
System.out.println();
System.out.println("students" + "\t" + "\t" + "Quiz" + "\t" + "\t" + "Midterm" + "\t" + "\t" + "FinalExam");
System.out.println();
System.out.println("Average" + "\t" + "\t" + ave1 + "\t" + "\t" + ave2 + "\t" + "\t" + ave3);
System.out.println();
System.out.println("Max" + "\t" + "\t" + max1 + "\t" + "\t" + max2 + "\t" + "\t" + max3);
System.out.println();
System.out.println("Min" + "\t" + "\t" + min1 + "\t" + "\t" + min2 + "\t" + "\t" + min3);
System.out.println();
System.out.println("Standing" + "\t" + "\t" + letter1 + "\t" + "\t" + letter2 + "\t" + "\t" + letter3);
}
}
The six lines where you set min1, min2, min3, max1, max2, max3 need to be up, inside the for loop where you gather the input; because you want to check after each input whether it's bigger or smaller than the current maximum and minimum. Where you have those lines at the moment, they can't possible work, because counter is no longer pointing to an entry in the array.
I'm not sure if you are allowed to use streams in your assignment. If you are then there is a much easier way of getting min, max, average in Java 8:
int[] scores = {1, 3, 6, 8, 10, 11, 2};
int max = Arrays.stream(scores).max();
int min = Arrays.stream(scores).min();
int avg = Arrays.stream(scores).average();
You don't really need to use loops often now that Java has streams.
I've figured out the codes and corrected some mistakes. Here's the updated java code and it worked :D! and I thank you for your comments and help :)
package java_final_project;
import java.util.*;
public class Java_Final_Project
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
// Declare inputs:
String letter1, letter2, letter3;
double ave1, ave2, ave3;
// Declare the four array structures
int[] quiz = new int[10];
int[] midterm = new int[10];
int[] finalexam = new int[10];
String [] students = new String[10];
int [] scores = new int[100];
// Input elements to the arrays
int counter, sum1=0;
int sum2=0;
int sum3=0;
for ( counter = 0; counter < 10; counter++)
{
System.out.println ("Enter student names and grades of quiz, midterm "
+ "and final with space between them");
students[counter] = console.next();
quiz[counter]= console.nextInt();
sum1 = sum1 + quiz[counter];
midterm[counter]= console.nextInt();
sum2 = sum2 + midterm[counter];
finalexam[counter]= console.nextInt();
sum3 = sum3 + finalexam[counter];
}
// max and min values for the quiz
int minGrade = quiz[0];
int maxGrade = quiz[0];
for (int i = 0; i < 10; i++)
{
if (minGrade > quiz[i])
minGrade = quiz[i];
if (maxGrade < quiz[i])
maxGrade = quiz[i];
}
// max and min values for the midterm
int minGrade1 = midterm[0];
int maxGrade1 = midterm[0];
for (int i = 0; i < 10; i++)
{ if (minGrade1 > midterm[i])
minGrade1 = midterm[i];
if (maxGrade1 < midterm[i])
maxGrade1 = midterm[i];}
// max and min values for the final
int minGrade2 = finalexam[0];
int maxGrade2 = finalexam[0];
for (int i = 0; i < 10; i++)
{if (minGrade2 > finalexam[i])
minGrade2 = finalexam[i];
if (maxGrade2 < finalexam[i])
maxGrade2 = finalexam[i];}
//calculate the average of quiz, midterm, final
ave1 = sum1/10;
ave2 = sum2/10;
ave3 = sum3/10;
// if statement for the standing
// ave1
if (ave1 > 90 && ave1 > 100)
{letter1 = "E";}
else if (ave1 > 70 && ave1 > 80)
{letter1 = "G" ;}
else if (ave1 > 50 && ave1 > 60)
{letter1 = "S";}
else
{letter1 = "P";}
// ave2
if (ave2 > 90 && ave2 > 100)
{letter2 = "E";}
else if (ave2 > 70 && ave2 > 80)
{letter2 = "G" ;}
else if (ave2 > 50 && ave2 > 60)
{letter2 = "S";}
else
{letter2 = "P";}
//ave3
if (ave3 > 90 && ave3 > 100)
{letter3 = "E";}
else if (ave3 > 70 && ave3 > 80)
{letter3 = "G" ;}
else if (ave3 > 50 && ave3 > 60)
{letter3 = "S";}
else
{letter3 = "P";}
// Display the elements of the four arrays
System.out.println (" Here is the elements of the four arrays");
System.out.println ("students"+"\t"+"quiz"+"\t"+"\t"+"midterm"+"\t"+"\t"+"finalexam");
for ( counter = 0; counter < 10; counter++)
{
System.out.println (students[counter]+"\t"+"\t"+quiz[counter]+"\t"+"\t"+midterm[counter]
+"\t"+"\t"+finalexam[counter]);
}
System.out.println (" ");
System.out.println ("Summary Report:");
System.out.println ("\t"+"\t"+"Quiz"+"\t"+"\t"+"Midterm"+"\t"+"\t"+"FinalExam");
System.out.println ("Average"+"\t"+"\t"+ave1+"\t"+"\t"+ave2+"\t"+"\t"+ave3);
System.out.println ("max"+ "\t"+"\t"+maxGrade+ "\t"+"\t"+ maxGrade1+ "\t"+"\t"+ maxGrade2);
System.out.println ("min"+ "\t"+"\t"+minGrade+ "\t"+"\t"+ minGrade1+ "\t"+"\t"+ minGrade2);
System.out.println ();
System.out.println ("Standing"+ "\t"+ letter1+ "\t"+ "\t"+ letter2+ "\t"+"\t"+ letter3);
}
}
I need to modify the code so that,
its structure is better
it is more readable
it uses methods and parameters
only one statement needs to be changed if a different number of integers is to be input
My new code is at the bottom but it's not working yet, can't quite figure out what else I need to do to it. If anyone could help that would be fab.
Original Code
import java.util.Scanner;
public class MakeMeBetter
{
public static void main(String[] args)
{
int[] a = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Scanner b = new Scanner(System.in);
System.out.println("Please input 10 numbers in the range 1-19 :> ");
int c = b.nextInt();
while (c < 1 || c > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[0] = c;
int d = b.nextInt();
while (d < 1 || d > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[1] = d;
int e = b.nextInt();
while (e < 1 || e > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[2] = e;
int f = b.nextInt();
while (f < 1 || f > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[3] = f;
int g = b.nextInt();
while (g < 1 || g > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[4] = g;
int h = b.nextInt();
while (h < 1 || h > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[5] = h;
int i = b.nextInt();
while (i < 1 || i > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[6] = i;
int j = b.nextInt();
while (j < 1 || j > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[7] = j;
int k = b.nextInt();
while (k < 1 || k > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[8] = k;
int l = b.nextInt();
while (l < 1 || l > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
}
a[9] = l;
System.out.println("\nArray contents");
System.out.print((a[0] < 10 ? " " : "") + a[0] + " ");
System.out.print((a[1] < 10 ? " " : "") + a[1] + " ");
System.out.print((a[2] < 10 ? " " : "") + a[2] + " ");
System.out.print((a[3] < 10 ? " " : "") + a[3] + " ");
System.out.print((a[4] < 10 ? " " : "") + a[4] + " ");
System.out.print((a[5] < 10 ? " " : "") + a[5] + " ");
System.out.print((a[6] < 10 ? " " : "") + a[6] + " ");
System.out.print((a[7] < 10 ? " " : "") + a[7] + " ");
System.out.print((a[8] < 10 ? " " : "") + a[8] + " ");
System.out.print((a[9] < 10 ? " " : "") + a[9] + " ");
System.out.println();
boolean noSwap = false;
int startAt = 0;
int stopAt = 9;
while (startAt < stopAt && noSwap == false)
{
noSwap = true;
for (int m=startAt; m<stopAt; m++)
{
if (a[m] > a[m+1])
{
int t = a[m];
a[m] = a[m+1];
a[m+1] = t;
noSwap = false;
}
}
stopAt = stopAt - 1;
}
System.out.println("\nArray contents");
System.out.print((a[0] < 10 ? " " : "") + a[0] + " ");
System.out.print((a[1] < 10 ? " " : "") + a[1] + " ");
System.out.print((a[2] < 10 ? " " : "") + a[2] + " ");
System.out.print((a[3] < 10 ? " " : "") + a[3] + " ");
System.out.print((a[4] < 10 ? " " : "") + a[4] + " ");
System.out.print((a[5] < 10 ? " " : "") + a[5] + " ");
System.out.print((a[6] < 10 ? " " : "") + a[6] + " ");
System.out.print((a[7] < 10 ? " " : "") + a[7] + " ");
System.out.print((a[8] < 10 ? " " : "") + a[8] + " ");
System.out.print((a[9] < 10 ? " " : "") + a[9] + " ");
System.out.println();
double n = (a[0] + a[1] + a[2] + a[3] +
a[4] + a[5] + a[6] + a[7] +
a[8] + a[9]) / 10;
System.out.println("The minimum number is: " + a[0]);
System.out.println("The maximum number is: " + a[9]);
System.out.println("The average value is: " + n);
System.out.println("The median is: " + a[4]);
}
}
New Code
import java.util.Scanner;
import java.math.*;
public class MakeMeBetterImproved {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int[] numbers = new int[10];
int array = 0;
System.out.println("Enter 10 integers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = kybd.nextInt();
int MyIntArray = array + i;
}
System.out.println("The minimum number is: " + math.min);
System.out.println("The maximum number is: " + math.max);
System.out.println("The average value is: " + math.average);
System.out.println("The median is: " + math.median);
}
}
Consider using a more dynamic structure than a primitive array.
I like ArrayLists: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Reorganize your long code into while or for loops.
An example:
ArrayList<Integer> a = new ArrayList<Integer>();
Scanner b = new Scanner(System.in);
Integer c = null;
while (a.size() != 10) {
System.out.println("Please input a number in the range 1-19 :> ");
c = b.nextInt();
while (c < 1 || c > 19)
{
System.out.println("Not in the range 1-19, please try again :> ");
c = b.nextInt();
}
a.add(c);
}
System.out.println("\nArray contents");
for (int i=0; i<10; i++) {
System.out.print((a.get(i) < 10 ? " " : "") + a.get(i) + " ");
}
(And so on...)
Could you try this? I made a few changes.
package p2;
import java.util.Arrays;
import java.util.Scanner;
public class TicTacToe {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
int[] numbers = new int[10];
int sum = 0;
System.out.println("Enter 10 integers: ");
for (int i = 0; i < numbers.length; i++) {
numbers[i] = kybd.nextInt();
sum += numbers[i];
}
Arrays.sort(numbers);
System.out.println("The minimum number is: " + numbers[0]);
System.out.println("The maximum number is: " + numbers[9]);
System.out.println("The average value is: " + sum / numbers.length);
System.out.println("The median is: " + median(numbers));
}
public static double median(int[] m) {
int middle = m.length / 2;
if (m.length % 2 == 1) {
return m[middle];
} else {
return (m[middle - 1] + m[middle]) / 2.0;
}
}
}
I'm working on a coin flip assignment and I have the majority of it functioning properly (albeit in a less elegant fashion compared to the code I see on here).
I'm trying to find a way to tell the user which number appears most in their flips, and if heads are assigned to even #s, and tails to odd #s, which one came up the most. I'm looking for suggestions to implement these features.
Here is the code thus far:
import java.io.*;
import java.util.*;
public class coinFlip {
public static void main(String[] args) throws IOException {
// declare in as a BufferedReader; used to gain input from the user
BufferedReader in;
in = new BufferedReader(new InputStreamReader(System.in));
//declare variables
int flips;
int anArray[];
int x;
int r;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
int counter7 = 0;
int counter8 = 0;
int counter9 = 0;
int counter10 = 0;
System.out.println("How many times would you like to flip your coin?");
flips = Integer.parseInt(in.readLine());
if (flips > 1000) {
System.out.println("Invalid input, restart program!");
}
if(flips <= 1000) {
System.out.println("You want to flip " + flips + " times");
anArray = new int[flips];
for(x = 0; x < flips; x++) {
r = (int) Math.round(Math.random()*9)+1;
anArray[x] = r;
System.out.println(anArray[x]);
if (anArray[x] == 1) {
counter1 += 1;
}
else if (anArray[x] == 2) {
counter2 += 1;
}
else if (anArray[x] == 3) {
counter3 += 1;
}
else if (anArray[x] == 4) {
counter4 += 1;
}
else if (anArray[x] == 5) {
counter5 += 1;
}
else if (anArray[x] == 6) {
counter6 += 1;
}
else if (anArray[x] == 7) {
counter7 += 1;
}
else if (anArray[x] == 8) {
counter8 += 1;
}
else if (anArray[x] == 9) {
counter9 += 1;
}
else if (anArray[x] == 10) {
counter10 += 1;
}
}
System.out.println("\n You rolled 1 " + counter1 + " times.");
System.out.println("You rolled 2 " + counter2 + " times.");
System.out.println("You rolled 3 " + counter3 + " times.");
System.out.println("You rolled 4 " + counter4 + " times.");
System.out.println("You rolled 5 " + counter5 + " times.");
System.out.println("You rolled 6 " + counter6 + " times.");
System.out.println("You rolled 7 " + counter7 + " times.");
System.out.println("You rolled 8 " + counter8 + " times.");
System.out.println("You rolled 9 " + counter9 + " times.");
System.out.println("You rolled 10 " + counter10 + " times.");
}
}
}
import java.io.*;
import java.util.Random;
public class CoinFlip {
public static void main(final String[] args) throws IOException {
// declare in as a BufferedReader; used to gain input from the user
final BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//declare variables
System.out.println("How many times would you like to flip your coin?");
final int flips = Integer.parseInt(in.readLine());;
if (flips > 1000) {
System.out.println("Invalid input, restart program!");
return;
}
System.out.println("You want to flip " + flips + " times");
final int[] counters = new int[10],
side = new int[2];
int r=0,x,max=0;
final Random rand = new Random();
for(x = 0; x < flips; ++x) {
r = rand.nextInt(10);
System.out.println(r+1);
counters[r]++;
}
for ( x = 0; x < counters.length; ++x )
{
System.out.println("You rolled " + (x+1) + " " + counters[x] + " times.");
if ( counters[x] > max )
{
max = counters[x];
r = x+1;
}
side[x%2] += counters[x];
}
System.out.println(r + " was rolled most.");
System.out.println("You rolled " + side[0] + " heads and " + side[1] + " tails." );
}
}
Using loops, as shown in another answer, will make life much easier.
There is a more critical logic error in your code:
You round the output of Math.random(), which gives a float between 0 and 1, and round that to get an integer. The following table shows what output you'll get from your code in respect to the RNG:
| Math.random() output | Resulting Integer |
| 0 ~ 0.04999 | 0 |
| 0.05 ~ 0.14999 | 1 |
| ...... | ..... |
| 0.95 ~ 0.99999 | 10 |
See the problem? 0 and 10 appear only half as much as the other numbers.
You should either floor() the output, or use Random.nextInt() to generate a uniform distribution of ints.
This would make your life much easier:
int counter[10];
...
for(x = 0; x < flips; x++) {
r = (int) Math.round(Math.random()*9)+1;
anArray[x] = r;
System.out.println(anArray[x]);
counter[r-1]++;
}
for(i=1; i <= counter.length; i++)
System.out.println("You rolled " + i + " " + counter[i-1] + " times.");
For your other two problems, there's nothing to really "suggest". Just iterate over counter, remember the largest value, and add up the even and odd indices separately.