I am new to my Intro to Java course and am struggling with a program. I have posted about this program before but this is a different question. My program is supposed to model a race between a hare and a tortoise. I think I have everything I need but I am having trouble with my JOptionPane phrase. I think my phrase is Ok, but I am experiencing problems with the while portion of my statement. Here is the error message: cannot find symbol - Variable OK.
I use Blue J to write and compile my program. Is there any reason why its not working? I thought the variable OK was the thing that the program user chooses to start the program. Am I mistaken? Can anyone help with this problem? Is there anything else you see in my program that needs fixing? Thanks
import java.util.Random;
import javax.swing.JOptionPane;
class Race
{
int [] race = new int[70];
int tortoise;
int hare;
Random randomGenerator = new Random();
public boolean again = true;
public void StartRace()
{
tortoise = 1;
hare = 1;
System.out.println("AND THEY'RE OFF!!!!");
while (tortoise < race.length && hare < race.length)
{
moveHare();
moveTortoise();
DisplayCurrentLocation();
String request;
}
if
(tortoise > hare)
{
System.out.println("\n TORTOISE WINS!!");
}
else if
(hare > tortoise)
{
System.out.println("\n HARE WINS!!!");
}
else if
(hare == tortoise)
{
System.out.println("TIE!!!");
}
}
public void moveTortoise()
{
int n = randomGenerator.nextInt(10) + 1;
//fast plod
if ( n > 0 && n< 6)
tortoise += 3;
//slip
else if (n > 10 && n< 11)
tortoise -= 6;
//slow plod
else if (n > 6 && n< 9)
++tortoise;
// protect from going past start
if (tortoise < 1)
tortoise = 1;
// to make sure game ends
else if (tortoise > 70)
tortoise = 70;
}// end tortoise
public void moveHare()
{
int m = randomGenerator.nextInt(10) + 1;
//big hop
if (m > 0 && m<3)
hare += 9;
//big slip
else if (m < 6)
hare -= 12;
// small hop
else if (m > 3 && m< 5)
++hare;
// )small slip
else if (m < 9)
hare -= 2;
else if (m < 11)
hare += 0;
//ensure hare doesn't go past start
if (hare < 1)
hare = 1;
// ensure hare doesnt go past end
else if (hare > 70)
hare = 70;
} // end movehare
public void DisplayCurrentLocation()
{
//this is the location of each on the array
for (int count = 1; count <= 70; count++)
// when at same location
if (count ==tortoise && count ==hare)
{
System.out.println("OUCH");
}
else if (count == hare)
{
System.out.println("H");
}
else if (count == tortoise)
{
System.out.println("T");
}
else
System.out.println();
}
public static void main ( String[] args)
{
Race Application = new Race();
int startRaceRequest;
while(startRaceRequest != JOptionPane.OK_OPTION)
{
JOptionPane.showConfirmDialog(null, "Select OK To Begin the Race!:");
}
do
{
Application.StartRace();
} while(startRaceRequest != JOptionPane.OK_OPTION);
}
}
To your question with the JOptionPane: I suggest you to use
JOptionPane.showConfirmDialog(null, "Message");
instead of
JOptionPane.showMessageDialog(null, "Message");
because it allows you to do this:
int startRaceRequest;
while(startRaceRequest != JOptionPane.OK_OPTION)
JOptionPane.showConfirmDialog(null, "Hit OK to start the race!");
I don't really understand what you mean by "Ok" later on in your code, but if you refer to the confirmed dialog, try using JOptionPane.OK_OPTION wich represents an int.
Also some help with your code: At the beginning you initialize the int[] race with the length of 70. Whenever you check if one of the racers is at or above 70, you do it like this
if(tortoise < 70 && hare < 70){}
wich is called hard-coding and you should try to avoid that as much as possible, to keep your code as dynamic as possible.
If you do this
if(tortoise < race.length && hare < race.length)
you don't have to rewrite half your code just because you changed the length of the race.
Another thing to the methods MoveTortoise and MoveHare. Conventionally the should be named moveTortoise and moveHare because method ins Java begin with lower case (that goes for all your methods!). Within those two methods inside your if conditions you write way too much code. for example this:
if (m == 1 || m == 2)
hare += 9;
else if (m == 6)
hare -= 12;
else if (m == 3 && m == 5) //there is something wrong here, m cant be 5 and 3 ;)
++hare;
else if (m == 7 || m == 8)
hare -= 2;
else if (m == 9 || m == 10)
hare += 0;
could be cut to this:
if(m > 0 && m < 3){ // if a number is > 0 and < 3 -> number is 1 or 2
} else if(m < 6){ // if a number is > 0 and > 3 -> if number is < 6 -> number could be 3, 4 or 5
} else if(m == 6){
} else if(m < 9){ // -> 7 or 8
} else if(m < 11){ // 9 or 10
}
In Addition, you use a random number generator and I think you are aiming for a number between 1 to 10, however this
int m = randomGenerator.nextInt(11);
will return a number from 0 to 10. Instead, try this:
int m = randomGenerator.nextInt(10) + 1;
wich will return a number from 0 to 9, adding one will result in a number between 1 and 10.
Hope this helps. Please remember to give feedback and mark a solution if your question was answered.
Related
class PrimeTernary {
public static void main(String[] args) {
int i, m;
int n = 8;
m = n / 2;
String result;
if (n == 0 || n == 1)
System.out.println("Not prime number");
else
for (i = 3; i <= m; i++) {
result = (n % i == 0) ? "not prime" : "prime";
System.out.println(result);
}
}
}
what is wrong in my code? Can anyone pleased to explain it in brief?
Even if n is 0 or 1 (only then your print statement could ever be reached), then m is necessarily 0. This means, the for loop does not run.
Your if condition is never true since n is always 8.
if (n == 0 || n == 1) is the same as if (8 == 0 || 8 == 1)
So your loop will never execute.
My problem is with output of my code. When I enter 20, the output must be weird, but I am getting not weird. Same with the value 18.
import java.util.Scanner;
public class conditional {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String ans = "";
if(n%2 == 1){
ans = "Weird";
} else {
if(n <= 2 && n >= 5){
ans="Not weird";
} else if(n <= 6 && n >= 20){
ans = "Weird";
} else{
ans = "Not Weird";
}
}
System.out.println(ans);
}
}
the output must be weird,but i am getting not weird
Because, if(n%2 == 1) return false and fall to else block where
if(n <= 2 && n >= 5) is `false`
and
else if(n <= 6 && n >= 20) is also `false`
So, again falls to else block. You probably change
if(n <= 2 && n >= 5)
to
if(n >= 2 && n <= 5)
and
else if(n <= 6 && n >= 20)
to
else if(n >= 6 && n <= 20)
Otherwise, they will never be true and always falls to else.
In your program last else is being executed. Change && (logical AND) to || (logical OR) which will check if number is less than something OR higher than something, instead of checking if something is less or equal 5 AND higher or equal to 20 in the same time as it doesn't have a possibility to evaluate in any case.
I have come up with two solutions and also i see a flaw:
1. if(n%2 == 1) this code can be altered to if(n%2 == 0)
2. The flaw is **(n <= 2 && n >= 5)** . No number can be <2 and >5 at the same time. Try changing that to (n <= 2 || n >= 5) and same goes for (n <= 6 && n >= 20)
import java.util.Scanner;
public class conditional {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n = sc.nextInt();
String ans = "";
if(n%2 == 1){
ans = "Weird";
} else {
if(n <= 6 || n >= 20){
ans="Not weird";
} else if(n <= 2 || n >= 5){
ans = "Weird";
} else{
ans = "Not Weird";
}
}
System.out.println(ans);
}
}
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).
I am writing a simple java program to find the smallest number which is divisible by all the numbers from 1 to 20.
I have written the following code:
package smallmultiple;
public class SmallMultiple {
public static void main(String[] args) {
int sml = 0;
outerloop:
for (int i = 40; i < 100000; i++) {
int j=1;
do {
if(i%j==0)
j++;
} while(j<21);
if(j==20) {
sml=i;
break outerloop;
}
}
System.out.println(sml);
}
}
It is not giving any error but it is not giving any output.
You can try this which is a bit faster than yours solution:-
for(int i = 190; ; i += 190) {
if(i % 3 == 0
&& i % 4 == 0
&& i % 6 == 0
&& i % 7 == 0
&& i % 8 == 0
&& i % 9 == 0
&& i % 11 == 0
&& i % 12 == 0
&& i % 13 == 0
&& i % 14 == 0
&& i % 15 == 0
&& i % 16 == 0
&& i % 17 == 0
&& i % 18 == 0
&& i % 20 == 0) {
System.out.println(i);
break;
}
}
You can also check out this article.
You are incrementing j only if i is perfectly divisible by j. Shouldn't you break or exit the do.. while loop of atleast one number is not divisible? Not doing so is causing infinite loop I believe. It should be something like
if(i%j==0) {
j++;
}
else {
break;
}
its simple. Let me explain your loop. First, i = 40 and j = 1, its ok. Then j++.Next i = 40 and j = 2, its still correctly. Then j++ again. Now i = 40, j = 3 and i%j !=0 => j cannot ++ and j still equal 3. And you see, j = 3 is still satisfy your loop ( j < 21) then it loop and loop forever. This is the reason why you cant get any output. You can use your IDE debugging to find this mistake. Sorry my English not good.
In java, to respect the object oriented best practise, it's not advised to user labels, try this :
public class NumberTool {
public static void main(String[] args) {
System.out.println("Smallest number is : " + getSmallestNumberDividedByOneToTwnety());
}
public static int getSmallestNumberDividedByOneToTwnety() {
for ( int i = 40; i <= 2147483647; i++) {
if (isNumberDivdedByOneToTwenty(i)) {
return i;
}
}
return 0;
}
public static boolean isNumberDivdedByOneToTwenty(int numberToTest) {
for (int i = 1; i <= 20; i++) {
if (numberToTest % i != 0) {
return false;
}
}
return true;
}
}
Output is:
Smallest number is : 232792560
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)