randomly generated numbers game with probability and loops - java

In the land of Puzzlevania, Aaron, Bob, and Charlie had an argument over which
one of them was the greatest puzzler of all time.
To end the argument once and
for all, they agreed on a duel to the death.
Aaron was a poor shooter and only hit
his target with a probability of 1>3.
Bob was a bit better and hit his target with a
probability of 1>2.
Charlie was an expert marksman and never missed. A hit means
a kill and the person hit drops out of the duel.
To compensate for the inequities in their marksmanship skills, the three decided
that they would fire in turns, starting with Aaron, followed by Bob, and then by
Charlie. The cycle would repeat until there was one man standing, and that man
would be the Greatest Puzzler of All Time.
An obvious and reasonable strategy is for each man to shoot at the most accurate
shooter still alive, on the grounds that this shooter is the deadliest and has the best
chance of hitting back.Write a program to simulate the duel using this strategy.
Your program should use
random numbers and the probabilities given in the problem to determine whether
a shooter hits the target.
Create a class named Duelist that contains the dueler’s
name and shooting accuracy, a Boolean indicating whether the dueler is still alive,
and a method ShootAtTarget ( Duelist target ) that sets the target to dead if
the dueler hits his target (using a random number and the shooting accuracy) and
does nothing otherwise.
Once you can simulate a single duel, add a loop to your program that simulates
10,000 duels. Count the number of times that each contestant wins and print the
probability of winning for each contestant (e.g., for Aaron your program might
output “Aaron won 3,595>10,000 duels or 35.95%”).
An alternate strategy is for Aaron to intentionally miss on his first shot. Modify the
program to accommodate this new strategy and output the probability of winning
for each contestant.
Which strategy is better for Aaron: to intentionally miss on the
first shot or to try and hit the best shooter? Who has the best chance of winning,
the best shooter or the worst shooter?
Ok so that the problem. Here is my code so far:
public class Duelist {
private String name;
private double probabilityOfHitting;
private boolean alive = true;
//Only declared instance variables. Must created setters and getters
public void setName(String newName){
name = newName;
}
//name setter created
public void setProbabilityOfHitting( double newProbabilityOfHitting){
probabilityOfHitting = newProbabilityOfHitting;
}
//probability of hitting setter created
public void setAlive(boolean newAlive){
alive = newAlive;
}
//name setter created
//now must create getters
public String getName(){
return name;
}
//created the name getter
public double getProbabilityOfHitting(){
return probabilityOfHitting;
}
//created the probability of hitting getter
public boolean getAlive(){
return alive;
}
//created the alive getter
//no constructors created before
public Duelist(String tempName, double tempProbability){
name = tempName;
probabilityOfHitting = tempProbability;
}
//constructor is now created
//need to create a method for the duelists to shoot at each other
public void shootAtTarget(Duelist target){
double randomNum = Math.random();
if (this.probabilityOfHitting ==1){
target.setAlive(false);
target.getAlive();
}
else if (randomNum <= this.probabilityOfHitting){
target.setAlive(false);
target.getAlive();
}
else {
target.getAlive();
}
}
}
public class Tester {
public static void main(String[] args) {
int winsA = 0;
int winsB = 0;
int winsC = 0;
Duelist aaron = new Duelist("Aaron",(1/3));
Duelist bob = new Duelist("Bob", (1/2));
Duelist charlie = new Duelist("Charlie", 1);
if(aaron.getAlive() == true){
if(charlie.getAlive()== true){
aaron.shootAtTarget(charlie);
}
else if(bob.getAlive() == true){
aaron.shootAtTarget(bob);
}
else{
winsA++;
}
}
else if(bob.getAlive() == true){
if(charlie.getAlive() == true){
bob.shootAtTarget(charlie);
}
else if(aaron.getAlive() == true){
bob.shootAtTarget(aaron);
}
else{
winsB++;
}
}
else{
if (bob.getAlive() == true){
charlie.shootAtTarget(bob);
}
else if(aaron.getAlive() == true){
charlie.shootAtTarget(aaron);
}
else{
winsC++;
}
}
System.out.println(winsA);
System.out.println(winsB);
System.out.println(winsC);
}
}
I know I haven't gotten close to finishing the problem yet. What I did in my tester class was to try and simulate one duel and once when I simulated one duel, I would be able to loop it so I can simulate more. The problem I'm having is that the when I run the code, the wins for Aaron, Bob, and Charlie all come up to 0 and I don't know why.

As the last parameter in the constructor calls, you wrote
Duelist aaron = new Duelist("Aaron",(1/3));
There you are dividing an int by another int, and the result will be 0 in this case. This has to be changed to
Duelist aaron = new Duelist("Aaron",(1.0/3.0));
so that double values are used (and the result will be 0.3333, as desired).
Most of your Duelist class does not seem to be "wrong", but the shootAtTarget method could be improved.
A general hint: I'd recommend you to never use Math.random(). This will deliver unpredictable results. Instead, you should use an instance of java.util.Random. This can be initialized with a certain random seed, so that it always provides the same sequence of random numbers. This makes debugging much easier.
Additonally, some tests have been redundant. When the probabilityOfHitting is 1.0, then there is no special test required: The random number will always be less-than-or-equal to 1.0. You are also occasionally calling target.getAlive() for no apparent reason.
So in the end, the method could look like this:
private static Random random = new Random(0);
//need to create a method for the duelists to shoot at each other
public void shootAtTarget(Duelist target)
{
double randomNum = random.nextDouble();
if (randomNum <= this.probabilityOfHitting)
{
target.setAlive(false);
}
}
However, the main problem was in your Test class. I'm not sure about general recommendations here. One could go very far in terms of abstraction. (A Java Enterprise Architect would probably end up with writing a AbstractDuelistStrategyFactory somewhere...). But to put it simply: At the moment, you are doing at most one shot. After one shot, nobody can have won. And you don't know how many shots have to be taken before there is only one duelist remaining.
Much of this could be made more elegant and flexible if you placed the Duelists into a List<Duelist>. But without that, an approach that is "structurally close to what you started" could look like this:
int alive = 3;
while (alive > 1)
{
System.out.println("Status: A:"+aaron.getAlive()+" B:"+bob.getAlive()+" C:"+charlie.getAlive());
if (aaron.getAlive())
{
if(charlie.getAlive())
{
System.out.println("A shoots at C");
aaron.shootAtTarget(charlie);
if (!charlie.getAlive())
{
System.out.println("A killed C");
alive--;
}
}
else if(bob.getAlive())
{
System.out.println("A shoots at B");
aaron.shootAtTarget(bob);
if (!bob.getAlive())
{
System.out.println("A killed B");
alive--;
}
}
}
// Other cases ...
}
if (aaron.getAlive())
{
winsA++;
}
if (bob.getAlive())
{
winsB++;
}
if (charlie.getAlive())
{
winsC++;
}
(Note that there are still cases missing!)

Related

Make a method run in a method java for my game?

I'm struggling with dealing of inventory scan for my game, it basically search for the user inventory if "Flying Broom" if present(it was collected in another method and upload the code is too long), if not it will run the method challengedragon() again; else, it will proceed to the next challenge if the item is present.I was think of inserting method as parameter but it is not possible. This is what I have now. :
public class Main {
String Flyingbroom = "Flying broom";
public static void main(String[] args) {
Player_inventory p = new Player_inventory();
challengedragon();
}
public void challengedragon() {
System.out.println("a Hungarian Horntail dragon! Let's start the battle! You have four options to beat the dragon: ");
System.out.println("1: Fly away with your broom");
System.out.println("2: Fight the dragon");
System.out.println("3: Just run to the egg and get it");
System.out.println("4: Hide behind a rock");
System.out.println("5: Go back to Hogwart");
System.out.println("Your choice is: ");
Scanner in = new Scanner(System.in);
int dragonfightchoice = in .nextInt();
if (dragonfightchoice == 1) {
{
p.Scanitem(Flyingbroom,
"Good choice! You managed to kill the Hungarian Horntail dragon and to get the golden egg",
"You dont have the broom. Try to search for the broom",
playerHP);
proceedtonextchallengelake();
} else if (dragonfightchoice == 2) {
System.out.println("The Hungarian Horntail dragon fired you. - 70HP. ");
playerHP -= 70;
challengedragon();
} else if (dragonfightchoice == 3) {
System.out.println("Bad idea... You lose 100 HP");
playerHP -= 100;
challengedragon();
} else if (dragonfightchoice == 4) {
System.out.println("The dragon found you. You lose 30 HP");
playerHP -= 30;
challengedragon();
} else if (dragonfightchoice == 5) {
Hogwart();
} else {
invalid();
challengedragon();
}
}
For my inventory class:
public void Scanitem(String item, String trueouputext, String textifconditionisnotmet) {
if (inv.contains(item) == true) {
System.out.println(trueouputext);
} else if (inv.contains(item) == false) {
System.out.println(textifconditionisnotmet);
}
public static ArrayList<String> inv = new ArrayList<String>();
Do you guys have any recommendation?
Are there additional steps to populate the inventory (variable inv)?
Also, wouldn't you want ScanItem to answer true or false, depending on whether the item was found? Then you would have something like this:
public boolean scanitem(String item) {
return ( inv.contains(item) );
}
if ( p.scanItem(flyingBroom) ) {
System.out.println("Good choice! You managed to kill the Hungarian Horntail dragon and to get the golden egg");
} else {
System.out.println("You dont have the broom. Try to search for the broom");
}
That will get you closer to what you want. However, there are two other issues which you'll need to put into your code:
You will need a loop of some sort, instead of calling challengeDragon from inside of itself.
Somehow, the return value from scanItem must be used to decide whether to loop.
Currently, you do a nested call of a method each time the player does something, this means that sooner or later you'll run out of the stack. A better idea for the framework for your text-based adventure is to have some kind of a description of the current game's state. The state could be represented as an object that contains the following information:
where's the player currently at (on which step, at which "crossing" etc.)
the player's stats (HP, available skills etc.)
the contents of the player's inventory
some previously made choices affecting the game
Then, the code could be written as a simple loop that does the following:
process player's input
change the state according to the player's input
present the player with available options according to the new state
wait for the next input
repeat

Recursion maze in java

This program doesn't work, but meanwhile it has no error notice...Every time I entered a starting point, the starting point will show up, but no path to the Ending point nor the path it through. the program has a 7*11 Maze, "B" presents obstacle and a fixed ending point which presents as "X" and what the program would do is, you can enter a coordinate into it to make it as your starting point. Then the program would find a way from your starting point to the end (also the path will be shown in "O"). I tried to use recursion during this process, however it wouldn't work, and I don't know why. Please help me out guys.
import java.io.*;
public class Maze {
private static final Maze[][] String = null;
String[][] Maze=new String[7][11];
int x,y;
public static void main(String[] args) throws IOException{
String name;
int k=0,x1,y1;
Maze M=new Maze();
System.out.println("Hello there, would you like to provide your name, please?");
name=M.Name();
M.Maze=M.Set(M.Maze);
M.Print(M.Maze);
while (k==0){
System.out.println(name+", now please enter coordinate of the starting point");
System.out.println("The left top point would be (0,0)");
System.out.println("Now, please enter the x value:");
M.x=M.Input();
System.out.println("And then, please enter the y value");
M.y=M.Input();
if (M.Maze[M.y][M.x]==" "){
M.Maze[M.y][M.x]="$";
k=1;
}
else
System.out.println("Sorry, you cannot put your starting point there, please try again");
}
M.Process(M.x,M.y);
M.Print(M.Maze);
System.out.println("$ is the Starting Point");
System.out.println("X is the Ending Point");
System.out.println("O is the Path");
}
public static String Name() throws IOException{
String name;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
name=br.readLine();
return name;
}
public static int Input()throws IOException{
int i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
i=Integer.parseInt(br.readLine());
return i;
}
public static String[][] Set(String Maze[][]){
for(int i=0;i<7;i++){
for(int j=0;j<11;j++){
Maze[i][j]=("B");
}
}
Maze[1][1]=Maze[2][1]=Maze[3][1]=Maze[4][1]=Maze[5][1]=Maze[1][2]=Maze[1][3]=Maze[2][3]=Maze[3][3]=Maze[5][3]=Maze[3][4]=Maze[5][4]=Maze[1][5]=Maze[2][5]=Maze[3][5]=Maze[5][5]=Maze[3][6]=Maze[4][6]=Maze[5][6]=Maze[1][7]=Maze[2][7]=Maze[2][7]=Maze[3][7]=Maze[5][7]=" ";
Maze[6][7]="X";
Maze[1][8]=Maze[3][8]=Maze[1][9]=Maze[3][9]=Maze[4][9]=Maze[5][9]=" ";
return Maze;
}
public static boolean Process(int x1, int y1){
Maze M=new Maze();
if (Move(M.Maze,x1,y1)){
if (End(x1,y1))
return true;
}
else{
M.Maze[y1][x1]="1";
if (Process(x1-1,y1)){
M.Maze[y1][x1]="O";
return true;
}
else if(Process(x1+1,y1)){
M.Maze[y1][x1]="O";
return true;
}
else if (Process(x1,y1-1)){
M.Maze[y1][x1]="O";
return true;
}
else if (Process(x1,y1+1)){
M.Maze[y1][x1]="O";
return true;
}
}
return false;
}
public static boolean Move(String Maze[][],int x1, int y1){
if (x1<0||y1<0||x1>6||y1>10)
return false;
if ((Maze[y1][x1]=="B")||Maze[y1][x1]=="1")
return false;
return true;
}
public static boolean End(int x1, int y1){
if ((y1==7)&&(x1==5))
return true;
return false;
}
public static void Print(String Maze[][]){
for(int i=0;i<7;i++){
for(int j=0;j<11;j++){
System.out.print(Maze[i][j]);
System.out.print(" ");
}
System.out.println(" ");
}
}
}
I'm not sure, what you want to do with this line, since it is used nowhere:
private static final Maze[][] String = null;
I found several issues in your code:
Every time your code enters the Process-method, a new instance of Maze is created with Maze M=new Maze();. The new instances don't know the extra markings which you made in the steps before (like the 1s), so it will switch back and forth between two neighbouring fields until you get an StackOverflowError.
Also the new Maze instances are not initialized with the labytinth, because you didn't call Set on it. You should place the code of the Set-method in the constructor of Maze, so that this kind of error can't occur.
BUT your program dosen't even come this far. If you feed the Process-method the cooridinates of your start field, it will wonder: "Can I move to the specified field and if so, is it the end?". The answer to "can I move there?" is obviously yes, since you made sure that the start field is clear. The answer to "is this the end?" is no. Process returns true and stops.
--> What you should do about it: place the recursive calls of Process into the if, not the else. You don't need the else.
To prevent the StackOverflowError from item 1 to occur (it does by now) pass an instance of Maze to the Process-method. Remember to do this everytime you call Process and be careful that it always is the same instance. Delete the lines that produce a new Maze instance in Process.
For now you are error free, but it still doesn't work. This is because you mixed up the x and y maximum indices in the Move-method. You declared the array like this: String[][] Maze=new String[7][11];. This means that the maximum x-index is 10 and the maximum y-index is 6. In Move you check the bounds like this: if (x1<0||y1<0||x1>6||y1>10)
Similar is true for the End-method. If you count of the 'X' in your labyrinth, it is the 8-th to the left and 6-the from the top. This corresponds with a y-index of 6 and a x-index of 7. You did (y1==7)&&(x1==5)
Now it works. The 1s are the paths the program tried.
I think you have noticed that you cannot call non-static methods from a static-mehtod like the main-mehtod. If you have an instance of an object, like the M in your code, you can call non-static methods on it with M.<methodName>().
I would strongly advice you to study the object orientated design more closely as it seems you did not understand it.
Also it would be nice if you would adhere to the java naming conventions - only classes and such start with an uppercase letter, everything else starts with a lowercase letter (variables, methods, etc.). It makes things easier to read for those who are used to it, which would almost be everyone, who was taught in a class or with a book.

Java Method not working constantly

I have a text based game that I am making. It is a RPG style where the user is given options linked to numbers and they have to choose a number. Now my problem is that when running the program. A certain method, Decision(), only works certain times. The method is in a superClass while it is being called in the subclass. in the subclass, It works the first time, but not necessarily the second. Also, when I copy the decision method from the superclass into the subclass its starts working, but the next time it is called, it stops. Here is what I've tried and the results. I've included the decision method and where it is being called.
Decision Method:
public int decision(String question, int length, String[] choices){
int[] numbers = new int[length];
int iterator = 1;
for(int i = 0; i < length; i++){
numbers[i] = iterator;
iterator++;
}
boolean done = false;
while(!done){
//print("Test");
print("");
print(question);
String options = "";
for(int i = 0; i < numbers.length; i++){
options = (options + numbers[i] + " - " + choices[i] + " ");
}
print(options);
boolean univSet = true;
int entry = 1;
while(univSet){
if(univInt != 0){
univSet = false;
entry = univInt;
univInt = 0;
//print("testing");
}
}
if(entry == 23){
help();
}else{
for(int i = 0; i < numbers.length; i++){
if(entry == numbers[i]){
done = true;
univInt = 0;
return entry;
}
}
print("Invalid Number, Try again");
print("");
univInt = 0;
}
}
return (Integer) null;
}
Chapter1 Class (Where it's being called:
public class Chapter1 extends Story implements Serializable {
Player player;
public Chapter1(Player player){
this.player = player;
}
public void engage() {
// TODO Auto-generated method stub
player.chapter = 1;
save(player.name);
sPrint("Welcome to Chapter 1");
print("You wake up in a lighted room with white walls.\nA fresh breeze is coming through the window yet the air smells rotten.");
print("You jolt up suddenly. You don't remember anything about how you got here. You've even forgotten who you are.");
print("You look down at your white shirt, there is a streak of blood across the top.\nYou are wearing a nametag that says: " + player.name + ".");
print("You're sitting in a chair but there are no restraints. You decide to get up and look around");
cur = decision("What do you do?", 2, new String[]{"Try the door", "Look out the window"});
print(cur + "");
if(cur == 1){
print("You walk over to the door and try and open it, it is unlocked.\nYou walk through and are welcomed by a cold and poorly lit hallway");
}else{
print("You walk to the window and look outside. You see a huge barren field. You can make out a humanoid like structure.\nYou call out yet the figure doesn't move.");
print("You decide to try the door. It's unlocked so you walk through into a cold dimly lit hallway.");
}
print("You see a dull knife on the floor as well as a door on the end of the hallway");
cur = decision("What do you do?", 2, new String[]{"Go to the door", "Take the knife"});
if(cur == 2){
print("You pick up the knife.");
addWeapon("Kitchen Knife", player);
}else{
print("You walk down the hallway to the door when suddenly the door opens and out comes a zombie.\nIt Lunges for your shoulder. You are caught by surprise and it bites into your skin and you are infected");
gameOver();
}
print("You continue to walk down the hall when suddenly a hideous creature lunges out from the door.\nYou jump back and prepare yourself for a battle.");
battle("Zombie", 5, 2, player);
sPrint("I see that you have succeeded in your first encounter with the undead.\nI congratulate you but you have a long way to go. Remember, I am your only way to learning about your past. \nNow, make your way down to the bottom of the tower. I will help you where I see fit along the way.");
print("You look around and see that the lights have brightened up. The zombie has been mutilated by your Kitchen Knife. \nYou don't know where the voice came from but you are scared. Behind the zombie's original hiding spot you see a staircase.\nYou follow it down, onto what seems to be..the 11th floor.");
print("");
print("Please input 'complete' to continue");
pause();
sPrint("Chapter 1 complete");
}
Now in this class, engage() is being called to run this chapter. And decision is being called where you see it, as well as in the battle() method(the battle method loops a couple times and decision() is called every loop.
Originally, both Decision and battle are in the superclass, but not in the sub class. This results in the first decision method in the class to be called, but not the second. In the second, it stops at the loop checking the value of univInt.
When I put the decision method into the sub class, It passes the first two but it fails to get past the first one in the battle method for the same reason.
When I put both the decision and battle method into the sub class, it has the same result as just putting decision.
Finally if I put battle in the sub class but not decision it only passes the first two again.
In the project I have one variable named cur that holds the integer value of whatever decision returns. I reuse it for every decision. I don't know if that has anything to do with it. This really doesn't make sense to me how whether the methods are in the same class, or inherited would matter at all if they are the same method.
I am ready to clarify anything and I hope someone is able to understand what is going wrong.
EDIT:
univInt is being set to another number other than 0 outside of decision. thats why it works some times. It is a swing class and a method in a superclass sets univInt to whatever is in a TextField when a button is pressed so with that while loop I try to constantly check to see univInt has been changed from 0
It seems like your "univInt" is a class member, not a local variable, and you do not reinitialize it when entering the function. Thus it won't be changed back to allow the program to enter the if-statement you mention.

Bingo Card Game in Java

I created two methods for my Bingo Game in Java. One method creates a new board which populates the Bingo Board with integers according to the Bingo rule (1-75). My second method generates random numbers with a range of 1 - 75.
public static int drawNum(){
Random rand = new Random();
int num = rand.nextInt(75)+1;
return num;
}
public static void bingoCard(){
int [][]card=new int [5][5];
ArrayList<Integer> alreadyUsed = new ArrayList<Integer>();
boolean valid = false;
int tmp = 0;
for(int i = 0; i <= 4; i++){
for(int row = 0; row < card.length; row++){
while(!valid){
tmp = (int)(Math.random() * 15) + 1 + 15 * i;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][i] = tmp;
valid = false;
}
}
card[2][2] = 0;
//create array to make title.
String title []={"B","I","N","G","O"};
for(int i=0;i<title.length;i++){
System.out.print(title[i]+ "\t");
}
System.out.println();
for(int row=0;row<card.length;row++){
for(int col=0;col<card[row].length;col++){
System.out.print(card[row][col]+ "\t");
}
System.out.println();
}
}
What I need help with is, how do I check whether or not the drawNum() method corresponds to any values stored inside my bingoCard() array? If so, print out a new array with the integers filled in. If the condition is met for a bingo, then you win.
I hope I don't make it sound like I want you to do it for me, but I am confused as to how to start coding that part. Thank you.
This my recommendation - Learn Object Oriented Programming immediately
I see you are using objects provided in the JDK, so why not learn to make your own?
Make two classes with the following methods (-) and members (+) (PS. This is not a formal way to document code)
BingoCard
+list of numbers on card
-reset() : gets new numbers for this card
-test(BingoDrawer) : Tests to see if this card won on this drawing
-toString() : returns a String representation of this card
BingoDrawer
+list of numbers drawn
-reset() : draws new numbers
-hasNumber(int number) : tests if this number was drawn
-toString() : returns a String representation of this drawing
One more suggestions
Instead of keeping track of what you used, keep track of what you have not used, it will make things much easier because you can just choose stuff from that list randomly. Unlike your current action which is choosing (a logical number) from thin air and hoping (which causes issues) it is not a collision
If you follow my recommendation you can write code like this
public static void main(String[] args) {
BingoCard bc = new BingoCard();
BingoDrawer bd = new BingoDrawer();
while(thePlayerWantsToPlay()) { //function to be defined by you
bc.reset();
bd.reset();
System.out.println(bc);
System.out.println(bd);
System.out.println(bc.test(bd));
}
}
You can take it a step further and make a BingoGame class and do what I did in main there and just create an instance of BingoGame and call some start method on the object.
For checking if you have the number in your board, read through the board in a similar manner as you do for the already_used numbers, except with the number the user just entered.
The conditions for the user to win should be checked after the board has another number guessed.
There are a few ways to do this, a simple one would be to iterate over every possible pattern that could win, checking to see if there are tokens there.
All of this would be in a loop, that goes a little like this:
Set up board via user entering numbers.
Start loop
set either a timer to wait for, or wait for a keypress (so the game doesn't just play really fast)
Get random number
Possibly add to board
Check if winner
if winner, break the loop and do something else.
Print the new board out.
(end of loop)
If they got here, that could mean they won!
Wait to exit
You can just write it out as pseudo-code and fill in the methods after that. It usually helps to work on these things in a top-down fashion. So, for bingo you might have:
board = generateBoard();
while (!bingoFound(board)) {
number = drawNumber();
board = stampNumbers(board, number);
}
If that makes sense, you can go a step deeper and define each method. For example, bingoFound might look like:
public boolean bingoFound(int[][] board) {
boolean wasFound = bingoRowFound(board)
|| bingoColFound(board)
|| bingoDiagonalFound(board);
return wasFound;
}
Again, I've defined everything in (mostly) pseudo-code. If this looks ok, you can move a step deeper. Let's define the bingoRowFound method.
public boolean bingoRowFound(int[][] board) {
for (int row = 0; row < NUM_ROWS; row++) {
boolean rowIsABingo = true;
for (int col = 0; col < NUM_COLS; col++) {
// We have to check that everything up until this point has
// been marked off. I am using -1 to indicate that a spot has
// been marked.
rowIsABingo = rowIsABingo && board[row][col] == -1;
}
if (rowIsABingo) { return rowIsABingo; }
}
return false; // If we didn't find a bingo, return false.
}
Some of the methods (like drawNumber) will be really easy to implement. Others, like looking for a diagonal bingo might be a bit more difficult.
Feb 12 2014 Update:
Retracted code, since this was a college course assignment, and I want to prevent people just copying the code. I almost got in trouble for being accused of sharing code (which is a nono in assignments) when another student lifted my code from my Github repo and sent it in as their own.
There were two classes, one main class and a class to hold my methods and constructors.
BINGOFINAL.java was my main class.
Bingo_Card.java held my constructor and methods.
If you want to run this, make sure you create a new project called BINGOFINAL, and put Bingo_Card.java into that same */src/ extension.

Getting a string from one class to write to a front screen class

I'm create an air traffic control system, where it generates a random amount of fuel and also a random amount of planes. I have these two elements done, however the issue is, in the output box it all shows and works perfectly. My issue is that I'm telling it, if there is no planes coming in to call the string no planes and if there is a plane then KLM. I can't get it to write to the main class with all the front end.
I've edited out some of the coding in the screen as I'm using Netbeans drag and drop front end:
enter public void StartSimulation()
{
Start pointer = new Start();
Plane incoming = new Plane();
//Needs a condition in here that checks if the plane and fuel has been
//Generated and also loop to keep up with the constant generated planes and fuel
jTextArea1.setText(incoming.planeName);
I have tried where the condition thing is the following:
if (incoming.nextPlaneLanding != 167) this generates the first thing over and over again in the output box. I've also tried setting a boolean in the plane class but again, it has had no effect even with the following condition around it. if (incoming.completed = true)
This is the stuff I have in my plane class:
class Plane
extends TimerTask
{
public int nextPlaneLoop = 0;
public int planes;
public int fuel;
public String planeName;
#Override
public void run()
{
if(nextPlaneLoop <=167)
{
//Currently only running 1 or 0 planes...
planes = (int) (Math.random()*((2-1)+1));
System.out.println("Random generated plane amount: "+planes);
System.out.println("Method called, one whole day loop");
//Adds to the plane in the airspace loop
nextPlaneLoop++;
System.out.println("Loop incrementing: "+nextPlaneLoop);
if(planes == 0)
{
System.out.println("No fuel is required as no planes are coming in");
planeName = "No incoming plane";
System.out.println("Planes name is: "+planeName);
System.out.println(" ");
}
else
{
//Amount of fuel
fuel = 30 + (int)(Math.random()*((120-30)+1));
System.out.println("Random fuel: "+fuel);
planeName = "KLM AirFrance";
System.out.println("Planes name is: "+planeName);
System.out.println(" ");
}
}
else
{
this.cancel();
System.out.println("Not in loop any more. End of day");
}
}
}
Can anyone suggest have to how to get the names to display on to the screen so I can then try and add them into a queue in the actual airport class.
I think the Observer pattern might work well for you. In Java, this is implemented via Observer and Observable.

Categories