How to Make it so that the User ends this program? - java

// ************************************************************
// ELEVATOR.java
//
// ELEVAOTR SIMULATION
// PROBLEM: NEED TO FIND A WAY TO AMKE IT SO THAT THE PROGRAM KEEPS RNNING AFTER USER INPUTS
// THIER FIRST DESIRED FLOOR.
// ************************************************************
import java.util.*;
public class Elevator_Simulation {
public static void main (String[] args) {
Person User = new Person();
Floor floors = new Floor();
floors.moveElevator(User.getDesiredFloor());
}
}
class Elevator { //NEEDS SETTER & GETTER METHODS
private int mass=0;
private int capcity=0;
private String name="";
private String color="";
}
class Floor {
ArrayList<Object> floorLevel = new ArrayList<Object>();
Elevator Lift = new Elevator();
Person Man = new Person();
Floor() { //Floors 0-9
floorLevel.add(Lift); //0
floorLevel.add(null); //1
floorLevel.add(null); //2
floorLevel.add(null); //3
floorLevel.add(null); //4
floorLevel.add(null); //5
floorLevel.add(null); //6
floorLevel.add(null); //7
floorLevel.add(null); //8
floorLevel.add(null); //9
}
System.out.println("Elevator is at Floor: " + floorLevel.indexOf(Lift) );
public void moveElevator (int chosenFloor) {
if (chosenFloor > 9) {
System.out.println("Woooooah Buddy! You can only choose 0-9!");
return;
}
if (chosenFloor == floorLevel.indexOf(Lift)) {
System.out.println("Bro you're already on that floor...");
}
while (floorLevel.indexOf(Lift)>chosenFloor) {
Collections.swap(floorLevel, floorLevel.indexOf(Lift), ( floorLevel.indexOf(Lift)-1 ) );
System.out.println(floorLevel.indexOf(Lift) );
}
while (floorLevel.indexOf(Lift)<chosenFloor) {
Collections.swap(floorLevel, floorLevel.indexOf(Lift), ( floorLevel.indexOf(Lift)+1 ) );
System.out.println(floorLevel.indexOf(Lift) );
}
}
}
class Person {
Scanner scan = new Scanner(System.in);
public int getDesiredFloor() {
int desiredFloor = scan.nextInt();
return desiredFloor;
}
}
Above is an Elevator Simulator Code (before I attempt to make one with a GUI) and my only problem, aside from the obvious beginner flaws, is that I'm having trouble of finding a way to make it so that the program doesn't just end once the user inputs one floor. I at least want the program to run until the user ends it with a command. I'm thinking of using a while loop somewhere but where? Please help and point out anything I should improve in this code.

You can put the while loop around the line
floors.moveElevator(User.getDesiredFloor());
Just add an input check for a value that represents exiting.

Related

Poker game : find likelihood of winning for a player

I have java based application for Texas Holdem Poker. I have to introduce a feature wherein whenever all players except one goes for all in, we have to calculate probability of winning for each player.
This can happen in pre-flop, flop & turn round. As you may know in pre-flop stage all 5 cards have to be chosen, in flop there are already 3 community cards in the table, 2 more cards have to be
chosen, whereas in turn round 1 more cards have to be chosen. Let us assume there are 2 players.
So each of the players have 2 hole cards. So we have to choose 2 cards from deck of 52 -2*2 = 48 cards. By using combinatorics I am able to do that. But in pre-flop stage there are too many combinations, from 48 we have to choose 5 cards which is 48Cr5 = 1712304 combinations. If I do that much computation the game gets stuck. So tried to use ForkJoinPool. I found there are only 2 cores in the machine where the application is deployed. It is not working at all. Is ForkJoinPool suitable for this task or should I go for some other ExecutorService. Here is some of my RecursiveTask code
public class WinnerPercentageTask extends RecursiveTask<List<String>> {
private static int threshold = 50_000;
private List<List<Byte>> combinations;
private int start;
private int end;
private ITexasHoldemGame game;
public WinnerPercentageTask(ITexasHoldemGame game, List<List<Byte>> allCombinations, int start, int end) {
super();
this.game = game;
this.combinations = allCombinations;
this.start = start;
this.end = end;
}
#Override
protected List<String> compute() {
if (end - start < threshold) {
return computeDirectly();
}
else {
int middle = (end + start) / 2;
WinnerPercentageTask subTask1 = new WinnerPercentageTask(game,combinations, start, middle);
WinnerPercentageTask subTask2 = new WinnerPercentageTask(game,combinations, middle, end);
invokeAll(subTask1, subTask2);
List<String> ret = new ArrayList<>();
ret.addAll(subTask1.join());
ret.addAll(subTask1.join());
return ret;
}
}
private List<String> computeDirectly() {
List<Card> communityCards = game.getCommunityCardsDealt();
List<Winner> winners = new ArrayList<>();
List<String> winnersForAllCombinations = new ArrayList<>();
for(List<Byte> combination: combinations.subList(start, end)) {
List<Card> allCommunityCard = new ArrayList<>();
for (Card c : communityCards) {
allCommunityCard.add(new Card(c.getId(), c.getFaceValue(), c.getSuit()));
}
for (Byte b : combination) {
Card fakeCommunityCard = new Card(b);
allCommunityCard.add(fakeCommunityCard);
}
List<PokerHand> playerRankList = calculateHandRank(allCommunityCard);
winners = prepareWinnerList(playerRankList);
winnersForAllCombinations.addAll(
winners.stream()
.map(Winner:: getPlayerId)
.collect(Collectors.toList()));
}
return winnersForAllCombinations;
}
private List<PokerHand> calculateHandRank(List<Card> communityCardsDealt) {
List<PokerHand> playerRankList = new ArrayList<>();
Map<String, List<Card>> playersCards = this.game.getCardsDealtForAllPlayers();
playersCards.forEach((player, holeCards) -> {
PokerHand pokerHand = new PokerHand(player, holeCards);
HandRanker.checkRanking(pokerHand, communityCardsDealt);
playerRankList.add(pokerHand);
});
Collections.sort(playerRankList);
// if (logger.isInfoEnabled()) {
// logger.info("Player Rank List : {}", playerRankList);
// }
return playerRankList;
}
private List<Winner> prepareWinnerList(List<PokerHand> playerRankList) {
List<Winner> winnerList = new ArrayList<>();
if (!CollectionUtils.isEmpty(playerRankList)) {
// Grouping Players based on similar Ranks
Map<HandRankingEnum, List<PokerHand>> groupByRankMap = playerRankList.stream()
.collect(Collectors.groupingBy(PokerHand::getRankingEnum));
// Sort the Map based on Rank, highest rank first
List<Map.Entry<HandRankingEnum, List<PokerHand>>> sortedWinnerList = groupByRankMap
.entrySet().stream().sorted(reverseOrder(Map.Entry.comparingByKey()))
.collect(Collectors.toList());
// Reading the Winners of highest rank
Map.Entry<HandRankingEnum, List<PokerHand>> winnerListMap = sortedWinnerList
.get(0);
List<PokerHand> highestRankList = winnerListMap.getValue();
List<PokerHand> winnerHandList = new WinnerIdentifier().getWinners(highestRankList);
for (PokerHand hand : winnerHandList) {
Winner winnerPlayer = Winner.builder()
.rank((byte) hand.getRankingEnum().getValue())
.rankName(hand.getRankingEnum().name())
.playerId(hand.getGamePlayerId()).cards(hand.getRankingList())
.pots(new ArrayList<>()).build();
winnerList.add(winnerPlayer);
}
}
return winnerList;
}
}
`

How do I access a record from another procedure?

So I am having an issue where I would like to create a record in one procedure, then alter the attributes of that record using other procedures and functions.
import java.util.Scanner; // Imports scanner utility
import java.util.Random;
import java.lang.Math;
class alienPet
{
public void main (String[] param)
{
// We want to call all of the functions
// and procedures to make an interactive
// alien program for the user.
welcomeMessage();
alienCreation();
System.exit(0);
} // END main
/* ***************************************
* Define a method to obtain the users input
* and start the correct method.
*/
public static String userInput (String message)
{
Scanner scan = new Scanner(System.in);
String inp;
print(message);
inp = scan.nextLine();
return inp;
} // END userInput
/* ***************************************
* Define a method to print messages.
*/
public static void print (String message)
{
System.out.println(message);
return;
} // END print
/* ***************************************
* Define a method to
*/
public static void welcomeMessage ()
{
print("Thank you for playing the pet alien game");
print("In this game, you will have to look after your own alien.");
print("There is multiple aspects to looking after your alien, such as:");
print("Hunger, Behaviour and Thirst.");
print("");
print("When prompted, you can use the following commands:");
print("feed -> Replenishes alien to max hunger level");
print("drink -> Replenished thirst level to max");
print("");
return;
} // END
/* ***************************************
* Define a method to
*/
public void alienCreation ()
{
Alien ufo = new Alien();
ufo.name = userInput("What would you like to name your new alien?");
ufo.hungerRate = ranNum(1, 6);
print("On a scale of 1-6, your alien, " + ufo.name + ", has a hunger rate of " + ufo.hungerRate);
alienBehaviour(ufo.hungerRate);
return;
} // END alienCreation
public void alienBehaviour (int hunger) {
if (hunger <= 2){
print(ufo.name + " is very hungry, and is dangerously angry!!");
String action = userInput("You should feed it as soon as possible. (by typing 'feed')");
if (action.equals("feed")){
feedAlien();
}else if (action.equals("drink")) {
alienDrink();
}else{
print("That is a dangerous decision.");
}
}else if (hunger <= 4) {
print(ufo.name + " is mildly hungry, but is in a calm state.");
String action = userInput("Would you like to take any actions?");
if (action.equals("feed")){
feedAlien();
}else if (action.equals("drink")) {
alienDrink();
}else{
print("Okay.");
}
}else if (hunger <= 6) {
print(ufo.name + " is not hungry and is in a happy state.");
String action = userInput("Would you like to take any actions?");
if (action.equals("feed")){
feedAlien();
}else if (action.equals("drink")) {
alienDrink();
}else{
print("Okay.");
}
}
}
public void feedAlien() {
ufo.hungerRate = 6;
print(ufo.name + "'s hunger level replenished to max level 6.");
print(ufo.name + " is now at a happy level.");
}
public void alienDrink() {
ufo.thirst = 6;
print(ufo.name + "'s thirst level replenished to max level 6.");
}
public static int ranNum(int min, int max){ // A function that generates a random integer wihin a given range.
Random random = new Random();
return random.ints(min,(max+1)).findFirst().getAsInt();
} // END ranNum
} // END class alienPet
class Alien {
String name;
int age = 0;
int hungerRate;
int thirst = 6;
}
Obviously, some of the annotations are incomplete as of this time, but the issue I am having is in the alienBehaviour(), feedAlien() and alienDrink() procedures, I cannot seem to access the record created in the alienCreation() procedure.
The errors are all the same and is as follows:
alienPet.java:84: error: cannot find symbol
print(ufo.name + " is very hungry, and is dangerously angry!!");
^
symbol: variable ufo
location: class alienPet
Now I am new to java, so I'm not sure whether I have to make the record global or something, so any help would be greatly appreciated.
Variables declared inside of a method are called local variables and are likely disposed of when the method finishes executing.
Variables declared outside any function are called instance variables and they can be accessed (used) on any function in the program.
You are looking for an instance Alien ufo variable.
class alienPet{ // It is recommended you use the java naming convention.
Alien myAlien = new Alien();
// alienPet a = new alienPet();
// a.myAlien; // you could potentially do this to get an alien from an alienPet class
void someVoid(){
Alien otherAlien;
}
void errorVoid(){
otherAlien.toString();
// causes an error, the otherAlien variable is never visible to errorVoid as it is a local variable
myAlien.toString(); // OK
}
}
https://www.oracle.com/technetwork/java/codeconventions-135099.html
You're having problems with the scope of your variable. Variables are only valid within the curly braces which they were declared in.
WRONG
public void alienCreation ()
{
Alien ufo = new Alien();
ufo.name = userInput("What would you like to name your new alien?");
ufo.hungerRate = ranNum(1, 6);
print("On a scale of 1-6, your alien, " + ufo.name + ", has a hunger rate of " + ufo.hungerRate);
alienBehaviour(ufo.hungerRate);
return;
} // END alienCreation and of the scope of your variable ufo
RIGHT
class alienPet
{
Alien ufo;
[...]
public void alienCreation ()
{
ufo = new Alien();
ufo.name = userInput("What would you like to name your new alien?");
ufo.hungerRate = ranNum(1, 6);
print("On a scale of 1-6, your alien, " + ufo.name + ", has a hunger rate of " + ufo.hungerRate);
alienBehaviour(ufo.hungerRate);
return;
} // END alienCreation and your variable ufo will be initialized afterwards
}

Array will not update but rather print out the wrong array

I managed to figure out how to print the array for my connect four program but I cannot get the board to update with my code, I looked at it and ran it the code works in theory but however the array won't take the new inputs
Ive tried running it through with a for loop but that turned out wrong and I was thinking about putting the drop method in the print board method but I feel that that would result in an error
public class Connect4 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// DON'T MODIFY THE MAIN METHOD UNLESS FOR DEBUGGING
//MAKE SURE YOU GET RID OF YOUR MODIFICATIONS HERE BEFORE
SUBMISSION
String[][] board = createEmptyBoard();
Scanner input = new Scanner(System.in);
boolean bl = true;
printPattern(board);
while(bl) {
int player1 = 1 , player2 = 2 , userInput;
System.out.println("Please drop a RED disk at the column between 0
and 6:");
userInput = input.nextInt();
dropDisk(board, userInput , player1);
printPattern(board);
System.out.println("Please drop a YELLOW disk at the column
between 0 and 6:");
userInput = input.nextInt();
dropDisk(board, userInput , player2);
printPattern(board);
String win = checkWinner(board);
/*
Write code to announce if there is winner and end the game
*/
}
}
public static String[][] createEmptyBoard() {
/* This method prints the first empty pattern for the game
DON'T MODIFY THIS METHOD
*/
String[][] f = new String[7][15];
for (int i =0;i<f.length;i++) {
for (int j =0;j<f[i].length;j++) {
if (j% 2 == 0) f[i][j] ="|";
else f[i][j] = " ";
if (i==6) f[i][j]= "-";
}
}
return f;
} // end of createEmptyBoard
public static void printPattern(String[][] brd) {
for (int i = 0; i < 7; i++){
System.out.println(brd[i][0] + brd[i][1]+ brd[i][2]+ brd[i][3]+
brd[i][4]+ brd[i][5]+ brd[i][6]+ brd[i][7]+ brd[i][8]+ brd[i][9]+
brd[i][10]+ brd[i][11]+ brd[i][12]+ brd[i][13]+ brd[i][14]);
}
} // end of printPattern
public static void dropDisk(String[][] brd, int position, int
player) {
if (player == 1){
brd[6][position] = "R";
if(brd[6][position] == "R"){
brd[6][position] = brd[6 - 1][position];
}
}
else if (player == 2){
brd[6][position] = "Y";
if(brd[6][position] == "Y"){
brd[6][position] = brd[6 - 1][position];
}
}
/*Write your code to drop the disk at the position the user entered
depending on which player*/
} // end of dropDisk
The logic of dropDisk seems to be not finished yet.
It sets the brd[6][position] to R or Y, just to immediately after that set it to the current value of brd[5][position].
And this should always be null.
In Java, objects are passed into methods by value. This means that when you pass a parameter into a function, the JVM makes a copy of that object which can be modified in the method.
In this case, when you pass brd into dropDisk, it is copied, and you make changes to the copy inside dropDisk. But once dropDisk ends, that copy is discarded. No changes are made to the board from your main method. This is because your board is an array of Strings, and Strings are immutable, meaning that they cannot be changed after instantiation.
If you wanted the board from your main method to update, consider returning brd in dropDisk.

How to capture click between several operations, 3,4,5,6, X, 2?

I'm programming a game of cards in Java and everything is going well, but I've come up with an unforeseen reason why I think I can not think of what to use and I want to know what idea to follow. I go:
My game:
My game consists of 6 players, I am always the Player 1 and the other players the computer, therefore I have done with 6 JLabel in a JFrame, each Jlabel means the card that throws jug1 ... jug6, and in the code I take the order of which player wins the hand with an array of integers equal to [3,4,5,6,1,2] assuming player 3 was won by hand.
My problem:
Taking the above arrangement as a reference [3,4,5,6,1,2], it means that in the next hand players [3,4,5,6] must show their card before Player 1, and After Player 1 shows his card, he must show Player 2.
I know how to show the cards of the first four players, but how can I make my program wait for me to click on my selected card and then continue with the last card of Player 2, my main question is how to receive that click Of Player 1 between players, before or after.
Here a fragment:
public void Tirar(JLabel [] label_cartas_en_mesa) //director function
{
cartas_en_mesa = new Vector<Baraja>();
for ( int i =0; i < 6; i++ )
{
switch( orden_de_tiro [i] )
{
case 1: { Tirar_Jugador1(label_cartas_en_mesa, i); break; }
case 2: { Tirar_Jugador2(label_cartas_en_mesa, i); break; }
case 3: { Tirar_Jugador3(label_cartas_en_mesa, i); break; }
case 4: { Tirar_Jugador4(label_cartas_en_mesa, i); break; }
case 5: { Tirar_Jugador5(label_cartas_en_mesa, i); break; }
case 6: { Tirar_Jugador6(label_cartas_en_mesa, i); break; }
default:break;
}
}
}
public void Tirar_Jugador1(JLabel [] label_cartas_en_mesa, int pos)
{ //decision_jug1 = true when I clicked a card and then break a loop.
while(decision_jug1==false) //My wrong idea to wait, I think..
{ }
label_cartas_en_mesa[pos].setIcon( new ImageIcon( Jug1_Barajas.get(pos_baraja_jug1).getImagen() ) );
cartas_en_mesa.add( Jug1_Barajas.get(pos_baraja_jug1) );
Jug1_Barajas.remove(pos_baraja_jug1);
decision_jug1 = false;
}
public void Tirar_Jugador2(JLabel [] label_cartas_en_mesa, int pos)
{
label_cartas_en_mesa[ pos ].setIcon( new ImageIcon( Jug2_Barajas.get(0).getImagen()));
cartas_en_mesa.add( Jug2_Barajas.get(0) );
Jug2_Barajas.remove(0);
}
public void Tirar_Jugador3(JLabel [] label_cartas_en_mesa, int pos)
{
label_cartas_en_mesa[ pos ].setIcon( new ImageIcon( Jug3_Barajas.get(0).getImagen()));
cartas_en_mesa.add( Jug3_Barajas.get(0) );
Jug3_Barajas.remove(0);
}
public void Tirar_Jugador4(JLabel [] label_cartas_en_mesa, int pos)
{
label_cartas_en_mesa[ pos ].setIcon( new ImageIcon( Jug4_Barajas.get(0).getImagen()));
cartas_en_mesa.add( Jug4_Barajas.get(0) );
Jug4_Barajas.remove(0);
}
public void Tirar_Jugador5(JLabel [] label_cartas_en_mesa, int pos)
{
label_cartas_en_mesa[ pos ].setIcon( new ImageIcon( Jug5_Barajas.get(0).getImagen()));
cartas_en_mesa.add( Jug5_Barajas.get(0) );
Jug5_Barajas.remove(0);
}
public void Tirar_Jugador6(JLabel [] label_cartas_en_mesa, int pos)
{
label_cartas_en_mesa[ pos ].setIcon( new ImageIcon( Jug6_Barajas.get(0).getImagen()));
cartas_en_mesa.add( Jug6_Barajas.get(0) );
Jug6_Barajas.remove(0);
}
regards,
Alex
you can have an array of players, all of them including you.
the player may have several members and methods, the 2 methods i want to focus on are play() and isHuman(), in your Game class? there is a method playHand(int) which will control the process:
assume the players array (or list) is
//it contains 6 objects, one of them is You.
List<Player> players = new ArrayList<Player>();
players.add(player1);// add all 6 players...
//make sure when u add human to set isHuman(true)...
and we need to have a method that we will call when it's the Human (you) turn in game, assume it's notifiyHumanPlayer(int)
we also need a local member (class scope) variable the points to the current player.
private int CURRENT_PLAYER = 0;
so your code may look like this:
the method that starts the hand (the round)
private void playHand(int startingPlayerIndex){
for(int i=startingPlayerIndex; i<players.size();i++){
CURRENT_PLAYER = i;
if(!players.get(i).isHuman()){
//not human
notifiyPlayer(i);
players.get(i).play();
}else{
//human
notifiyPlayer(i);
//no call to play();...
break;
}
}//for loop
//when loop ends, all players were done, do what you do at end of each hand...
calculateHandWinner();
}
Shows a simple indicator (arrow) or play some sound...
private void notifiyPlayer(int myIndex){
//it may show an arrow or indeicator on/next player icon, to show which who's playing now
showTurnIndecator(myIndex);
}
when it's your turn, just the onClick of any card you have
private void humanPlayerOnClick(){
//this is the onClick() of the human (when human clicks on any of the cards)
//write the code for drawing a card from human's hand
// now we need to see if human was last player, or not,
if(CURRENT_PLAYER+1 >= players.size()){
//all players were done, do what you do at end of each hand...
calculateHandWinner();
}else{
//still more players after human in the array
playHand(CURRENT_PLAYER+1); // same loop but it will start from the player next to human.
}
}
private void calculateHandWinner(){
//do your logic here ...
//re arrange players list...
playHand(0);//start next hand from first player...
}
not sure if this will suite your current structure you may take something useful out of it.

Unfair Candy Distribution

I am completing an assignment and am having a hard time figuring out the logic need to make the program work. I do not want a direct answer but could someone point me in the right direction?
Assignment:
Define a class named UnfairCandyDistributor. An UnfairCandyDistributor object represents a mean big brother who is going to divide a set of candies between himself and his hungry little brother. This will be done unfairly: for every candy given to the sibling, the big brother takes for himself a number of additional candies equal to the younger sibling's total. Each UnfairCandyDistributor object should have the same method:
public void nextCandy()
Each time nextCandy is called, the method prints a message about who gets a candy. Each call to nextCandy produces a single line of output. This time the output is the following:
public class TestCandy2 {
public static void main(String[] args) {
UnfairCandyDistributor mean = new UnfairCandyDistributor();
mean.nextCandy(); // 1 for you.
mean.nextCandy(); // 1 for me.
mean.nextCandy(); // 2 for you.
mean.nextCandy(); // 1 for me.
mean.nextCandy(); // 2 for me.
mean.nextCandy(); // 3 for you.
mean.nextCandy(); // 1 for me.
mean.nextCandy(); // 2 for me.
mean.nextCandy(); // 3 for me.
Here The class I have made so far:
public class UnfairCandyDistributor {
private int you;
private int me;
private int extra;
public void nextCandy()
{
if (you != me || extra != you - 1)
{
me++;
System.out.println(me + " for me");
}
else
{
you++;
System.out.println(you + " for you");
extra = 0;
}
}
}
Can't you just add a boolean variable that tells you who to dole out candy to?
public class UnfairCandyDistributor {
private int you = 0;
private int me = 0;
private boolean candyToMe = false;
public void nextCandy()
{
if (candyToMe)
{
for (int i=0; i<you; i++) {
System.out.println("one for me");
me++;
}
else
{
System.out.println("one for you");
you++;
}
candyToMe = !candyToMe;
}
}
or
public class UnfairCandyDistributor {
private int you = 0;
private int me = 0;
private boolean candyToMe = false;
public void nextCandy()
{
if (candyToMe)
{
System.out.println(you + " for me");
me += you;
}
else
{
System.out.println("1 for you");
you++;
}
candyToMe = !candyToMe;
}
}
..depending on whether you want the candies doled out one at a time or in hand-fulls where appropriate.

Categories