On the Programming By Doing website I'm stuck on the DoubleDice exercise. It's supposed to run a while loop until you come up with the same value for each dice (doubles - 3 and 3, 4 and 4, etc.)
I've input what I think to be the correct code, but I get this infinite loop that prints out the exact same "randoms" every time through the while loop.
I've pondered this for about a day and decided to give it to SO.
Thanks.
import java.util.Random;
public class diceDoubles {
public static void main(String[] args){
Random dice = new Random();
int roll1 = 1 + dice.nextInt(6);
int roll2 = 1 + dice.nextInt(6);
System.out.println("HERE COMES THE DICE!\n");
while(roll1 != roll2) {
System.out.println("Die 1: " + roll1);
System.out.println("Die 2: " + roll2);
System.out.println("The total is " + (roll1 + roll2) + "\n");
}
}
}
You need to add "variables roll1 and roll12 update code" to while loop, like this:
while(roll1 != roll2) {
roll1 = 1 + dice.nextInt(6);
roll2 = 1 + dice.nextInt(6);
System.out.println("Die 1: " + roll1);
System.out.println("Die 2: " + roll2);
System.out.println("The total is " + (roll1 + roll2) + "\n");
}
Spend some time familiarizing yourself with the control flow of the code, and what each statement does.
<type> <identifier>;
Lines like this DECLARE a variable - i.e., give it a type, and a place in the namespace. Once a variable is declared, references to it will be consistent within its scope, and it cannot be re-assigned. (Mostly. There's some trickiness with member variable and local variables sharing a name, but you don't need to worry about that.)
Note that this doesn't assign a value. Primitive data types (int, boolean, double, etc), will have a default value (0 or false), which references will default to null.
<identifier> = <expression>;
computes the value of an expression, and updates an identifier to hold that value. You can combine these into:
<type> <identifier> = <expression>;
Which will declare a variable and immediately assign it a value.
while(<condition>) { <expressions> }
executes the expressions again and again until the condition becomes false. It only repeats the expressions between the curly braces, though.
In your code, nothing between those braces (i.e., "in the body of the while loop") actually updates those values. You only call the assignment statement outside of the while loop, so nothing ever changes.
Related
I am fairly new to java, so I don't have much experience with the syntax, I have tried some tutorials online and have watched a few videos on while and do while loops in Java from a user input. However, every edit i try breaks my code. The program below takes an answer from the user, an integer from 1 to 20, and has if statements, that carry out the different scenarios. However, I am trying to make it so that it will keep asking the user for an answer, until they input 0. Here is a part of relevant code:
System.out.print("Type in the pokedex number of the pokemon:");
int answer = Integer.parseInt(reader.nextLine());
if (answer == 1){
System.out.println(
"\nPokemon: " + Bulbasaur.getname() +
"\nType: " + Bulbasaur.getthing_about() +
"\nHealth: " + Bulbasaur.gethp() +
"\nAttack: " + Bulbasaur.getattack() +
"\nDefense: " + Bulbasaur.getdefense() +
"\nSpecial attack: " + Bulbasaur.getspattack() +
"\nSpecial defense: " + Bulbasaur.getspdefense()+
"\nSpeed: " + Bulbasaur.getspeed() +
"\nTotal: " + Bulbasaur.gettotal());
}
.
.
.
There are 19 other if statements similar to this (I know this is inefficient code, but i will be making it efficient if it loops).
How would I add a do while/while loop that loops these statements until 0 is entered?
You need to check answer in the loop condition. You can do the check and assignment to answer in one line
int answer;
while ((answer = Integer.parseInt(reader.nextLine())) != 0) {
// code here
}
Your code would be more efficient if you kept the methods like getName() and all 'non-static', so that they could be called from objects of the classes.
If you've understood how to use int[], double[] etc. type of Arrays, what you can do is create an array of objects of the Pokemon like so:
Object[] pokemon = {new Bulbasaur(), new Ivysaur(), new Venusaur()}; // etc. etc.
int answer = Integer.parseInt(reader.nextLine());
answer = answer - 1; // because arrays start at zero, not one
System.out.println("\nPokemon: " + pokemon[answer].getname() +
"\nType: " + pokemon[answer].getthing_about() +
"\nHealth: " + pokemon[answer].gethp() +
"\nAttack: " + pokemon[answer].getattack() +
"\nDefense: " + pokemon[answer].getdefense() +
"\nSpecial attack: " + pokemon[answer].getspattack() +
"\nSpecial defense: " + pokemon[answer].getspdefense()+
"\nSpeed: " + pokemon[answer].getspeed() +
"\nTotal: " + pokemon[answer].gettotal());
Here's a guide to using Objects if you need it.
By making the methods non-static, you can call them from Objects which belong to an array, and all you have to do to add more Pokemon to the array is add , new WhateverPokemon() to it..
Also, if you want to print the choices to the user, you can do so like this:
for(int i = 0; i < pokemon.length; i++)
{
System.out.println(i+1+". "+ pokemon[i].getName());
}
If you want to add this code, then place it immediately after the Object[] pokemon ....
This is a quite intuitive implementation of what you want:
System.out.print("Type in the pokedex number of the pokemon:");
int answer = -1; // Initialize to a trivial value different from 0
while (answer != 0) { // It will not enter here if initialized to 0!
answer = Integer.parseInt(reader.nextLine());
if (answer == 1){
// Code from the if statement
} // End of if
} // End of while
As #Coffeehouse said, you should take a look at what an array is, and try to use it appropriately. It will shorten your code by quite a lot. Step by step, though :)
I'm making a dice game that scores points based on rolling a 7 or 11(pair of dice). The game keep track of the bets and score. The current score should be added to 3 times the bet amount if the the condition is met. However the score only changes the in the first instance the condition is met, then remain the same through any other roll attempts. I tried to set my getters and setters to be static but that didn't work. What can I do to make my counter work properly?
Program:
public Game() {
final Dice throwDice = new Dice();
//Roll Dice
rollDice.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
throwDice.PairOfDice();
diceResult.setText("You rolled: " + throwDice.getDie1() +
" + " + throwDice.getDie2() +
" = " + throwDice.getTotal());
currentScore.setText("Score: $" + throwDice.getScore());
if(throwDice.getTotal() == 7 || throwDice.getTotal() == 11) {
throwDice.setScore(Integer.parseInt(input.getText()) * 3);
currentScore.setText("Score: $" + throwDice.getScore());
}
}
});
The declaration of your Dice:
Dice throwDice = new Dice();
is in actionPerformed() which means it is created every time you call that function.
Move the declaration into Game, ie. make it an attribute of a game and you should be fine.
You can safely make Dice::score, Dice::getScore() and Dice:setScore(int) non-static.
UPDATE: Given there is still an issue, perhaps try replacing:
throwDice.setScore(Integer.parseInt(input.getText()) * 3);
with:
throwDice.setScore(throwDice.getScore() + (3 + throwDice.getBet()));
In your question you say:
The current score should be added to 3 times the bet amount
You are not adding to the current score. You are only setting the score to the 3 times the bet amount every time. So the value will not change (unless, of course, you change the bet amount).
throwDice.setScore(Integer.parseInt(input.getText()) * 3)
Instead you need to add it to the current score:
throwDice.setScore(throwDice.getScore() + Integer.parseInt(input.getText()) * 3)
You need to move
Dice throwdice = new Dice`
up the code so that it is not called every time it enters actionperformed
Creating a basic post fix expression evaluator/calculator program in Java using Eclipse. I want to be able to store some statistics (listed below)
• The highest overall result value
• The lowest overall result value
• The aggregate value (all answers added together)
• The average answer (from all answers of all expressions)
• Total invalid expressions entered
• Total valid expressions entered
Current code: http://pastebin.com/EijjR6jq
Any guidance appreciated, thanks.
An easy solution would be to create an arraylist to store the values (before printing). This arraylist will contain all of the values which you have gotten so far. Sorting it will get you the highest/lowest overall value, summing it up & dividing that sum by the number of elements in the arraylist will get you the aggregate value & average answer.
As for the invalid and valid expressions, counters could be implemented to keep track of those. Increment the respective counter (valid/invalid) depending on the expression entered.
So for example, it will look something like below.
Scanner input = new Scanner(System.in);
int invalidNumberExpressions = 0; //counter for invalids
int validNumberExpressions = 0; //counter for valids
ArrayList<String> values = new ArrayList<String>(); //Arraylist for calculated values
while (true) {
... //Omitted
if ("+".equals(part3)) {
// Note that your calculation ends up with a string, and not a float
values.add(part1 + " " + part3 + " " + part2 + " " + " = " + (number1 + number2));
System.out.println(values.get(validNumberExpressions));
validNumberExpressions++;
}
// Omitted
Could also consider using switch statements & refactoring out the common section of code in both parts into another method so you don't have to repeat the whole section twice. Looks cleaner, too.
Something like the below for the switch statement. I'll leave the refactoring part to you.
switch (part3) {
case "+": values.add(part1 + " " + part3 + " " + part2 + " " + " = " + (number1 + number2));
System.out.println(values.get(validNumberExpressions));
validNumberExpressions++;
break;
... //other cases here
}
public static void main(String[] args) {
//call for input
System.out.println("Please Enter a 3-digit number..");
Scanner in = new Scanner(System.in);
int[] num = new int[3];
for (int i = 0; i < num.length; i++) {
int val = in.nextInt();
num[i] = val;
}
System.out.println("The Sum of the numbers is " + sumNums);
System.out.println("The Reverse of the numbers is " + reverseNums);
}
public int sumNums(int x) {
return num[0] + num[1] + num[2];
}
public in reverse(int x) {
return num[2] + num[1] + num[0];
}
I'm trying to create a couple methods that add a broken up number, for example, if I enter 123, it would result in 1+2+3=6, but I keep getting "cannot find symbol". Also is the way I broke up the input the most efficient?
There are several problems with your implementation.
In your println, you are not making a method call
System.out.println("The Sum of the numbers is " + sumNums);
System.out.println("The Reverse of the numbers is " + reverseNums );
Should be
System.out.println("The Sum of the numbers is " + sumNums(0));
System.out.println("The Reverse of the numbers is " + reverseNums(0) );
Also, your current sumNums and reverseNums methods aren't using the parameter passed in and they could probably be removed...
The () at the end of the function call is not optional in java, so in your printlns, you need to say sumNums() instead of sumNums. (there is no point of the int x, I assume you remove it.
There are other issues.. such as in should be int, and infact should probably be String if you want to reverse the number.. right now all you are doing is adding them up. And you probably want to pass num as a parameter to the other functions, or make it a class member..
your last method's return type has a typo.
you need to define the array num out of the main method(as a field), or the other methods didn't know this variable(Methods : OMG, What's is the num?)
calling a method is like that : methodName(params...)
I don't think you need to use the par "x" in those methods.
I recommend you to try a better code style
I wouldn't worry about efficiency if I were you. Right now, your program isn't getting any input into the methods that need it.
Two main things here:
Your methods aren't static, so you can't call them inside of main() without an instance of your class (let's call it TestClass for the time being).
You don't pass any of the information you get from the user to your methods to begin with. This is the reason you're running into "cannot find symbol" - num has no definition in the scope of those methods.
To at least remedy the latter issue, you should change the signature of your methods to accept an int array instead of a single int:
public int sumNums(int[] num) {
return num[0] + num[1] + num[2];
}
public int reverse(int[] num) {
return num[2] + num[1] + num[0];
}
I wouldn't expect the results of these two methods to differ in any way though, since addition is commutative.
Instantiating the object, and calling the methods, I leave as an exercise to the reader.
I have a quick question in regards to the value of how variable values work. I am working on a program right now, which looks like this:
public void run() {
println("There are " + ATOMS + " initially.");
int atoms = ATOMS;
int year = 0;
while (atoms > 0) {
for (int i = atoms; i > 0; i--) {
println(i);
if( rgen.nextBoolean() ) {
atoms--;
println("The total atoms is " + atoms);
}
println("The total for i is " + i + "\n" );
}
year++;
println("There are " + atoms + " at the end of year " + year );
}
}
At the part with the for loop, and setting the variable i to the value of atoms, is what has me confused. Lets say the value of atoms starts at 20. It goes through the for loop and lets assume that the first time through the RandomGenerator makes it true. So that subtracts 1 from atoms. Then after that the value of i should also be minused due to the i--. So my question is: When I set the variable i to the value of atoms does that just take i and set it to the initial value of 20? And then from there every time I adjust the value of i it is taking off of its own version of 20, and then when I change the value of atoms it, too has its own value. So when I subtract from atoms, that is not also being subtracted from i? That is the only way I can make sense of it because this program is written and works correctly, but that part has me confused.
Thank you very much in advance for any help!
yes you have answered your own question. the variable i and atoms are two separate instances.
when you start the loop you are setting i equal to the same value as atoms but they are still separate variables. therefore inside the loop when you change the value of one it does not affect the other.
Once you set the value of i=atoms, it no longer changes. It is the loop initializer, and will no longer be processed.
"i" of course will be decremented continuously (because of the i-- decrement).
But you can change the value of atoms to whatever and the results will not change.
i=atoms is the initialization in the for loop. So then on, value of i independent of atoms.