This method is to sum up all the numbers present on the dice and add them to the total score. There are 5 dice, I'm having trouble with it because whenever I activate it through the GUI it just adds some random numbers together and not the numbers present, also I can activate the button without rolling and it gives me numbers still.
dieList is the ArrayList that carries the current die numbers, and nextRound just puts the game to the next round. If you require more information I will be happy to supply it.
public void checkChance(){
int chance = 0;
for(GVdie die: dieList){
chance = chance + die.getValue();
score = score + chance;
}
nextRound();
}
Related
I am a beginner programmer and i understand this pseudocode will have many errors, and that is why i came here to ask for help! I know i'm not passing anything i just can't seem to wrap my head around how to get them there. I'm also not sure if while gather input i'm using alter and prompt correctly. In the display function, the spacing is necessary for when it will be displayed. Corrections and explanations are greatly appreciated. Any help would be amazing as i cannot wrap my head around how to formulate this. (NOTE: this is for java)
Instructions for exercise:
Last year, a local college implemented rooftop gardens as a way to promote energy efficiency and save money. Write a program that will allow the user to enter the energy bills from January to June prior to going green. Next, allow the user to enter the energy bills from January to June after going green. The program should calculate the energy difference and display the 6 months’ worth of data, along with the savings.
Hint:
Create 4 global arrays of size 6 each. The first array (notGreenCost) will store the first 6 months of energy costs, the second array (goneGreenCost) will store the 6 months after going green, and the third array (savings) will store the difference. Also, create an array (months) that stores the month names
The pseudocode so far:
//Add statements to declare the global array variables
Declare Real notGreenCost[6]
Declare Real goneGreenCost[6]
Declare Real savings[6]
Declare Real months[6]
Module main()
//Declare local variables
Declare String endProgram = “no”
Call initMonths()
While endProgram == “no”
//Module calls
Call getNotGreen()
Call getGoneGreen()
Call energySaved()
Call displayInfo()
Display “Do you want to end the program (enter yes or no):”
Input endProgram
While endProgram<>”no” AND endProgram<>”yes”
Display “Please enter a value of yes or no: ”
Input endProgram
End While
End While
End Module
Module initMonths()
months = “January”, “February”, “March”, “April”, “May”, “June”
End Module
Module getNotGreen()
//Add statements to retrieve 6 months of info and save to the array
Set counter = 0
For counter < 6
Display “Enter NOT GREEN energy costs for”, months[counter]
Input notGreenCosts[counter]
Set counter = counter + 1
End For
End Module
Module getGoneGreen()
//Add statements to retrieve 6 months of info and save to the array
Set counter = 0
For counter < 6
Input goneGreenCosts[counter]
Set counter = counter + 1
End For
End Module
Module energySaved()
//Add statements to calculate 6 months of savings and save to the array
Set counter = 0
While counter < 6
Set savings[counter] = notGreenCost[counter] – goneGreenCost[counter]
Set counter = counter + 1
End While
End Module
Module displayInfo()
//Add statements to display results as shown above
Set counter = 0
While counter < 6
Display “Information for”, months[counter]
Display “Savings $”, savings[counter]
Display “Not Green Costs $”, notGreenCost[counter]
Display “Gone Green Costs $”, goneGreenCost[counter]
End While
End Module
Perhaps this is what you are looking for
import java.util.Scanner;
class A{
public static int []PriorGreen = new int[6];
public static int []AfterGreen = new int[6];
public static String []month = {"Jan","Feb","Mar","April","May","June"};
static void PriorG()
{
System.out.println(" Enter Cost for Prior Green Month's Below !!!");
Scanner in = new Scanner(System.in);
for(int i=0;i<6;i++){
System.out.println(" Please enter cost for "+month[i]);
PriorGreen[i]=in.nextInt();
}
}
static void AfterG()
{
System.out.println(" Enter Cost for After Green Month's Below !!!");
Scanner in = new Scanner(System.in);
for(int i=0;i<6;i++){
System.out.println(" Please enter cost for "+month[i]);
AfterGreen[i]=in.nextInt();
}
}
static void energySaved()
{
for(int i=0;i<6;i++){
System.out.println(" Energy saved in "+month[i]+" is "+(PriorGreen[i]-AfterGreen[i]));
}
}
static void display()
{
System.out.println("Prior Green "+"After Green "+ "Savings");
for(int i=0;i<6;i++){
System.out.println(PriorGreen[i]+" "+AfterGreen[i]+" "+(PriorGreen[i]-AfterGreen[i]));
}
}
public static void main(String []args)
{
PriorG();
AfterG();
energySaved();
display();
}
}
I see only one small oversight in your pseudocode. In your displayInfo you forgot to increment your counter. You should add Set counter = counter + 1 inside the while loop.
One other thing I notice is that you have a loop that runs the core logic until the user responds "no":
While endProgram == “no” which is not in your requirements. I don't think it's a bad thing necessarily but it would depend on your instructor and whether they would mark you down for that.
I suggest you start writing your Java code and update your post if you run into problems for which you can't find a solution.
I'm fairly new to java and am experimenting building my own text based game, at the moment im just trying to work on individual concepts and then hopefully be able to pull it all together in a final project, my problem i have come across at the moment and cant seem to find an answer is exactly what the title question states:
How can i validate user input against a String ArrayList of randomly generated elements?
To clarify, i have a working program at the moment that when run generates a random amount and random types of enemy and then populates them into the dungeon each time the dungeon object is created, the user is then presented with a question allowing them to pick which enemy they should confront first, this is where i require the validation in order that the game would continue, im trying to use a while loop which if the condition returns false would just skip and move on to if statements and their validations, i hope that makes sense and ive posted my code below, apologies in advance if there are many things wrong with my code either syntactically or structurally as stated earlier im still very new to java and at the moment if i can just learn to code then i can worry about how professional or proper something should be.
Here is my code:
package com.davegreen;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
// Declaring some variables and creating some objects of other classes that i need.
Scanner scanner = new Scanner(System.in);
Dungeon dungeon = new Dungeon();
List<String> enemyType = dungeon.getEnemy(); // Gets all the enemy from my enemy ArrayList in the Dungeon class.
int enemyNumberTotal = dungeon.getEnemy().size(); // Gets the amount of enemy in my enemy ArrayList.
runGame();
int randomAmountOfEnemy = generateRandomNumber(enemyNumberTotal); // Generates a random amount of enemy into the dungeon from the total number in the ArrayList.
System.out.println("\n The enemies in this dungeon are: \n");
// Generates the random enemies that will populate the dungeon based on a method in my Dungeon class and then passes a random amount of said enemy each time also.
List<String> randomlyPickedEnemy = dungeon.populateWithRandomEnemy(enemyType, randomAmountOfEnemy);
System.out.println("\n\t * " + randomlyPickedEnemy);
System.out.println("\n> Which enemy would you like to confront first?");
String userChoice = scanner.nextLine();
// I want to validate the user input from line 31 of the code to reflect that if the user has not selected an enemy that was in the randomly populated list
// then we stay in the while loop and continue asking until of course the user types in a enemy that was in the randomly populated list, at which
// point we would of course skip the while loop moving onto the if statements validation, it would be nice also to have ignore case somewhere in there.
while(!userChoice.equals(randomlyPickedEnemy))
{
System.out.println("\n\t That enemy does not live in this dungeon!");
System.out.println("\n> Which enemy would you like to confront first?");
userChoice = scanner.nextLine();
}
// For the validation here i realise of course that just using the variable randomlyPickedEnemy in the sout would more than likely return ALL the enemy that
// were randomly populated and not specifically the enemy that the user had chosen, so at this point i need a way to be able to access exactly what enemy it was
// that the user had chosen to battle so that the sout statement makes sense but more importantly so i can then direct the code where it needs to go based on any given
// particular enemy.
if(userChoice.equals(randomlyPickedEnemy))
{
System.out.println("You have chose to battle " + randomlyPickedEnemy);
}
}
public static void runGame()
{
System.out.println("##################################################");
System.out.println("##### DUNGEON CRAWLER #####");
System.out.println("##################################################");
}
// This is my method to generate a random amount of enemy for the total amount of enemy in my ArrayList.
public static int generateRandomNumber(int howManyEnemies)
{
Random random = new Random();
int rng = random.nextInt(howManyEnemies) + 1;
System.out.println("\n There are " + rng + " enemies in this dungeon!");
return rng;
}
}
You are actually comparing a String to a List (randomlyPickedEnemy).
If I understand correctly, you want to know if this list contains the input of the user.
To do this you just have to modify your whilestatement :
while(!randomlyPickedEnemy.contains(userChoice)) {
...
}
First, I have searched. And all of the answers I have found have been about NOT having the same reference to the same object in two different array lists. so maybe that should tell me I'm doing this wrong in itself? But I'm not sure of how else to manage this.
I am trying to learn Java. And part of that is Swing.
My app I am working on is a simple tournament/bracket app (think march madness. or any simple bracket tree).
Simplified code with just the issue at hand:
class Bracket extends JPanel {
ArrayList<Round> rounds = new ArrayList<Round>();
public void declareWinner(Team team, Game game, Round round) {
// code that gets current round, game, team numbers to calculate the next round, game, team numbers.
int currentRoundNum = rounds.indexOf(round);
int currentGameNum = rounds.get(currentRoundNum).games.indexOf(game);
int currentTeamNum = rounds.get(currentRoundNum).games.get(currentGameNum).teams.indexOf(team);
int nextRoundNum = currentRoundNum + 1;
int nextGameNum = (int) (Math.floor(gameNumber / 2));; // to position the team in the appropriate game slot in the next round
int nextTeamNum = ((gameNumber % 2) == 0) ? 0 : 1; // even game numbers will be the top team in the next round, odd team numbers will be the bottom team in the next round
// here is where things are getting wonky. Trying to set the next round slot to the team that is being declared the winner
rounds.get(nextRoundNum).games.get(nextGameNum).teams.set(nextTeamNum, team);
}
public Bracket(int numRounds) {
// code that creates the bracket structure. # of rounds. the correct # of games depending on the round. etc. Creates empty shell of "placeholder" teams with no name/info.
for(int i = 0; i < numRounds; i++) {
int numGames // set to (number of games of the last round added) * 2
rounds.add(0, new Round(numGames)
}
}
}
class Round extends JPanel {
ArrayList<Game> games = new ArrayList<Game>();
public Round(int numGames) {
for(int i = 0; i < numGames; i++) {
games.add(new Game());
}
}
// more code...
}
class Game extends JPanel {
ArrayList<Team> teams = new ArrayList<Team>();
// more code... creates two teams per each game in constructor
}
class Team extends JPanel {
String teamName;
public Team(String name) {
teamName = name;
add(new JLabel(name));
}
// simple team info, just going for functionality. not much else is here yet.
}
So, lets say in the first round (index 0 of rounds), in the first game (index 0 of rounds.get(0).games), Team 1 (index 0 of rounds.get(0).games.get(0).teams) wins. It's calculating all the stuff correctly. The team is placed in the correct slot. BUT, it completely removes the team from the current position in the round. So now I'm left with only 1 team in the first game of the first round.
It won't let me have the same Team object referenced in both ArrayLists in Rounds[0].Games[0].Teams and Rounds[1].Games[0].Teams. They are nested array lists in each, so 2 different Array Lists. Am I failing because it's bad to extend the JComponents on the classes themselves, and I should completely refactor this?
I can't see exactly what is going on in your example code, as it is not self-contained. However from your description it looks like you are falling foul of the property that Swing components can only be added to one container at a time. If you add the same component to a second container it is automatically removed from the first one.
This doesn't affect the contents of your ArrayLists in the slightest - you can have the same object in as many different ArrayLists as you like.
It also looks like you are muddying the waters by storing this sort of data inside objects which extend Swing components. I suggest you consider separating out a data structure (the Model) from the display components (the View) to make things clearer. Just get the data structure working first, then build the view from it once you have verified it is correct.
On an unrelated note, it looks like you could simplify the start of your code, where before you had:
public void declareWinner(Team team, Game game, Round round) {
// code that gets current round, game, team numbers to calculate the next round, game, team numbers.
int currentRoundNum = rounds.indexOf(round);
int currentGameNum = rounds.get(currentRoundNum).games.indexOf(game);
int currentTeamNum = rounds.get(currentRoundNum).games.get(currentGameNum).teams.indexOf(team);
...
you could replace these lines with
public void declareWinner(Team team, Game game, Round round) {
// code that gets current round, game, team numbers to calculate the next round, game, team numbers.
int currentRoundNum = rounds.indexOf(round);
int currentGameNum = round.games.indexOf(game);
int currentTeamNum = game.teams.indexOf(team);
...
since you already have references to those objects passed in as arguments.
The requirements of the program are:
Antonia and David are playing a game.
Each player starts with 100 points.
The game uses standard six-sided dice and is played in rounds. During one round, each player rolls one die. The player with the lower roll loses the number of points shown on the higher die. If both players roll the same number, no points are lost by either player.
Write a program to determine the final scores.
I came up with the following code:
import java.util.*;
public class prob3
{
public static void main(String[]args)
{
Random g=new Random();
int a,b,c;
int rounds;
int antonio=100;
int david=100;
Scanner s=new Scanner(System.in);
System.out.println("Please enter the no. of rounds you want to play(1-15): ");
rounds=s.nextInt();
for(int d=1;d<=rounds;d++)
{
a=g.nextInt(6)+1;
b=g.nextInt(6)+1;
System.out.println("Round "+d+":"+a+" "+b);
if(a<b)
antonio=100-b;
else if(a>b)
david=100-a;
}
System.out.println("Total for Antonio: "+antonio);
System.out.println("Total for David: "+david);
}
}
The program fails to calculate the right sum at the end.
What am I doing wrong?
Any help would be appreciated.
Thanks.
You are doing this.
antonio=100-b;
When you probably want
antonio = antonio - b;
The first code simply subtracts the dice roll from 100 every time, which is pointless. You want to subtract the dice roll from the players totals. Do this for both players.
As stated above the "100 - b" was your main problem. But there is no reason in your problem statement to set a number of rounds.
I whould rather use a loop like this:
while(antonio >= 0 && david >= 0){
//do the same stuff here
}
System.out.println...
Since it looks as some exercise for some java course.. This may sound useless but:
Format always your code.. Spaces, brakets and tabs
Use descriptive variable mames. a b c d are not quite intuitive in a larger program.
Remover unused variables
Y mucha suerte tío!
Okay so this is for homework. I don't want a complete answer, just someone to help nudge me in the right direction. I am fairly new to Java, so please take it easy :P Okay so my professor is having us do a Dice simulation program with OOP. This is just one portion of the entire problem, but it's the part I'm stuck on, so if you need more I can provide more. But the instructions say:Make a Roll function that will simulate rolling each die, and return the total
This function should only allow values between the appropriate range (i.e. if each die only has 4 faces, only numbers 1 - 4 should be allowed).
What I have so far for this particular function is this:
public double Roll()
{
for(int i = 0; i < numDice; i++)
{
double total = Math.random()*numFaces + 1;
}
return total;
I don't know where to go from here, and I don't know what really to do. This is my first programming class and it's way over my head :P So like I said, if I could just get pointed in the right direction (using dummy talk, cause I'm still having a hard time grasping this whole thing) that would be awesome. And I can provide more of the actual problem if need be.
Just noticed you used double , replace double with int or short. Look at the following tutorial.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Your also not so hot with naming conventions. Read this.
http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html
You don't need to roll for each face, only for each dice. Do this.
Please note, for this you could use shorts as well.
public int roll() {
return new Random().nextInt(6) + 1; // Returns number between 1 and 6
}
If you want to roll multiple dice you could do this.
public int roll(int amount) {
int total = 0;
for(int i = 0; i < amount; i++) {
total += new Random().nextInt(6) + 1;
}
return total;
}
You're defining total inside the for loop, which makes it invisible outside it. Also, you're overwriting it (=) instead of adding to it (+=) on each die throw.
public double Roll()
{
double total = 0;
for(int i = 0; i < numDice; i++)
{
total += Math.random()*numFaces + 1;
}
return total;
}
I would also recommend to follow Java style and rename the method roll (methods start with a lowercase letter). The return type also strikes me as odd, I would probably use int in a similar situation.
You could create a class named Die to represent a die. This fits with OOP as 'die' would be one of your nouns. Now think of what configuration and behavior a Die might have. You may wish to have a Die have a configurable number of faces, but default to 6 if it isn't specified. You also want to be able to roll a die. Lets see what we have so far. Implementation left up to the reader.
public class Die {
public Die(){
this(6);
}
public Die(int faces){
//TODO: Write a constructor that takes number faces as an argument.
}
public int roll(){
//TODO: Implement a roll for this die, considering the number of faces.
}
}
Ok, so you have the beginning of a Die class. Now you might think, wouldn't it be cool if I could group die together as Dice (a set of dice if you will).
public class Dice {
public Dice(Die... dice){
//TODO: Implement constructor that takes an array of die objects.
}
public int roll(){
//TODO: Roll all the dice, sum and return the result.
}
}
Next you might think, man wouldn't it be sweet if I could treat Dice and a single Die as a single type, I mean they both can be rolled. Let us create an interface called Rollable that specified the roll behavior and have both Dice and Die implement it.
public interface Rollable {
int roll();
}
Then go back and change the class declarations to be.
public class Die implements Rollable
and
public class Dice implements Rollable
Now code that needs to roll things only needs to worry about Rollable instead of Die or Dice
First of all, you need to declare the total outside the for-loop. Then initialize it to zero.
Then, inside the for-loop. Increase the variable.
If numFaces should be able to be different for each die, you will need to get the value for it inside the for-loop, on each iteration.
Also, you should ask yourself: Which possible values do I want for the total variable? Should it be int or double?
You need to define total outside the for loop and then do total+=… inside the loop