Scanner only accepting input once - java

Recently, I've been working on my Noughts and Crosses game, but I've stumbled upon a problem that I can't seem to be able to fix.
Whenever I type in something the first time, it works and prints out the board, however, from that point onward, it just stops checking and printing out the board.
while(inf){
String temp = input.next();
if(playerTurn == 1){
if(amountP1 <= 3){
if(temp.equalsIgnoreCase("00")){
if(board[0][0] == 0){
board[0][0] = 1;
showBoard(board);
playerTurn = 2;
amountP1++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("01")){
if(board[0][1] == 0){
board[0][1] = 1;
showBoard(board);
playerTurn = 2;
amountP1++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("02")){
if(board[0][2] == 0){
board[0][2] = 1;
showBoard(board);
playerTurn = 2;
amountP1++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("10")){
if(board[1][0] == 0){
board[1][0] = 1;
showBoard(board);
playerTurn = 2;
amountP1++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("11")){
if(board[1][1] == 0){
board[1][1] = 1;
showBoard(board);
playerTurn = 2;
amountP1++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("12")){
if(board[1][2] == 0){
board[1][2] = 1;
showBoard(board);
playerTurn = 2;
amountP1++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("20")){
if(board[2][0] == 0){
board[2][0] = 1;
showBoard(board);
playerTurn = 2;
amountP1++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("21")){
if(board[2][1] == 0){
board[2][1] = 1;
showBoard(board);
playerTurn = 2;
amountP1++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("22")){
if(board[2][2] == 0){
board[2][2] = 1;
showBoard(board);
playerTurn = 2;
amountP1++;
}
else{
System.out.println("This space is already occupied!");
}
}
}
else if(playerTurn == 2){
if(amountP2 <= 3){
if(temp.equalsIgnoreCase("00")){
if(board[0][0] == 0){
board[0][0] = 2;
showBoard(board);
playerTurn = 1;
amountP2++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("01")){
if(board[0][1] == 0){
board[0][1] = 2;
showBoard(board);
playerTurn = 1;
amountP2++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("02")){
if(board[0][2] == 0){
board[0][2] = 2;
showBoard(board);
playerTurn = 1;
amountP2++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("10")){
if(board[1][0] == 0){
board[1][0] = 2;
showBoard(board);
playerTurn = 1;
amountP2++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("11")){
if(board[1][1] == 0){
board[1][1] = 2;
showBoard(board);
playerTurn = 1;
amountP2++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("12")){
if(board[1][2] == 0){
board[1][2] = 2;
showBoard(board);
playerTurn = 1;
amountP2++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("20")){
if(board[2][0] == 0){
board[2][0] = 2;
showBoard(board);
playerTurn = 1;
amountP2++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("21")){
if(board[2][1] == 0){
board[2][1] = 2;
showBoard(board);
playerTurn = 1;
amountP2++;
}
else{
System.out.println("This space is already occupied!");
}
}
else if(temp.equalsIgnoreCase("22")){
if(board[2][2] == 0){
board[2][2] = 2;
showBoard(board);
playerTurn = 1;
amountP2++;
}
else{
System.out.println("This space is already occupied!");
}
}
}
}
}
}
And this is the method for printing out the board:
public static void showBoard(int x[][]){
int rowNumber = 1;
for(int row = 0 ; row < x.length ; row++){
for(int column = 0 ; column < x[row].length ; column++){
if(x[row][column] == 0){
if(rowNumber <= 2){
System.out.print(" E");
rowNumber++;
}
else if(rowNumber == 3){
System.out.println(" E");
rowNumber = 1;
}
}
else if(x[row][column] == 1){
if(rowNumber <= 2){
System.out.print(" X");
rowNumber++;
}
else if(rowNumber == 3){
System.out.println(" X");
rowNumber = 1;
}
}
else if(x[row][column] == 2){
if(rowNumber <= 2){
System.out.print(" O");
rowNumber++;
}
else if(rowNumber == 3){
System.out.println(" O");
rowNumber = 1;
}
}
}
}
}
Also, I am aware that this code is a big mess and there's problably a ton of other, more efficient ways to do this, but since I am a fairly new programmer, I chose to go with functionality over efficiency with this one.

Your else if(playerTurn == 2) line needs to be pulled out to the same level as if(playerTurn == 1):
if(playerTurn == 1){
if(amountP1 <= 3){
//...
}
else if(playerTurn == 2){
//...
}
}
should become
if(playerTurn == 1){
if(amountP1 <= 3){
//...
}
} else if(playerTurn == 2) {
//...
}

Related

TicTacToe using 2D array in java

Hello Everyone I need help.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char[][] board = {
{'?','?','?'},
{'?','?','?'},
{'?','?','?'}
};
System.out.print("Type any key to play the game and type 'n' to stop the game: ");
String Stop = sc.nextLine();
while(true){
if(Stop.equals("n"))break;
System.out.print("Player" + "[" + "X" + "]: ");
int PlayerX = sc.nextInt();
if(PlayerX == 1){
board[2][0] = 'x';
}
if(PlayerX == 2){
board[2][1] = 'x';
}
if(PlayerX == 3){
board[2][2] = 'x';
}
if(PlayerX == 4){
board[1][0] = 'x';
}
if(PlayerX == 5){
board[1][1] = 'x';
}
if(PlayerX == 6){
board[1][2] = 'x';
}
if(PlayerX == 7){
board[0][0] = 'x';
}
if(PlayerX == 8){
board[0][1] = 'x';
}
if(PlayerX == 9){
board[0][2] = 'x';
}
for(char[] x1 : board){
for(char x2 : x1){
System.out.print(x2 + "\t");
}
System.out.println();
}
System.out.print("Player" + "[" + "O" + "]: ");
int PlayerO = sc.nextInt();
if(PlayerO == 1){
board[2][0] = 'o';
}
if(PlayerO == 2){
board[2][1] = 'o';
}
if(PlayerO == 3){
board[2][2] = 'o';
}
if(PlayerO == 4){
board[1][0] = 'o';
}
if(PlayerO == 5){
board[1][1] = 'o';
}
if(PlayerO == 6){
board[1][2] = 'o';
}
if(PlayerO == 7){
board[0][0] = 'o';
}
if(PlayerO == 8){
board[0][1] = 'o';
}
if(PlayerO == 9){
board[0][2] = 'o';
}
for(char[] x1 : board){
for(char x2 : x1){
System.out.print(x2 + "\t");
}
System.out.println();
}
}
}
}
I am trying to make a simple tictactoes program in java. I am already done in placing the X and O, but I am struggling on checking of wether there is a winner or not.
I am confused on what code I will type o check the winner of the program.
You simply just need to write some code to check if there are 3 matches in each row column and diagonal.
You can utilise for loops to do this more efficiently
public static char checkWinner(char[][] board) {
// Check rows
for (int i = 0; i < 3; i++) {
if (board[i][0] != '?' && board[i][0] == board[i][1] && board[i][1] == board[i][2]) {
return board[i][0];
}
}
// Check columns
for (int j = 0; j < 3; j++) {
if (board[0][j] != '?' && board[0][j] == board[1][j] && board[1][j] == board[2][j]) {
return board[0][j];
}
}
// Check diagonal
if (board[0][0] != '?' && board[0][0] == board[1][1] && board[1][1] == board[2][2]) {
return board[0][0];
}
// Check anti-diagonal
if (board[0][2] != '?' && board[0][2] == board[1][1] && board[1][1] == board[2][0]) {
return board[0][2];
}
// No winner
return '?';
}
If you havent come accross for loops yet, there are plenty of good tutorials out there such as https://www.w3schools.com/java/java_for_loop.asp
(Note, you can also use loops to clean up some of your pre-existing code)

Weird behavior of for loops in specific conditions. Processing

I'm learning how to use processing and tried to make a simple snake game, while doing it it does show (although it was cntrl+c cntrl+v from the first one, which was up) a Weir behavior in for loops specifically for going right or down.
i managed to fix the 'down' problem by simply changing
for(int k=0;k<56;k++)
to
for(int k=55;k<=0;k--)
which is exactly the same thing, isn't it? i am i missing something?
int [][] snakeHead = new int[60][60];
int game = 1;
int value = 0;
String s = "You lost\nPress SHIFT to Restart";
void setup(){
size(600,600);
frameRate(10);
for(int i=0;i<56;i++){
for(int k=0;k<56;k++){
snakeHead[i][k] = 0;
}
}
snakeHead[1][22] = 1;
game = 1;
value = 0;
}
void draw(){
background(0);
fill(255);
rect(20, 20, 560, 560);
if(game == 1){
for(int i=0;i<56;i++){
for(int k=0;k<56;k++){
if(snakeHead[i][k] == 1){
fill(0,255,0);
rect(20+i*10, 20+k*10, 10,10);
}
}
}
if(value == 1){
up();
}else if(value == 2){
down();
}else if(value == 3){
left();
}else if(value == 4){
right();
}
}
else{
textSize(32);
textAlign(CENTER);
fill(0,0,255);
text(s, 300, 300);
}
}
void keyPressed(){
if(key == CODED){
if(keyCode == UP){
value = 1;
}
else if(keyCode == DOWN){
value = 2;
}
else if(keyCode == LEFT){
value = 3;
}
else if(keyCode == RIGHT){
value = 4;
}else if(keyCode == SHIFT){
setup();
}
}
}
void up(){
for(int i=0;i<56;i++){
for(int k=0;k<56;k++){
if(snakeHead[i][k] == 1 && k == 0){
game = 0;
}else if(snakeHead[i][k] == 1){
snakeHead[i][k-1] = 1;
snakeHead[i][k]=0;
}
}
}
}
void down(){
for(int i=0;i<56;i++){
for(int k=0;k<56;k++){
if(snakeHead[i][k] == 1 && k == 55){
game = 0;
}else if(snakeHead[i][k] == 1 && k != 55){
snakeHead[i][k+1] = 1;
snakeHead[i][k] = 0;
}
}
}
}
void right(){
for(int i=0;i<56;i++){
for(int k=0;k<56;k++){
if(snakeHead[i][k] == 1 && i == 55){
game = 0;
}else if(snakeHead[i][k] == 1 && i != 55){
snakeHead[i+1][k] = 1;
snakeHead[i][k]=0;
}
}
}
}
void left(){
for(int i=0;i<56;i++){
for(int k=0;k<56;k++){
if(snakeHead[i][k] == 1 && i == 0){
game = 0;
}else if(snakeHead[i][k] == 1){
snakeHead[i-1][k] = 1;
snakeHead[i][k]=0;
}
}
}
}
Your problem in the right and down that in both you update the head down the loop (with i+1 or j+1) so the else block get execute more then once (in the up and left you doing i-1 and j-1 so it doesn't happens there).
Let look at the right function to demonstrate:
void right(){
for(int i=0;i<56;i++){
for(int k=0;k<56;k++){
if(snakeHead[i][k] == 1 && i == 55){
game = 0;
} else if(snakeHead[i][k] == 1 && i != 55){
snakeHead[i+1][k] = 1; // update the sankeHead to i+1 which will be reached in the next iteration in i so basiclly keep moving right till reach if block
snakeHead[i][k]=0;
}
} // end k loop
} // end i loop
}
To fix this all you need to do is add return because you only want to move the snakeHead once!
so:
void right(){
for(int i=0;i<56;i++){
for(int k=0;k<56;k++){
if(snakeHead[i][k] == 1 && i == 55){
game = 0;
return;
} else if(snakeHead[i][k] == 1 && i != 55){
snakeHead[i+1][k] = 1;
snakeHead[i][k]=0;
return;
}
} // end k loop
} // end i loop
}

How to fix a program that incorrectly calculates the percentages of numbers in Java?

I am trying to find the frequency of each letter in a document, so this program counts up the number of occurrences of each letter, and then finds the total number of letters. Then it's supposed to find the frequency, the problem is it counts the letters correctly and the total, but the percentages incorrectly. How do I calculate the percentage?
//find number of occurrences for each letter
String[] letter = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
int[] count = new int[26];
int totalCount = 0;
for(int i = 0; i < subset.length(); i++)
{
char letters = subset.charAt(i);
if(letters == 'a')
count[0]++;
else if(letters == 'b')
count[1]++;
else if(letters == 'c')
count[2]++;
else if(letters == 'd')
count[3]++;
else if(letters == 'e')
count[4]++;
else if(letters == 'f')
count[5]++;
else if(letters == 'g')
count[6]++;
else if(letters == 'h')
count[7]++;
else if(letters == 'i')
count[8]++;
else if(letters == 'j')
count[9]++;
else if(letters == 'k')
count[10]++;
else if(letters == 'l')
count[11]++;
else if(letters == 'm')
count[12]++;
else if(letters == 'n')
count[13]++;
else if(letters == 'o')
count[14]++;
else if(letters == 'p')
count[15]++;
else if(letters == 'q')
count[16]++;
else if(letters == 'r')
count[17]++;
else if(letters == 's')
count[18]++;
else if(letters == 't')
count[19]++;
else if(letters == 'u')
count[20]++;
else if(letters == 'v')
count[21]++;
else if(letters == 'w')
count[22]++;
else if(letters == 'x')
count[23]++;
else if(letters == 'y')
count[24]++;
else if(letters == 'z')
count[25]++;
}
//find total characters in document
double[] frequency = new double[26];
for(int i = 0; i < 26; i++)
{
totalCount += count[i];
frequency[i] = ((double)count[i] / (totalCount + 1)) * 100; //the problem
}
System.out.println(totalCount);
//for(int i = 0; i < 26; i++)
//{
// frequency[i] = (double)(count[i] / totalCount * 100);
//}
//print
System.out.println(" Letter Occurrences Frequency");
System.out.println("--------------------------------");
for(int i = 0; i < 26; i++)
{
System.out.println(" " + letter[i] + "\t " + count[i] + "\t " + df.format(frequency[i]));
}
The frequency needs to be calculated after you have the totalCount:
for(int i = 0; i < 26; i++) {
totalCount += count[i];
}
System.out.println(totalCount);
System.out.println(" Letter Occurrences Frequency");
System.out.println("--------------------------------");
for(int i = 0; i < 26; i++) {
frequency[i] = ((double)count[i] / (totalCount + 1)) * 100;
System.out.println(" " + letter[i] + "\t " + count[i] + "\t " + df.format(frequency[i]));
}
Side note
You don't need a for loop for totalCount since it's just the length of the string (i.e. totalCount = subset.length())
you wouldn't need 25 if else statements to find letter counts... Just do:
count[subset.charAt(i) - 61]++;
61 is the ASCII value for letter 'a'

Java - Roman Numeral validity

I am writing a program to add two roman numerals without converting to any bases. I have everything working except I am not sure how to check if my input String is a valid roman numeral or not.
These are the rules to check validity:
Five in a row of any digit is not allowed
Some digits are allowed in runs of up to 4. They are I,X,C, and M. The others (V,L,D) can only appear singly.
Some lower digits can come before a higher digit, but only if they appear singly. E.g. "IX" is ok but "IIIX" is not.
But this is only for pairs of digits. Three ascending numbers in a row is invalid. E.g. "IX" is ok but "IXC" is not.
A single digit with no runs is always allowed
I have not really been able to make much progress with this step and don't have anything working yet. Any help would be great!
Why not use regular expression:
boolean valid = word.matches("^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$");
Look at the post of paxdiablo:
How do you match only valid roman numerals with a regular expression?
Loop through each character in the string.
Use a if conditions to check which character it is.
Use the if conditions to check for the roman numeral rule violations in the adjacent characters to the selected character.
for(int i = 0; i < s.length(); i++){
if (s[i] == 'V'){
**Check if the character before of after is also 'V'. Then it is a violation
}
else if(s[i] == 'L'){
**Conditions for 'L' etc.
}
}
This is what I have come up with based on my rules. Any thoughts on refactoring this to make it simpler?
public static boolean checkValidity (String s1, HashSet<Character> romanNumerals){
HashSet<Character> alreadyContained = new HashSet<Character>();
if (s1.length() == 1 && romanNumerals.contains(s1.charAt(0))){
return true;
}
int i = 0;
while (i < s1.length()){
if (s1.charAt(i) == 'M'){
if (alreadyContained.contains('M')){
return false;
}
int count = 1;
i++;
while (s1.charAt(i) == 'M'){
i++;
count++;
}
alreadyContained.add('M');
if (count >= 5){
return false;
}
}
else if (s1.charAt(i) == 'D'){
if (alreadyContained.contains('D')){
return false;
}
alreadyContained.add('D');
if (!alreadyContained.contains('M')){
alreadyContained.add('M');
}
i++;
if ((i < s1.length()) && (s1.charAt(i) == 'D')){
return false;
}
}
else if (s1.charAt(i) == 'L'){
if (alreadyContained.contains('L')){
return false;
}
alreadyContained.add('L');
if (!alreadyContained.contains('M')){
alreadyContained.add('M');
}
if (!alreadyContained.contains('D')){
alreadyContained.add('D');
}
if (!alreadyContained.contains('C')){
alreadyContained.add('C');
}
i++;
if ((i < s1.length()) && (s1.charAt(i) == 'L')){
return false;
}
}
else if (s1.charAt(i) == 'V'){
if (alreadyContained.contains('V')){
return false;
}
alreadyContained.add('V');
if (!alreadyContained.contains('M')){
alreadyContained.add('M');
}
if (!alreadyContained.contains('D')){
alreadyContained.add('D');
}
if (!alreadyContained.contains('C')){
alreadyContained.add('C');
}
if (!alreadyContained.contains('L')){
alreadyContained.add('L');
}
if (!alreadyContained.contains('X')){
alreadyContained.add('X');
}
i++;
if ((i < s1.length()) && (s1.charAt(i) == 'V')){
return false;
}
}
else if (s1.charAt(i) == 'C'){
if (alreadyContained.contains('C')){
return false;
}
int count = 1;
i++;
if ((i < s1.length()) &&(s1.charAt(i) == 'M' || s1.charAt(i) == 'D')){
i++;
}
else if (i < s1.length() && s1.charAt(i) == 'C'){
while ((i < s1.length()) && (s1.charAt(i) == 'C')){
i++;
count++;
}
}
alreadyContained.add('C');
if (!alreadyContained.contains('M')){
alreadyContained.add('M');
}
if (!alreadyContained.add('D')){
alreadyContained.add('D');
}
if (count >= 5){
return false;
}
}
else if (s1.charAt(i) == 'X'){
if (alreadyContained.contains('X')){
return false;
}
int count = 1;
i++;
if ((i < s1.length()) && (s1.charAt(i) == 'D' || s1.charAt(i) == 'M')){
return false;
}
while ((i < s1.length()) && s1.charAt(i) == 'X'){
i++;
count++;
}
alreadyContained.add('X');
if (count >= 5){
return false;
}
}
else if (s1.charAt(i) == 'I'){
if (alreadyContained.contains('I')){
return false;
}
alreadyContained.add('I');
i++;
int count = 1;
if ((i < s1.length()) && (s1.charAt(i) != 'I' && s1.charAt(i) != 'X' && s1.charAt(i) != 'V')){
return false;
}
else if (i < s1.length() && s1.charAt(i) == 'I'){
while (i < s1.length() && s1.charAt(i) == 'I'){
i++;
count++;
}
if (count >= 4){
return false;
}
}
}
else if (!romanNumerals.contains(s1.charAt(i))){
return false;
}
}
return true;
}

(Java) Using nested loops

My assignment instructions are "rolling" 2 dice and getting the sum and then finding the probability that that sum came up based on how many times the user wants to roll the die. I must use a nested loop and I can't use separate loops for each dice combination (which I haven't done). I am not allowed to use arrays in this assignment.
Write a program to simulate tossing a pair of 11-sided dice and determine the percentage of times each possible combination of the dice is rolled.
Create a new project called 5.05 Random Dice in the Mod05 Assignments folder.
Create a class called DiceProbability in the newly created project folder.
Ask the user to input how many times the dice will be rolled.
Calculate the probability of each combination of dice. (You may want to start with more familiar six-sided dice.)
Print the results neatly in two columns
I need help in finding out what I put into the second "for" loop. Sorry for the messy list of integers and if statements. The code is unfinished.
import java.util.Random;
import java.util.Scanner;
public class DiceProbability
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Random randNum = new Random();
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
int count10 = 0;
int count11= 0;
int count12= 0;
int count13 = 0;
int count14 = 0;
int count15 = 0;
int count16 = 0;
int count17 = 0;
int count18 = 0;
int count19 = 0;
int count20 = 0;
int count21 = 0;
int count22 = 0;
int die1 = 0, die2 = 0;
int rolls = 0;
int actualDiceSum;
double probabilityOfDice = 0.0;
System.out.print("Number of Rolls: ");
rolls = in.nextInt();
for(int timesRolled = 0; timesRolled < rolls; timesRolled++)
{
die1 = randNum.nextInt(12);
die2 = randNum.nextInt(12);
actualDiceSum = die1 + die2;
for()
{
if(actualDiceSum == 2){
count2++;
probabilityOfDice = count2 / rolls;
}
else if(actualDiceSum == 3){
count3++;
probabilityOfDice = count3 / rolls;
}
else if(actualDiceSum == 4){
count4++;
probabilityOfDice = count4 / rolls;
}
else if(actualDiceSum == 5){
count5++;
probabilityOfDice = count5 / rolls;
}
else if(actualDiceSum == 6){
count6++;
probabilityOfDice = count6 / rolls;
}
else if(actualDiceSum == 7){
count7++;
probabilityOfDice = count7 / rolls;
}
else if(actualDiceSum == 8){
count8++;
probabilityOfDice = count8 / rolls;
}
else if(actualDiceSum == 9){
count9++;
probabilityOfDice = count9 / rolls;
}
else if(actualDiceSum == 10){
count10++;
probabilityOfDice = count10 / rolls;
}
else if(actualDiceSum == 11){
count11++;
probabilityOfDice = count11 / rolls;
}
else if(actualDiceSum == 12){
count12++;
probabilityOfDice = count12 / rolls;
}
else if(actualDiceSum == 13){
count13++;
probabilityOfDice = count13 / rolls;
}
else if(actualDiceSum == 14){
count14++;
probabilityOfDice = count14 / rolls;
}
else if(actualDiceSum == 15){
count15++;
probabilityOfDice = count15 / rolls;
}
else if(actualDiceSum == 16){
count16++;
probabilityOfDice = count16 / rolls;
}
else if(actualDiceSum == 17){
count17++;
probabilityOfDice = count17 / rolls;
}
else if(actualDiceSum == 18){
count18++;
probabilityOfDice = count18 / rolls;
}
else if(actualDiceSum == 19){
count19++;
probabilityOfDice = count19 / rolls;
}
else if(actualDiceSum == 20){
count20++;
probabilityOfDice = count20 / rolls;
}
else if(actualDiceSum == 21){
count21++;
probabilityOfDice = count21 / rolls;
}
else if(actualDiceSum == 22){
count22++;
probabilityOfDice = count22 / rolls;
}
}
}
System.out.println("Sum of Dice \t\t Probability");
System.out.println("2's\t\t" + probabilityOfDice + "%");
System.out.println("3's\t\t" + probabilityOfDice + "%");
System.out.println("4's\t\t" + probabilityOfDice + "%");
System.out.println("5's\t\t" + probabilityOfDice + "%");
System.out.println("6's\t\t" + probabilityOfDice + "%");
System.out.println("7's\t\t" + probabilityOfDice + "%");
System.out.println("8's\t\t" + probabilityOfDice + "%");
System.out.println("9's\t\t" + probabilityOfDice + "%");
System.out.println("10's\t\t" + probabilityOfDice + "%");
System.out.println("11's\t\t" + probabilityOfDice + "%");
System.out.println("12's\t\t" + probabilityOfDice + "%");
System.out.println("13's\t\t" + probabilityOfDice + "%");
System.out.println("14's\t\t" + probabilityOfDice + "%");
System.out.println("15's\t\t" + probabilityOfDice + "%");
System.out.println("16's\t\t" + probabilityOfDice + "%");
System.out.println("17's\t\t" + probabilityOfDice + "%");
System.out.println("18's\t\t" + probabilityOfDice + "%");
System.out.println("19's\t\t" + probabilityOfDice + "%");
System.out.println("20's\t\t" + probabilityOfDice + "%");
System.out.println("21's\t\t" + probabilityOfDice + "%");
System.out.println("22's\t\t" + probabilityOfDice + "%");
}
}
Well according to me you don't require 2nd for loop.
Every time a dice is rolled you calculate the the sum and increase the count according to the sum.
you would require to use separate variables for calculating the probability of each sum.
For example
Probability of count2 = (count2/number of rolls);
Probability of count3 = (count2/number of rolls);
Use separate variables for probability of counts
try this code
import java.util.Random;
import java.util.Scanner;
public class DiceProbability
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
Random randNum = new Random();
int count2 = 0;
int count3 = 0;
int count4 = 0;
int count5 = 0;
int count6 = 0;
int count7 = 0;
int count8 = 0;
int count9 = 0;
int count10 = 0;
int count11= 0;
int count12= 0;
int count13 = 0;
int count14 = 0;
int count15 = 0;
int count16 = 0;
int count17 = 0;
int count18 = 0;
int count19 = 0;
int count20 = 0;
int count21 = 0;
int count22 = 0;
int die1 = 0, die2 = 0;
int rolls = 0;
int actualDiceSum;
double probabilityOfDice = 0.0;
System.out.print("Number of Rolls: ");
rolls = in.nextInt();
for(int timesRolled = 0; timesRolled < rolls; timesRolled++)
{
die1 = randNum.nextInt(12);
die2 = randNum.nextInt(12);
actualDiceSum = die1 + die2;
if(actualDiceSum == 2){
count2++;
}
else if(actualDiceSum == 3){
count3++;
}
else if(actualDiceSum == 4){
count4++;
}
else if(actualDiceSum == 5){
count5++;
}
else if(actualDiceSum == 6){
count6++;
}
else if(actualDiceSum == 7){
count7++;
}
else if(actualDiceSum == 8){
count8++;
}
else if(actualDiceSum == 9){
count9++;
}
else if(actualDiceSum == 10){
count10++;
}
else if(actualDiceSum == 11){
count11++;
}
else if(actualDiceSum == 12){
count12++;
}
else if(actualDiceSum == 13){
count13++;
}
else if(actualDiceSum == 14){
count14++;
}
else if(actualDiceSum == 15){
count15++;
}
else if(actualDiceSum == 16){
count16++;
}
else if(actualDiceSum == 17){
count17++;
}
else if(actualDiceSum == 18){
count18++;
}
else if(actualDiceSum == 19){
count19++;
}
else if(actualDiceSum == 20){
count20++;
}
else if(actualDiceSum == 21){
count21++;
}
else if(actualDiceSum == 22){
count22++;
}
}
}
System.out.println("Sum of Dice \t\t Probability");
System.out.println("2's\t\t" + count2/rolls + "%");
System.out.println("3's\t\t" + count3/rolls + "%");
System.out.println("4's\t\t" + count4/rolls + "%");
System.out.println("5's\t\t" + count5/rolls + "%");
//and so on...
}
}
I think you need to use two dimensional array as below:
int rolls = 0;
System.out.print("Number of Rolls: ");
rolls = in.nextInt();
int[][] numAndOccuranceCount= new int[11][2]; //sum will be between 2 -12
//initialize your array
for(int indx=0; indx<11;indx++){
numAndOccuranceCount[indx] = new int[]{indx+2,0);
}
for(int timesRolled = 0; timesRolled < rolls; timesRolled++){
die1 = randNum.nextInt(12);
die2 = randNum.nextInt(12);
actualDiceSum = die1 + die2;
for(int indx=0; indx<11;indx++){
if(actualDiceSum == numAndOccuranceCount[i][0]){
numAndOccuranceCount[indx][1] = numAndOccuranceCount[indx][1]+1;
break;
}
}
}
double proabability = 0.0;
//compute and print the probablity as below:
for(int indx=0; indx<11;indx++){
proabability = numAndOccuranceCount[indx][1]/rolls;
System.out.println("Probability of "+ numAndOccuranceCount[indx][0] +" = "+proabability);
}
I have some comment on your code.
Based on the instruction, you sum up the dice1 and dice2 is not a correct approach 'cause 1 + 5 = 2 + 4 = 3 + 3 but they are different. So we have to calculate the possibility based on the combination, not the sum.
Here's my code:
DTO class:
public class DiceCombination {
private int dice1;
private int dice2;
public DiceCombination(int dice1, int dice2) {
this.dice1 = dice1;
this.dice2 = dice2;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Combination of [dice " + dice1 + " and dice " + dice2 + "]";
}
/* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
if(dice1 < dice2) {
return prime*dice1 + dice2;
}
else {
return prime*dice2 + dice1;
}
}
/* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DiceCombination other = (DiceCombination) obj;
if ((dice1 == other.dice1 && dice2 == other.dice2) || (dice1 == other.dice2 && dice2 == other.dice1))
return true;
return false;
}
}
Main class:
public class Posibility {
public static void main(String[] args) {
Map<DiceCombination,Integer> possibility = new HashMap<DiceCombination,Integer>();
int dice1;
int dice2;
int roll = 400; // value here should be inputted from user, you may change any value you want
Random randNum = new Random();
for(int i = 0; i < roll; i ++) {
dice1 = randNum.nextInt(12);
dice2 = randNum.nextInt(12);
DiceCombination dc = new DiceCombination(dice1, dice2);
if(possibility.containsKey(dc)) {
possibility.put(dc , possibility.get(dc) + 1);
}
else {
possibility.put(dc, 1);
}
}
for(DiceCombination key : possibility.keySet()) {
System.out.println("Result: " + key.toString() + " is " + ((double)possibility.get(key)/roll));
}
}
}
I agree with #Thinhbk that the question is technically worded in terms of combinations not sums but the picture in the link shows sums so I believe sums is the intention. The combinations approach as you have coded is impressive but too advanced for what appears to be an intro course to Java. I like how the picture shows that the IDE is BlueJ. Takes me back. Anyway, the assignment description doesn't specify the need for an inner for loop. I see #user1713336's edit that arrays are not allowed else before your (user1713336's) first loop you could add:
int[] count = new int[23];
//0 is the default value for each
//int[22] is the 23rd value in the array
What is your entire inner for loop could be replaced with:
count[actualDiceSum]++;
Then while printing in a for loop, print count[i]/rolls*100 and start int i at 2, the lowest possible value. I suspect you'll learn arrays next so I wanted to show how it'd be done.
Since you can't use arrays, your countx = 0; lines are fine as is. Don't calculate the probability in real time. It's unnecessarily and and adds many lines of code, just keep track of the number of times each value is rolled so:
if(actualDiceSum == 2)
count2++;
else if(actualDiceSum == 3)
count3++;
//etc
Note that you don't need to use {} if only one line of code is tied to the if or while statement as shown. Then print the same way as before, count2/rolls*100 (Multiply by 100 since the picture showed percentages, not ratios).

Categories