Java dice roll with unexpected random number - java

I've written a simple Java program to display the results of 20 dice rolls on the console. The results I'm getting are listed below:
3
1
java.util.Random#62efae3b
1
5
4
1
java.util.Random#62efae3b
1
java.util.Random#62efae3b
java.util.Random#62efae3b
1
6
java.util.Random#62efae3b
1
java.util.Random#62efae3b
java.util.Random#62efae3b
1
2
3
3
When I ran it for a few times, the string after "#" is different, but basically in the same format. What have I done wrong?
Here is the code:
import java.util.Random;
public class QiProb3 {
public static void main(String[] args) {
Random diceNumber = new Random();
for (int count = 0; count <= 20; count++) {
if ((diceNumber.nextInt(6) + 1) == 1) {
System.out.println("1");
} else if ((diceNumber.nextInt(6) + 1) == 2) {
System.out.println("2");
} else if ((diceNumber.nextInt(6) + 1) == 3) {
System.out.println("3");
} else if ((diceNumber.nextInt(6) + 1) == 4) {
System.out.println("4");
} else if ((diceNumber.nextInt(6) + 1) == 5) {
System.out.println("5");
} else if ((diceNumber.nextInt(6) + 1) == 6) {
System.out.println("6");
} else {
System.out.println(diceNumber);
}
}
}
}

else {
System.out.println(diceNumber);
}
You are printing the address of diceNumber by invoking its default toString() function in your else clause.
That is why you are getting the java.util.Random#62efae3b
The more critical issue is why it gets to the 'else' clause, I believe that is not your intention.
Note: In the question, a new number is generated in each if/else if clause, which is why the code actually gets to the final else clause.
What you should be doing is:
for (int count = 0; count < 20; count++) {
int rollValue = diceNumber.nextInt(6) + 1;
if (rollValue == 1) {
System.out.println("1");
} else if (rollValue == 2) {
System.out.println("2");
} else if (rollValue == 3) {
System.out.println("3");
} else if (rollValue == 4) {
System.out.println("4");
} else if (rollValue == 5) {
System.out.println("5");
} else if (rollValue == 6) {
System.out.println("6");
} else {
// This else is now redundant
System.out.println(diceNumber);
}
}
or a more straight-forward method would be:
// count < 20 instead of count <= 20
for (int count = 0; count < 20; count++) {
int rollValue = diceNumber.nextInt(6) + 1;
System.out.println(rollValue);
}
Credit goes to 'Elliott Frisch' for realizing that the loop is
executed 21 times instead of 20.

You're Re-Rolling
With each if you re-roll the dice. Store the value, and test it!
Random diceNumber = new Random();
for (int count = 0; count <= 20; count++) {
int roll = diceNumber.nextInt(6) + 1;
if (roll == 1) {
System.out.println("1");
} else if (roll == 2) {
System.out.println("2");
} else if (roll == 3) {
System.out.println("3");
} else if (roll == 4) {
System.out.println("4");
} else if (roll == 5) {
System.out.println("5");
} else if (roll == 6) {
System.out.println("6");
} else {
System.out.println("RNG Error: " + diceNumber);
}
}
It Could be More Concise
Your posted code might be shortened like
for (int count = 0; count <= 20; count++) {
int roll = diceNumber.nextInt(6) + 1;
System.out.println(roll);
}
Note
Also, you get 21 rolls using the above <= 20 test.

You can do this without the large if-else ladder:
int x = 0;
int i = 0;
while(i < 20){
x = (int)(Math.random() * 7);
if(x != 0)
{
System.out.println((int)Math.floor(x));
i++;
}
}
Math.random() gets a value between 0 and 1 and this value is multiplied to 7. If the dice turns out to be zero, skip the roll and do another one. The Math.floor() value will round the decimal value down to the nearest integer (if product = 6.2 then the output of the roll will be 6).

Related

my do-while loop seems to be running forever even though i change the value of the condition

boolean onGoing = true;
do {
String p1 = "playing";
while (p1.equals("playing")) {
System.out.println("Player 1, enter hit row/column:");
int a = sc.nextInt();
int b = sc.nextInt();
if (a >= 0 && a < 5 && b >= 0 && b < 5) {
if (history1[a][b] == '-') {
p1 += " no more";
if (board2[a][b] == '#') {
history1[a][b] = 'X';
board2[a][b] = 'X';
String status = check(board2);
if (status.equals("win")) {
System.out.println("PLAYER 1 WINS! YOU SUNK ALL OF YOUR OPPONENT'S SHIPS!");
onGoing = false;
printBattleShip(board1);
printBattleShip(board2);
break;
} else {
System.out.println("PLAYER 1 HIT PLAYER 2's SHIP!");
}
} else if (board2[a][b] == '-') {
System.out.println("PLAYER 1 MISSED!");
history1[a][b] = 'O';
board2[a][b] = 'O';
}
} else {
System.out.println("You already fired on this spot. Choose different coordinates.");
}
} else {
System.out.println("Invalid coordinates. Choose different coordinates.");
}
}
String p2 = "playing";
while (p2.equals("playing")) {
System.out.println("Player 2, enter hit row/column:");
int c = sc.nextInt();
int d = sc.nextInt();
if (c >= 0 && c < 5 && d >= 0 && d < 5) {
if (history2[c][d] == '-') {
p2 += " no more";
if (board1[c][d] == '#') {
history2[c][d] = 'X';
board1[c][d] = 'X';
String status = check(board1);
if (status.equals("win")) {
System.out.println("PLAYER 2 WINS! YOU SUNK ALL OF YOUR OPPONENT'S SHIPS!");
onGoing = false;
printBattleShip(board2);
printBattleShip(board1);
break;
} else {
System.out.println("PLAYER 2 HIT PLAYER 1's SHIP!");
}
} else if (board1[c][d] == '-') {
history2[c][d] = 'O';
board1[c][d] = 'O';
System.out.println("PLAYER 2 MISSED!");
}
} else {
System.out.println("You already fired on this spot. Choose different coordinates.");
}
} else {
System.out.println("Invalid coordinates. Choose different coordinates.");
}
}
} while (onGoing);
private static String check(char[][] arr1) {
int sum = 0;
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr1.length; j++) {
if (arr1[i][j] == '#') {
sum += 1;
}
}
}
if (sum == 0) {
return "win";
} else {
return "keep playing";
}
}
// I declared and initialized a boolean variable called ongoing before a do-while loop. Then I create a while loop inside the do while loop. And inside the while loop, there are a series of conditional statement. Eventually, I changed the value of the boolean variable and feed it back to the while statement, letting it evaluate it. But it doesn't seem to change the value. Is it because the scope of the variable? How can I fix it?
edit: check method added

This code is getting unreachable code, and I'm not sure why

Sorry for the large amount of code, but I'm not sure why
int timesWon;
is getting a unreachable code error on line 90.
Anything that is put on line 90 is unreachable code, meaning anything after it isn't readable.
This is my code for a game of craps for an assignment:
package homework2_3;
import java.security.*;
public class Craps
{
static enum score
{
win, lose
}
public static void main(String[] args)
{
//random Number for a dice roll
SecureRandom random = new SecureRandom();
//ints for the totals on the two dice
int dice1;
int dice2;
//array for times won/lost
score[] total = new score[1000000];
//int for the score of the first throw, if it was not an imediate win or loss
int throw1Score = 0;
//count how many times a win or loss happened at each roll from 1-21
int[] rollWon = new int[22];
int[] rollLost = new int[22];
//loop for each game from 1-1000000
for(int indexGame = 1; 1 <= 1000000; indexGame++)
{
//loop for each throw within a game
for(int indexThrow = 1; total[indexGame] != score.win || total[indexGame] != score.lose; indexThrow++)
{
//get the total of blips on the dice
dice1 = random.nextInt(6) + 1;
dice2 = random.nextInt(6) + 1;
//check if the throw total in throw 1
if(indexThrow == 1)
{
//check if throw 1 is an instant win
if((dice1 + dice2) == 7 || (dice1 + dice2) == 11)
{
total[indexGame] = score.win;
rollWon[indexThrow]++;
}
//check if throw 1 is an instant loss
else if((dice1 + dice2) == 2 || (dice1 + dice2) == 3 || (dice1 + dice2) == 12)
{
total[indexGame] = score.lose;
rollLost[indexThrow]++;
}
//get your "point"
else
{
throw1Score = dice1 + dice2;
}
}
//anything other than throw 1
else
{
//check if you "made your point"
if((dice1 + dice2) == throw1Score)
{
total[indexGame] = score.win;
if(indexThrow <= 20)
{
rollWon[indexThrow]++;
}
else if(indexThrow > 20)
{
rollWon[21]++;
}
}
//check if you rolled a 7 (lost)
else if((dice1 + dice2) == 7)
{
total[indexGame] = score.lose;
if(indexThrow <= 20)
{
rollLost[indexThrow]++;
}
else if(indexThrow > 20)
{
rollLost[21]++;
}
}
}
}
}
//ints to add up all the wins and losses in the array of scores
int timesWon;
int timesLost;
//loop for the adding
for(int winLossCheck = 1; winLossCheck <= 1000000; winLossCheck++)
{
if(total[winLossCheck] == score.win)
{
timesWon++;
}
if(total[winLossCheck] == score.lose)
{
timesLost++;
}
}
//print the total times you won/lost
System.out.println("you won " + timesWon + " times, and you lost " + timesLost + " times");
}
}
As far as I can tell, everything is logically correct and syntactically correct.
Thanks in advance for any help!
1 <= 1000000 is always true
You have a for loop in which the condition is 1 <= 1000000. This loop will not exit, thus making all code after the loop unreachable. Change the the condition to something where the code will exit.
For example:
for(int i = 1; i<=10; i++) {
System.out.println(i);
}
This code will print out the integers from 1-10. However if I create another for loop with a condition that is always true like 0<7. Since the loop won't end, all code after it is unreachable. Change your for loop to have a condition that won't always be true, so the program will continue.

Understanding nested loop and classes

I started a project to understand deeply nested loops and classes. In my CYCLING method when I reach the if(y >= 0) loop it doesn't properly use my variables in classes. For example if MPH is 15 and the gear is 1 or 3 it won't ask me to change gear. Or if gear is 1 and speed is 11+ it wont ask me to change gear? What am I doing incorrectly?
public class Bike {
int speed;
int gear;
void changeGear(int newVal) {
gear = newVal;
}
void speedUp(int newVal) {
speed = newVal;
}
void breaks(int slow) {
speed = speed + slow;
}
void printState() {
System.out.println("Gear is: " + gear);
System.out.println("Speed is: " + speed + ("MPH"));
}
}
//________________________
public static boolean cycle = true;
public static Bike b1 = new Bike();
public static int x;
public static int y;
public static Scanner input = new Scanner(System.in);
public static int choice;
//______________________________
public static void cycling() {
while (cycle == true) {
System.out.println("What would you like to do now? Enter a number.");
System.out.println("1: Speed Change");
System.out.println("2: Change Gear");
choice = input.nextInt();
if (choice == 1) {
System.out.println("Choose a speed change");
y = input.nextInt();
if (y < 0) {
b1.breaks(y);
if (b1.speed < 0) {
b1.speed = Math.abs(y) + y;
System.out.println("You've stopped entirely");
}
}
if (y >= 0) {
b1.speed = y;
b1.printState();
if (b1.speed >= 0 && b1.speed <= 10) {
while (b1.gear != 1) {
System.out.println("You need to be in Gear 1 for " + "that! Please change gears.");
x = input.nextInt();
b1.changeGear(x);
}
if (b1.speed >= 11 && b1.speed <= 20) {
while (b1.gear != 2) {
System.out.println("You need to be in Gear 2 for" + "that! Please change gears.");
x = input.nextInt();
b1.changeGear(x);
}
if (b1.speed >= 21) {
while (b1.gear != 3) {
System.out.println("You need to be in Gear 3 for" + "that! Please change gears.");
x = input.nextInt();
b1.changeGear(x);
}
}
/*if(b1.speed >= 0 && b1.speed <=10){
b1.gear = 1;
}else if(b1.speed >= 11 && b1.speed <=20){
b1.gear = 2;
}else if(b1.speed >= 21){
b1.gear = 3;
}*/
b1.printState();
}
}
}
}
}
}
Think about your statements. You have something that basically looks like this:
if (b1.speed >= 0 && b1.speed <= 10) {
//some while loop here to do whatever
if (b1.speed >= 11 && b1.speed <= 20) {
//more code
}
}
In your code, this statement will never be true:
if (b1.speed >= 11 && b1.speed <= 20) {
The only way you get to that statement is if b1.speed>=0 && b1.speed<=10. Therefore, will b1.speed ever be between 11 and 20 when you get to that second (nested) if statement?

Can't figure out the error Luhn check

Its supose to tell me if a card is valid or invalid using luhn check
4388576018402626 invalid
4388576018410707 valid
but it keeps telling me that everything is invalid :/
Any tips on what to do, or where to look, would be amazing. I have been stuck for a few hours.
It would also help if people tell me any tips on how to find why a code is not working as intended.
im using eclipse and java
public class Task11 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a credit card number as a long integer: ");
long number = input.nextLong();
if (isValid(number)) {
System.out.println(number + " is valid");
} else {
System.out.println(number + " is invalid");
}
}
public static boolean isValid(long number) {
return (getSize(number) >= 13) && (getSize(number) <= 16)
&& (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 6) || prefixMatched(number, 37))
&& (sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 == 0;
}
public static int sumOfDoubleEvenPlace(long number) {
int result = 0;
long start = 0;
String digits = Long.toString(number);
if ((digits.length() % 2) == 0) {
start = digits.length() - 1;
} else {
start = digits.length() - 2;
}
while (start != 0) {
result += (int) ((((start % 10) * 2) % 10) + (((start % 10) * 2) / 2));
start = start / 100;
}
return result;
}
public static int getDigit(int number) {
return number % 10 + (number / 10);
}
public static int sumOfOddPlace(long number) {
int result = 0;
while (number != 0) {
result += (int) (number % 10);
number = number / 100;
}
return result;
}
public static boolean prefixMatched(long number, int d) {
return getPrefix(number, getSize(d)) == d;
}
public static int getSize(long d) {
int numberOfDigits = 0;
String sizeString = Long.toString(d);
numberOfDigits = sizeString.length();
return numberOfDigits;
}
public static long getPrefix(long number, int k) {
String size = Long.toString(number);
if (size.length() <= k) {
return number;
} else {
return Long.parseLong(size.substring(0, k));
}
}
}
You should modiffy your isValid() method to write down when it doesn't work, like this:
public static boolean isValid(long number) {
System.err.println();
if(getSize(number) < 13){
System.out.println("Err: Number "+number+" is too short");
return false;
} else if (getSize(number) > 16){
public static boolean isValid(long number) {
System.err.println();
if(getSize(number) < 13){
System.out.println("Err: Number "+number+" is too short");
return false;
} else if (getSize(number) > 16){
System.out.println("Err: Number "+number+" is too long");
return false;
} else if (! (prefixMatched(number, 4) || prefixMatched(number, 5) || prefixMatched(number, 6) || prefixMatched(number, 37)) ){
System.out.println("Err: Number "+number+" prefix doesn't match");
return false;
} else if( (sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 != 0){
System.out.println("Err: Number "+number+" doesn't have sum of odd and evens % 10. ");
return false;
}
return true;
}
My guess for your problem is on the getPrefix() method, you should add some logs here too.
EDIT: so, got more time to help you (don't know if it's still necessary but anyway). Also, I corrected the method I wrote, there were some errors (like, the opposite of getSize(number) >= 13 is getSize(number) < 13)...
First it will be faster to test with a set of data instead of entering the values each time yourself (add the values you want to check):
public static void main(String[] args) {
long[] luhnCheckSet = {
0, // too short
1111111111111111111L, // too long (19)
222222222222222l // prefix doesn't match
4388576018402626l, // should work ?
};
//System.out.print("Enter a credit card number as a long integer: ");
//long number = input.nextLong();
for(long number : luhnCheckSet){
System.out.println("Checking number: "+number);
if (isValid(number)) {
System.out.println(number + " is valid");
} else {
System.out.println(number + " is invalid");
}
System.out.println("-");
}
}
I don't know the details of this, but I think you should work with String all along, and parse to long only if needed (if number is more than 19 characters, it might not parse it long).
Still, going with longs.
I detailed your getPrefix() with more logs AND put the d in parameter in long (it's good habit to be carefull what primitive types you compare):
public static boolean prefixMatched(long number, long d) {
int prefixSize = getSize(d);
long numberPrefix = getPrefix(number, prefixSize);
System.out.println("Testing prefix of size "+prefixSize+" from number: "+number+". Prefix is: "+numberPrefix+", should be:"+d+", are they equals ? "+(numberPrefix == d));
return numberPrefix == d;
}
Still don't know what's wrong with this code, but it looks like it comes from the last test:
I didn't do it but you should make one method from sumOfDoubleEvenPlace(number) + sumOfOddPlace(number)) % 10 and log both numbers and the sum (like i did in prefixMatched() ). Add logs in both method to be sure it gets the result you want/ works like it should.
Have you used a debugger ? if you can, do it, it can be faster than adding a lot of logs !
Good luck
EDIT:
Here are the working functions and below I provided a shorter, more efficient solution too:
public class CreditCardValidation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
long array[] = new long [16];
do
{
count = 0;
array = new long [16];
System.out.print("Enter your Credit Card Number : ");
long number = in.nextLong();
for (int i = 0; number != 0; i++) {
array[i] = number % 10;
number = number / 10;
count++;
}
}
while(count < 13);
if ((array[count - 1] == 4) || (array[count - 1] == 5) || (array[count- 1] == 3 && array[count - 2] == 7)){
if (isValid(array) == true) {
System.out.println("\n The Credit Card Number is Valid. ");
} else {
System.out.println("\n The Credit Card Number is Invalid. ");
}
} else{
System.out.println("\n The Credit Card Number is Invalid. ");
}
in.close();
}
public static boolean isValid(long[] array) {
int total = sumOfDoubleEvenPlace(array) + sumOfOddPlace(array);
if ((total % 10 == 0)) {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return true;
} else {
for (int i=0; i< array.length; i++){
System.out.println(array[i]);}
return false;
}
}
public static int getDigit(int number) {
if (number <= 9) {
return number;
} else {
int firstDigit = number % 10;
int secondDigit = (int) (number / 10);
return firstDigit + secondDigit;
}
}
public static int sumOfOddPlace(long[] array) {
int result = 0;
for (int i=0; i< array.length; i++)
{
while (array[i] > 0) {
result += (int) (array[i] % 10);
array[i] = array[i] / 100;
}
}
System.out.println("\n The sum of odd place is " + result);
return result;
}
public static int sumOfDoubleEvenPlace(long[] array) {
int result = 0;
long temp = 0;
for (int i=0; i< array.length; i++){
while (array[i] > 0) {
temp = array[i] % 100;
result += getDigit((int) (temp / 10) * 2);
array[i] = array[i] / 100;
}
}
System.out.println("\n The sum of double even place is " + result);
return result;
}
}
I also found a solution with less lines of logic. I know you're probably searching for an OO approach with functions, building from this could be of some help.
Similar question regarding error in Luhn algorithm logic:
Check Credit Card Validity using Luhn Algorithm
Link to shorter solution:
https://code.google.com/p/gnuc-credit-card-checker/source/browse/trunk/CCCheckerPro/src/com/gnuc/java/ccc/Luhn.java
And here I tested the solution with real CC numbers:
public class CreditCardValidation{
public static boolean Check(String ccNumber)
{
int sum = 0;
boolean alternate = false;
for (int i = ccNumber.length() - 1; i >= 0; i--)
{
int n = Integer.parseInt(ccNumber.substring(i, i + 1));
if (alternate)
{
n *= 2;
if (n > 9)
{
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
public static void main(String[] args){
//String num = "REPLACE WITH VALID NUMBER"; //Valid
String num = REPLACE WITH INVALID NUMBER; //Invalid
num = num.trim();
if(Check(num)){
System.out.println("Valid");
}
else
System.out.println("Invalid");
//Check();
}
}

Why isn't my FizzBuzz code processing both if statements when they both match? [duplicate]

This question already has answers here:
Conditional statement true in both parts of if-else-if ladder
(4 answers)
Closed 2 years ago.
For those who don't know, FizzBuzz is the following problem:
Write a program that prints the numbers from 1 to 100. But for
multiples of three print "Fizz" instead of the number and for the
multiples of five print "Buzz". For numbers which are multiples of
both three and five print "FizzBuzz".
Every FizzBuzz solution I find is either some crazy esoteric solution made for the sake of being original, or your basic if-else chain:
for(int i = 1; i <= 100; i++) {
if(i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
I am looking for a simple solution that aims to take out the "FizzBuzz" if statement. I have this in mind:
for(int i = 1; i <= 100; i++) {
if (i % 3 == 0)
System.out.print("Fizz");
if (i % 5 == 0)
System.out.println("Buzz")
else
System.out.println(i);
}
But this doesn't work. I assume it would be able to print FizzBuzz by entering both ifs, for Fizz and for Buzz, but if the number is, for example, 3, it would print Fizz3. How do I avoid this?
What you're trying to do is
if (a)
...
if (b)
...
else // if neigther a nor b
...
This is simply not possible. An else can only belong to a single if. You have to go with the slightly longer variant.
To avoid doing redundant evaluations of the modulo operator, you could formulate the loop body as
boolean fizz = i % 3 == 0;
boolean buzz = i % 5 == 0;
if (fizz)
System.out.print("Fizz");
if (buzz)
System.out.print("Buzz");
if (!(fizz || buzz))
System.out.print(i);
System.out.println();
Another one would be
String result = "";
if (i % 3 == 0) result = "Fizz";
if (i % 5 == 0) result += "Buzz";
if (result == "") result += i;
System.out.println(result);
Your first if statement is all alone.
So, your code hits the first statement, which is ONLY an if statement, and then goes on to the next, which is an if/else statement.
RosettaCode has a good example without using AND operators.
int i;
for (i = 0; i <= 100; i++) {
if ((i % 15) == 0)
cout << "FizzBuzz" << endl;
else if ((i % 3) == 0)
cout << "Fizz" << endl;
else if ((i % 5) == 0)
cout << "Buzz" << endl;
else
cout << i << endl;
}
If your only goal is to avoid using &&, you could use a double negation and DeMorgan's laws:
for(int i = 1; i <= 100; i++) {
if(!(i % 3 != 0 || i % 5 != 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
You can avoid && using the fact that i % 3 == 0 and i % 5 == 0 implies i % 15 == 0, as per RFC1337's answer.
Another solution is to use a switch on the remainder (mod 15, which is 5 times 3):
for(int i = 1; i <= 100; i++) {
final int mod = i % 15;
switch (mod) {
case 0:
case 3:
case 6:
case 9:
case 12:
System.out.print("Fizz");
if (mod != 0) break;
case 5:
case 10:
System.out.print("Buzz");
break;
default:
System.out.print(i);
}
System.out.println();
}
This is my solution. Granted, it's a bit convoluted (as in roundabout), but I believe it suits your requirement.
int main()
{
char fizzpass=0;
unsigned short index=0;
for(index=1;index<=100;index++)
{
if(0 == (index%3))
{
printf("Fizz");
fizzpass = 1;
}
if(0 == (index%5))
{
if(1 == fizzpass)
{
fizzpass = 0;
}
printf("Buzz\n");
continue;
}
if(1 == fizzpass)
{
fizzpass = 0;
printf("\n");
continue;
}
printf("%d\n",index);
}
return 0;
}
Regards.
Just add a flag variable and use System.out.print:
package com.stackoverflow;
public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
boolean printed = false;
if (i % 3 == 0) {
printed = true;
System.out.print("Fizz");
}
if (i % 5 == 0) {
printed = true;
System.out.print("Buzz");
}
if (printed) {
System.out.println();
} else {
System.out.println(i);
}
}
}
}
This doesn't take out the if statements but does not use the && (and) operator, you could flip the binary operators.
//FizzBuzz Case
if(!(a % 3 != 0 || a % 5 != 0)){ //flips
result[index] = "FizzBuzz";
index++;
}
Don't use an if statement at all.
import java.util.*;
import java.lang.*;
import java.io.*;
class FizzBuzz
{
public static void main (String[] args) throws java.lang.Exception
{
String[] words = {"", "Fizz", "Buzz"};
String[] nwords = {"", ""};
for(int i = 1; i < 101; ++i)
{
int fp = (i % 3 == 0) ? 1 : 0;
int bp = ((i % 5 == 0) ? 1 : 0) * 2;
int np = ((fp > 0 || bp > 0) ? 1: 0);
nwords[0] = Integer.toString(i);
System.out.print(words[fp]);
System.out.print(words[bp]);
System.out.println(nwords[np]);
}
}
}
See it on ideone.
public class fizzbuzz
{
public static void main(String[] args)
{
String result;
for(int i=1; i<=100;i++)
{
result=" ";
if(i%3==0)
{
result=result+"Fizz";
}
if(i%5==0)
{
result=result+"Buzz";
}
if (result==" ")
{
result=result+i;
}
System.out.println(result);
}
}
}
This is the most efficient way I could come up with. Hope it helps! :)
Crazy albeit unrelated solution done in Python3
#!/usr/bin/python3
for i in range(1,100):
msg = "Fizz" * bool(i%3==0)
msg += "Buzz" * bool(i%5==0)
if not msg:
msg = i
print(msg)

Categories