First of all, I apologize if this has been asked before and I couldn't find it. I scoured the depths of the internet looking for some guidance but did not come up successful.
In my programming II class we are working on creating a program for the lottery. We have created external classes (did that in the classroom) and have used the objects created in those classes in our driver. For this assignment, we are creating a program which outputs lottery numbers. The program asks the user if they are playing Pick 3, 4, or 5 and then is supposed to output a random number for each "ball". In one of the separate classes we have already imported and instantiated the randomizer. However, when I program the array and for loop, while it generates the proper number of printouts (3 printouts for 3, 4 printouts for 4, and 5 printouts for 5), a new number is not being generated for each loop. Instead, it is holding onto the first value and printing that out for each loop after. I've included my code below. Please help!
import java.util.Scanner;
public class LotteryGame2 {
public static void main(String[] args){
//Declare and instantiate objects
PickGame2 pick = new PickGame2();
Scanner keyboard=new Scanner(System.in);
pick.activate();
//Ask for and obtain user input
System.out.print("Are you playing Pick 3, Pick 4, or Pick 5? Enter number here: ");
int numberOfGame=keyboard.nextInt();
PickGame2[] gamenumber=new PickGame2 [numberOfGame];
for (int i=0; i<gamenumber.length; ++i){
int ball=pick.pullBall();
System.out.println("Ball " + (i+1) + " is " + ball);
}//Ending bracket of for loop
//Close Scanner object
keyboard.close();
}//Ending bracket of main method
}//Ending bracket of class LotteryGame2
The external classes are as follows:
private int ball;
private Random randomizer;
public LotteryContainer(){
this.ball=0;
this.randomizer=new Random();
}//Ending bracket of constructor
public void activate(){
this.ball=this.randomizer.nextInt(9) + 1;
}//Ending bracket of method activate
public int getBall(){
return this.ball;
}//Ending bracket of method getBall
and
private LotteryContainer machine;
public PickGame2(){
this.machine=new LotteryContainer();
}//Ending bracket of constructor
public void activate(){
this.machine.activate();
}//Ending bracket of method activate
public int pullBall(){
return this.machine.getBall();
}//Ending bracket of pullBall
If you look at your PickGame2 class, you'll see that it uses a LotteryContainer for picking the balls. And the LotteryContainer has two methods - one that picks a number for the ball (activate) and one that returns the ball number that was picked (getBall). Since you only ever call pullBall in PickGame2, and pullBall only calls getBall from LotteryContainer, it means you never call the activate method which gets you a new ball.
Add a call to activate before every call to pullBall, and you'll get a different number printed each time.
(Actually, it's possible for a random number generator to generate the same number several times. I don't know what the specification of your homework was, but if it's supposed to simulate a "real" lottery where each ball is different, then just generating random numbers and displaying them is not enough).
Related
I'm writing this golf program for my class that takes a .txt that has 5 numbers per row and 18 rows. The first number in each row is the par for that hole. The other four numbers are for each player.
I kind of have my own spin on this program, though. I wrote another program to create the .txt file with random numbers. The output is dependent on how many players there are which is inputted by the user.
Anyway, I've gotten the .txt generator just fine and I've gotten the Golf program to accurately count how many players there are. What I can't figure out is how to create that number of arrays with different names. I want each array to be int player1[18], player2[18], player3[18], etc.
Here's my code up to that point:
import java.util.Scanner;
import java.io.*;
public class Golf
{
public static void main(String[] args) throws java.io.IOException
{
Scanner countScan = new Scanner(new File("golfscores.txt"));
Scanner file = new Scanner(new File("golfscores.txt"));
//------------------------------------------------------------
// Counting the number of players
//
// This takes the number of integers in the file, divides it by
// the 18 holes in the course and subtracts 1 for the par.
//
// I needed to count the players because it's a variable that
// can change depending on how many players are entered in the
// java program that creates a random scorecard.
//------------------------------------------------------------
int players = 0;
for (int temp = 0; countScan.hasNextInt(); players++)
temp = countScan.nextInt();
players = players/18-1;
//------------------------------------------------------------
//Creating necessary arrays
//------------------------------------------------------------
}
}
EDIT: I must use an array for each player and I am not allowed to use ArrayLists. At this point it looks like I will be using an array of arrays as suggested by some in the comments. Didn't know this was a thing (obviously I'm very noob).
Well you can use a HashMap to store your arrays. Or if you don't care about using strings to get to the array just use 2D Arrays like this:
int[][] players = new int[playerCount][18];
If you then use for example player 2 and want to see hole 12, you'd call players[1][11]
You should not go that way.
Instead create a class named Player to hold each player properties, then create a list of players: List<Player> players = new ArrayList<>();
Add each new player to that list.
I'm in the process of writing a very simple quiz-style boardgame that moves players around the board based on if they answer the question correctly and what they roll on the dice. I'm attempting to create and pass an array mehtod that stores the scores of player 1 and player 2, but the array doesn't seem to actually keep track of the score. For example, a fragment of some of the code is as follows:
public static int[] scorearray
{
int scoreplayer1 = 0;
int scoreplayer2 = 0;
return new int[] = {scoreplayer1, scoreplayer2};
}
public static int questions(int diceroll, int[] score)
{
String textinput = input("What's 9+10?");
int ans = Integer.parseInt(textinput);
if (ans == 19)
{
output("Fantastic answer, that's correct!");
diceroll = dicethrow(diceroll); // rolls the dice
output("Move forward " + diceroll + " squares. You are on square " + score[0]);
//I need the output above to print position 0 in the above array
score[0] = score[0] + diceroll; //array stores the cumulative score
}
else
{
output("Sorry, the answer was 19. Next player's turn.")
//This is where I need the loop to switch between players
}
In addition, I need to come up with a way of switching between player 1 and 2 while also switching to the position 1 in the above array, that is, I need to add to player two's score instead of player one's. I've been combing through this code for ages now trying to figure out how to do this but I can only come up with the idea of using a for/while loop. Other than that I'm truly stumped.
Thanks.
EDIT: It appears that my array apparently still does not store the score when being used in the method questions.
Also I have now realised I can control whose turn it is by creating another method, for example public static void activePlayer() but I'm still not sure how to use a loop (or anything else for that matter) to switch between the two. Also my concern is where I use score[0] = score[0] + diceroll; in my questions method only keeps the score (or at least attempts to; see above problem) for player one. How would I switch it to keep score for score[1]? Please.
your options here seem to be either have your questions function output the score or change your score object to be a static object instead of a static function.
public static int[] scorearray = [0,0];
or
public static int[] questions(int diceroll, int[] score)
`
System.err.println("welcome to the game");
System.err.println("please throw your dice 10 times");
Scanner s=new Scanner(System.in);
Random r=new Random();
for(int i=0;i<10;i++)
{
System.err.println("try"+i);
int d= r.nextInt(6)+1;
System.err.println(r.nextInt(10)+1);
}
}
I have a question,I am developing a basic game dice rolling .I am a bit confused that how to take random number when user press enter key each time ,a new random number is generated ?here ,all the random no. is genereted at once.but I want it just like user inputs any integer no or double etc after pressing the enter key.
I'm going to assume you mean you want the user to press a button, and a new number is randomly generated.
First off, in Java, a random number is generated from the Random class.
You can import Random by saying, at the top of your code:
import java.util.*;
or, to be more precise:
import java.util.Random;
When you want to generate a random number in your main method, you must make a Random object, then create an instance of Random, since Java is an Object-Oriented Language. In other words, like this:
public static void main(String[] args) {
Random r = new Random();
int rantInt = r.nextInt(7); //random integer between 0 and 6
}
You could use the Scanner class to get user input; however, at your level, I would suggest simply rerunning the program to get a new random dice roll.
Also, on StackOverflow, as well as any other Stack Exchange website (or any forum, to be honest), you should be clear about your question. At the very least, write in complete sentences and with proper grammar. If possible, provide some of your source code, as well as your environment/experience.
I need to write a program for Java that "rolls" two 6-sided die and that keeps track of how many tries it took to roll a 7. The program also needs to run this process N number of times, determined by the user. After the Nth trial, the program needs to compute the average amount of trials it takes to roll a 7.
I'm pretty confident that I should use a while loop inside of a for loop but I'm unsure of exactly how to do it. I already have written the code to a program that "rolls the dice," and is shown below.
import java.util.*;
public class RollDice {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
String input = "";
do {
System.out.println("Rolling the dice...");
System.out.println("You rolled a"+((rand.nextInt(6)+1)+(rand.nextInt(6)+1)));
System.out.println("Roll again? (y/n)");
input = keyboard.next();
} while (input.equalsIgnoreCase("y"));
}
}
Yes, I know it's a do-while loop, but it's all I have so far.
https://codereview.stackexchange.com/questions/31980/a-simple-dice-roll-game
This would be a great place for you to start. Then just add a second die, and a variable for the average. But please do not copy this code directly. Use it as a template/guideline. I want no part in plagiarism.
Ok, I am having a problem receiving a value... I have been researching for several days, but nothing has hit the topic I need. It is a mastermind game. I am creating this for a Final project in my High School programming class. The Eclipse Compiler is telling me that in cannot be resolved. How do I fix this and Accomplish my goal. This is not being run in an applet.
package masterMind;
import java.util.Scanner;
public class MasterMind {
public static void main(String[] args) {
System.out.println("This is MasterMind, a logic game");
System.out.println("To win you must guess correctly where each number is");
System.out.println("You will be told if you get one correct");
System.out.println("You will only get 10 tries, then you lose");
System.out.println("Lets begin");
//Change this value to change the game
int m1=2;
int m2 =3;
int m3=2;
int m4=1;
//Create Board
System.out.println("__ __ __ __");
Scanner UserGuess = new Scanner(System.in);
int num = in.nextInt();
I have very limited Coding knowledge, so please keep it simple and explain
System.in is the InputStream of the system (like the cmd for windows) , in order to read from that you use the Scanner or InputStreamReader just like you are trying to do ... so instead of
in.nextInt();
you need
userGuess.nextInt();
and btw learn to use capital letters properly as it will help you later , like userGuess should not start with a capital since its an instance not a class.
anyways , for your game you have to guess 10 times which means you have to repeat the same guessing action 10 times or till the user guesses all the numbers , thats when you should use a while loop like so ....
boolean guessedAll = false;
int guessedCount=0;
int tryCounter=0;
while(tryCounter<9 || !guessedAll){
//read the number from the user and test it ...
//if number equals one of the numbers above then guessedCount++ ...
//if guessedCount==4 then guessedAll=true
tryCounter++;
}
now i almost gave you all of the algorithm needed to do that homework , but i ain't going to solve it for you till you try , else you will learn nothing ;)
you could ofcourse ask for help as comment after you've tried some ... good luck
for nextInt method you should call it from Scanner object
Change this
int num = in.nextInt();
To
int num = UserGuess.nextInt();
You never closed the brackets when you started the class nor when you started the main method. Match every { with a }.
package masterMind;
import java.util.Scanner;
public class MasterMind {
public static void main(String[] args) {
System.out.println("This is MasterMind, a logic game");
System.out.println("To win you must guess correctly where each number is");
System.out.println("You will be told if you get one correct");
System.out.println("You will only get 10 tries, then you lose");
System.out.println("Lets begin");
//Change this value to change the game
int m1=2;
int m2 =3;
int m3=2;
int m4=1;
//Create Board By randomly generating the number
//After generating the code, print the blank board to start the game
System.out.println("__ __ __ __");
//Take in the user's guess (limit is 10)
int limit = 10
for(int i = 0; i < limit; ++i) {
Scanner UserGuess = new Scanner(System.in);
int num = in.nextInt();
//Other logic..Leaving it for you to attempt
}
}
You want to make a program which the user must guess where each number is in a 4 digit code.. Well how do you do this?
We need the user to be able to input a number, typically the rules of this game are:
There are 6 possible numbers or colors
The code is 4 numbers or colors long
The user has ten tries to guess the code correctly
That means we have to start by doing something like this.
Generate the 4-digit code somehow (with the possible combinations from 0000-6666) and the split the random number put it in an array
Ask the user to enter a number guess along with a position for that number
Keep checking the user guess against the code, each time display the current guesses and which ones they have correct