Floating number not showing up? - java

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.

Related

Why does my loop increment 1 over the value needed?

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);
}
}
}

Detecting when an integer is made up of only the same digit

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+");
}

Luhn's Algorithm not working properly

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);

Luhn formula implementation in Java

I'm trying to implement a luhn formula in my java servlet application. I tried other 'valid' credit cards numbers scattering in the internet and didn't work. I just want to know if I got it correctly. Any help would be appreaciate!
public static boolean luhn(String input){
char[] creditCard = input.toCharArray();
int checkSum = 0;
boolean alternate = false;
for (int i = creditCard.length - 1; i >= 0; i --){
int m = (int)Integer.parseInt(Character.toString(creditCard[i]));
if (alternate){
m *= 2;
if (m > 9){
m = (m & 10) + 1;
}
}
checkSum += m;
alternate = true;
}
if ( (checkSum % 10) == 0){
return true;
}else{
return false;
}
}
here the working code
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean repeat;
List<Integer> digits = new ArrayList<Integer>();
do {
repeat = false;
System.out.print("Enter your Credit Card Number : ");
String input = in.next();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c < '0' || c > '9') {
repeat = true;
digits.clear();
break;
} else {
digits.add(Integer.valueOf(c - '0'));
}
}
} while (repeat);
int[] array = new int[digits.size()];
for (int i = 0; i < array.length; i++) {
array[i] = Integer.valueOf(digits.get(i));
}
boolean valid = check(array);
System.out.println("Valid: " + valid);
}
to check for luhn algo
public static boolean check(int[] digits) {
int sum = 0;
int length = digits.length;
for (int i = 0; i < length; i++) {
// get digits in reverse order
int digit = digits[length - i - 1];
// every 2nd number multiply with 2
if (i % 2 == 1) {
digit *= 2;
}
sum += digit > 9 ? digit - 9 : digit;
}
return sum % 10 == 0;
}
or a more refracted program might be as below
import java.util.Scanner;
public class Luhn {
private static Scanner input;
public static void main(String... args) {
input = new Scanner(System.in);
System.out.print("Enter number to validate:\n");
String pnr = input.nextLine();
boolean result = luhn(pnr);
printMessage(result);
input.close();
}
static boolean luhn(String pnr){
// this only works if you are certain all input will be at least 10 characters
int extraChars = pnr.length() - 10;
if (extraChars < 0) {
throw new IllegalArgumentException("Number length must be at least 10 characters!");
}
pnr = pnr.substring(extraChars, 10 + extraChars);
int sum = 0;
for (int i = 0; i < pnr.length(); i++){
char tmp = pnr.charAt(i);
int num = tmp - '0';
int product;
if (i % 2 != 0){
product = num * 1;
}
else{
product = num * 2;
}
if (product > 9)
product -= 9;
sum+= product;
}
return (sum % 10 == 0);
}
private static void printMessage(boolean valid) {
if (valid){
System.out.print("Valid!\r");
}
else{
System.out.print("Invalid!");
}
}
}

Unreachable code in Java

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.

Categories

Resources