I don't get what does "unreachable code" means ?
Here in the last line of my code double probabilityOfWin = wins / (wins + loses); it says unreachable code.
import java.util.Random;
public class CrapsGame {
public static final int GAMES = 9999;
public static void main(String[] args) {
Random randomGenerator1 = new Random();
Random randomGenerator2 = new Random();
Random randomGenerator3 = new Random();
Random randomGenerator4 = new Random();
int dice1 = randomGenerator1.nextInt(6) + 1;
int dice2 = randomGenerator2.nextInt(6) + 1;
int comeoutSum = dice1 + dice2;
int point = 0;
// The comeout roll
if (comeoutSum == 7 || comeoutSum == 12)
System.out.println("wins");
else if ( comeoutSum == 2 || comeoutSum == 3 || comeoutSum == 12)
System.out.println("loses");
else
point = comeoutSum;
int wins = 0;
int loses = 0;
while(GAMES <= 9999)
{
dice1 = randomGenerator3.nextInt(6) + 1;
dice2 = randomGenerator4.nextInt(6) + 1;
int sum = dice1 + dice2;
if (sum == point)
wins++;
else if (sum == 7)
loses++;
}
double probabilityOfWin = wins / (wins + loses);
}
}
This loop here:
while(GAMES <= 9999)
{
...
}
resolves to while (true) because the value of GAMES is never modified. So any code that comes after (in your case, double probabilityOfWin = wins / (wins + loses);) is deemed unreachable.
You did not make any change to the constant GAME. So while loop will never terminate. Last line of code is unreachable.
Unreachable means the code never gets executed. For example,
return 15;
int a = 12;
Then the last line of code will not get executed because the function has already returned.
Related
This is my first CS class ever, and I'm trying to learn everything the best that can. In this loop I am trying to find valid mastercard numbers using Luhn's formula. The program works, but it's been bugging me that my final for loop outputs 1 number over the correct value, unless I subtract 1 from z after the loop finishes iterating. For example: if the sum = 56 , then z would = 5 , when the correct answer would be 4. How can I fix this going forward?
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class MCGenerator {
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
Random rand = new Random();
System.out.print("How many Mastercard numbers would you like to generate? ");
int quantity = scnr.nextInt();
int x;
int use;
int range;
int appendI;
Long appendL;
String firstDigits;
String append;
String preliminary;
int y;
int c;
int sum;
int z;
int findDigit;
String lastNum;
String cardNumber;
System.out.println("\nHere you go, have fun: ");
for(x = 0; x < quantity; x++ ) {
use = rand.nextInt(2 - 1 + 1) +1;
if(use == 1) {
range = rand.nextInt(55 - 51 + 1) + 51;
}
else {
range = rand.nextInt(272099 - 222100 +1) + 222100;
}
if(range < 56) {
appendL = ThreadLocalRandom.current().nextLong(1000000000000L, 10000000000000L);
append = String.valueOf(appendL);
}
else {
appendI = rand.nextInt(999999999 - 100000000 + 1) + 100000000;
append = String.valueOf(appendI);
}
firstDigits = String.valueOf(range);
preliminary = firstDigits + append;
for(y = 0, sum = 0; y < 15; y++ ) {
c = preliminary.charAt(y) - '0';
if(y % 2 == 0){
c *= 2;
}
if(c > 9) {
c -= 9;
}
sum += c;
}
for(z = 0, findDigit = sum; findDigit > 0; z++){
findDigit = sum + z;
findDigit %= 10;
}
z -= 1;
lastNum = String.valueOf(z);
cardNumber = preliminary + lastNum;
System.out.println(cardNumber);
}
}
}
I'm writing a Java program that will play a game.
Basically you choose the no. of players and rounds, then the program shows you what every player should say, in order, considering the following rules:
-assuming the players are standing in a circle, they start counting one-by-one clockwise until someone reaches a number (larger than 10) made of only the same digit. For example 11, 22, 33, .. , 444 etc, then they start counting counter clockwise
E.g.: P9: 9; P10: 10; P11: 11; P12: 13; P11: 14 etc (P10 = Player 10)
-when the get to a number that is multiple of 7, contains 7 or the sum of the digits is 7, they say "Boltz"
E.g.: P1: 13; P2: Boltz (instead of 14); P3: 15; P4 Boltz (16); P5: Boltz (17); P6:18 etc
I have the code in Java, but i can't seem to get the switching from clockwise turns to counterclockwise at numbers made up from only one digit
Can you please help me on SameDigits function? Thank you!
import java.util.Scanner;
public class Boltz {
private static Scanner keyboard;
public static void main(String[] args) {
keyboard = new Scanner(System.in);
int nPlayers = 0;
int nRounds = 0;
int currentPlayer = 0;
int sum = 0;
int x = 0;
boolean isSameDigit = true;
System.out.print("Cati jucatori sunt? ");
nPlayers = keyboard.nextInt();
System.out.print("Cate runde sunt? ");
nRounds = keyboard.nextInt();
System.out.print("Jucatori: " + nPlayers + "; Runde: " + nRounds + "\n");
for (x = 1; x <= nPlayers * nRounds; x++) {
isSameDigit = SameDigits(currentPlayer);
if (currentPlayer < nPlayers && isSameDigit == false) {
currentPlayer++;
} else {
currentPlayer = 1;
}
if (currentPlayer > 1 && isSameDigit == true) {
currentPlayer--;
} else {
currentPlayer = nPlayers;
}
sum = digitSum(x);
if (x % 7 == 0 || String.valueOf(x).contains("7") || sum == 7) {
System.out.println("P:" + currentPlayer + " Boltz");
} else {
System.out.println("P:" + currentPlayer + " " + x);
}
}
}
public static int digitSum(int num) {
int suma = 0;
while (num > 0) {
suma = suma + num % 10;
num = num / 10;
}
return suma;
}
public static boolean SameDigits(int num) {
int add = 0, add2 = 0;
while (num > 0) {
add = add + num % 10;
add2 = add2 + add % 10;
num = num / 10;
}
if (add == add2) {
return true;
} else {
return false;
}
}
}
If I understand you correctly, you want SameDigits to return true if the number is all the same digits and false otherwise. Single-digit numbers should also return true. This should do it:
public static boolean SameDigits(int num) {
if (num < 0) return false; // or something else?
int onesDigit = num % 10;
num /= 10;
while (num > 0) {
if (onesDigit != num % 10) return false; // fail if digits differ
num /= 10;
}
return true;
}
P.S. You should conform to Java naming conventions and name your methods starting with a lower-case letter (sameDigits instead of SameDigits).
That would be something like:
public static boolean sameDigits(int number) {
//speical case
if (number < 10)
return false;
String string = String.valueOf(number);
for (int i = 1; i <= 9; i++) {
if (string.replaceAll(String.valueOf(i), "").length() == 0)
return true;
}
return false;
}
I'd use a regular expression. This one checks whether a String consists of a single digit, followed by one or more repetitions of the same digit.
public static boolean sameDigits(int arg) {
return Integer.toString(arg).matches("(\\d)\\1+");
}
For those who are familiar with Luhn's Algorithm, I am compiling a program that verify credit card numbers using this Algorithm. Here's what I have already:
Scanner input = new Scanner(System.in);
String ccNum = "";
int product = 0;
int sum = 0;
System.out.print("Please enter a credit card #: ");
ccNum = input.next();
for(int i = 0 + 1; i < ccNum.length(); i--){
int number = Integer.parseInt(ccNum.substring(i, i + 1));
if(i % 2 != 0){
product = number * 1;
}
else{
product = number * 2;
}
if(product > 9){
product -= 9;
sum += product;
}
}
boolean valid = (sum % 10 == 0);
if(valid){
System.out.println("Valid!");
}
else{
System.out.println("Invalid!");
}
}
}
I am confused about this program. When I run it, I got the "StringIndexOutOfBoundsExpection" error. What should I change up? We cannot use arrays with this program, however. Instead of the full 16-digit number, we are only using 8 digits.
Try this.
boolean alt = false;
for(int i = ccNum.length() - 1; i >= 0; i--, alt = !alt){
int number = ccNum.charAt(i) - '0';
if(alt)
number *= 2;
if(number > 9)
number -= 9;
sum += number;
}
boolean valid = (sum % 10 == 0);
So I'm having an issue simulating a game of craps. Everything runs properly except for the while loop within the while loop. When debugging, the sum variable is retaining it's value, the newSum variable is changing in every iteration, and often hitting 7 and the sum variable's value. If I comment out the nested while loop, and just have it as wins++;, then the code executes properly, to an expected value. So I'm quite certain the issue is within the nested loop.
Thanks for all your input!!
import java.util.Random;
import java.text.DecimalFormat;
public class Ch3Ex2
{
public static void main (String[] args)
{
Random rng = new Random();
int counter = 0;
int sum = 0;
int wins = 0;
int losses = 0;
int newSum = 0;
int reroll1 = 0;
int reroll2 = 0;
while (counter < 10000)
{
int die1 = rng.nextInt(6) + 1;
int die2 = rng.nextInt(6) + 1;
sum = die1 + die2;
if ((sum == 7) || (sum == 11))
wins++;
else if ((sum == 2) || (sum == 3) || (sum == 12))
losses++;
else
{
while((newSum != sum) || (newSum != 7))
{
reroll1 = rng.nextInt(6) + 1;
reroll2 = rng.nextInt(6) + 1;
newSum = reroll1 + reroll2;
}
if (newSum == sum)
{
wins++;
}
else
{
losses++;
}
}
counter++;
}
DecimalFormat percent = new DecimalFormat("0.00%");
double winDenom = wins + losses;
double winRate = wins/winDenom;
System.out.print("Your chance of winning a game of craps is : ");
System.out.println(percent.format(winRate));
}
}
The infinite loop is in this blook:
while((newSum != sum) || (newSum != 7))
{
reroll1 = rng.nextInt(6) + 1;
reroll2 = rng.nextInt(6) + 1;
newSum = reroll1 + reroll2;
}
because if you got a not 7 value in the first start, it will always be true and not stop.
i think you should replace the || with &&
so it could look like this:
while((newSum != sum) && (newSum != 7))
{
reroll1 = rng.nextInt(6) + 1;
reroll2 = rng.nextInt(6) + 1;
newSum = reroll1 + reroll2;
}
while((newSum != sum) || (newSum != 7))
This logic is incorrect. At the moment it will only ever exit if sum is equal to 7.
You need to use && not ||.
At your algorithm (newSum == sum) or (newSum == 7) conditions win so you will use the opposite of this action. After the logical negation
¬(x or y) = ¬x and ¬y
you will have this solution. That means you need to change your while condition as (newSum != sum) && (newSum != 7).
Your program will still be wrong as you never update newSum in nested while loop.
Once you enter the nested while loop, your newSum set to 7. Then it won't change anymore. Then this would cause your win chance to about 20%.
So you need update the newSum to 0 after a nested while loop terminate. Then the win change would be about 50%. You should
else
{
while((newSum != sum) || (newSum != 7))
{
reroll1 = rng.nextInt(6) + 1;
reroll2 = rng.nextInt(6) + 1;
newSum = reroll1 + reroll2;
}
if (newSum == sum)
{
wins++;
}
else
{
losses++;
}
newSum = 0;
}
I have to make a program for my java class that rolls 2 dice, then compares the sum of their observed percentage of appearance compared to the expected percentage of appearance. The observed percentage is expected to be rounded to do decimal places. However, whenever I run the program the observed percentage always comes out as "%.2fn,[percentage]". Here's my (admittedly somewhat messy) code:
import java.util.*;
public class Problem1 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Random roll1 = new Random();
Random roll2 = new Random();
int die1;
int die2;
int sum;
double zero = 0;
double one = 0;
double two = 0;
double three = 0;
double four = 0;
double five = 0;
double six = 0;
double seven = 0;
double eight = 0;
double nine = 0;
double ten = 0;
double[] occurances = new double [11];
double[] percentages = new double [11];
percentages[0] = 2.78;
percentages[1] = 5.56;
percentages[2] = 8.33;
percentages[3] = 11.11;
percentages[4] = 13.89;
percentages[5] = 16.67;
percentages[6] = 13.89;
percentages[7] = 11.11;
percentages[8] = 8.33;
percentages[9] = 5.56;
percentages[10] = 2.78;
System.out.print("How many times would you like to roll the dice? ");
int repeat = keyboard.nextInt();
for (int i = 0; i < repeat; i++) {
die1 = roll1.nextInt(6);
die2 = roll2.nextInt(6);
sum = die1 + die2;
if (sum == 0) {
zero++;
occurances[0] = zero;
} else if (sum == 1) {
one++;
occurances[1] = one;
} else if (sum == 2) {
two++;
occurances[2] = two;
} else if (sum == 3) {
three++;
occurances[3] = three;
} else if (sum == 4) {
four++;
occurances[4] = four;
} else if (sum == 5) {
five++;
occurances[5] = five;
} else if (sum == 6) {
six++;
occurances[6] = six;
} else if (sum == 7) {
seven++;
occurances[7] = seven;
} else if (sum == 8) {
eight++;
occurances[8] = eight;
} else if (sum == 9) {
nine++;
occurances[9] = nine;
} else if (sum == 10) {
ten++;
occurances[10] = ten;
}//if
}//for
System.out.println("roll observed expected");
for (int i = 0; i < occurances.length; i++) {
float observed = (float)(occurances[i]/repeat) * 100;
System.out.println((i+2)+" %.2fn"+observed+"% "+percentages[i]+"%");
}
}
}
How can I get rid of the "%.2fn," before each of the expected percentage and make it only have 2 decimal places? I thought %.2fn was the proper notation for that kind of thing, but it's not working for this.
The println method doesn't know anything about formatting patterns such as %.2f; it thinks that's the literal string you want to print.
Look into the printf method instead, which understands formatting patterns.