My return statement is not working while all values up until the get statement (i.e. the set, variables, etc) are working, if forced to a value the display works.
if (Pasta.isChecked() && Pork.isChecked() && Tomato.isChecked() && Carrots.isChecked() && TomatoPaste.isChecked()) {
// RecipeCodes recipe1 = new RecipeCodes();
//recipe1.setRecipeCode(1);
setRecipeCode(1);
getRecipecode();
//Recipecode = 1;
Log.i("INTERNAL CHECK", "RCODE ~" + Recipecode);
break;
public void setRecipeCode(int C) {
Recipecode = C;
Log.i("SETRECIPECODETEST", "RECIPE CODE ~ " + Recipecode);
}
public int getRecipecode(){
return Recipecode;
}
Here is my code for the class that displays based on the "RecipeCode" variable
Recipes temp = new Recipes();
RecipeCodes RDisplay = new RecipeCodes();
//temp.getRecipeCode();
if(temp.getRecipecode() == 1){
RDesc.setText("Italiano Sausage");
//Log.i("WITHINIF","RCODE INTERNAL ~ " + temp.getRecipeCode());
} else {
RDesc.setText("test");
//Log.i("TEST","RCODE WITHIN DISPLAY ~ " + RDisplay.getRecipeCode());
}
(I've done a lot of editing and commenting out of lines so if there's minor syntax errors my bad).
This works:
class Recipe {
private int recipecode;
public void setRecipeCode(int c) {
recipecode = c;
}
public int getRecipecode() {
return recipecode;
}
public static void main(String[] args)
{
Recipe temp = new Recipe();
temp.setRecipeCode(1);
System.out.println(temp.getRecipecode());
}
}
Related
I am looking to create an algorithm in Java that can take any number of "players" and group them up a specified number of times each. However, two pairs cannot be the same. So, if we are supplied 9 players (dubbed 0, 1, 2, etc) by the user and each player should be paired 3 times, that means that this algorithm needs to be able to generate a list of pairs where each player is paired 3 times.
So 4 players being paired two times could be: {{0, 1}, {2, 3}, {0, 2}, {1, 3}}.
Obviously, it can be impossible in some scenarios (like 4 players being uniquely paired 20 times), but I have input restrictions to combat that.
{0, 1} and {1, 0} are equal pairs. The order of the numbers does not matter, they are not unique.
The preferable way for input is just given two numbers (number of players, number of pairs per players) and the preferable way for the output to be given is in a two dimensional array of integers (each player being dubbed by an integer), like I gave an example of.
Does anyone have any ideas on how to do this? Pseudo-code, actual code, any ideas are welcome. Thanks!
I think your question is valid and interesting to solve in code.
This is why I coded that whole thing.
There's one downside to my solution, or rather: the problem.
In certain situations, some players can have many matches between them, while others have little. So in the end, some players might not get matched properly.
In this case, you'd need a mathematical trick, or a backtracking algorithm, that steps back on parts of the solution and tries (brute-forces) other combinations. My algorithm has neither, but it indicates Exceptions and validity.
Also check the comments in the code.
package snippet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
public class BadPairingStuff6 {
static class Player {
public final int mID;
private final BadPairingStuff6 mParentLogic;
public int mMatches;
public Player(final int pID, final BadPairingStuff6 pBadPairingStuff5) {
mID = pID;
mParentLogic = pBadPairingStuff5;
}
#Override public int hashCode() {
return mID;
}
#Override public boolean equals(final Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final Player other = (Player) obj;
if (mID != other.mID) return false;
return true;
}
#Override public String toString() {
return "Player[" + mID + "]";
}
public void incMatches() {
++mMatches;
}
public int getMatches() {
return mMatches;
}
public boolean canPlayAnotherMatch() {
return getMatches() < mParentLogic.mPairingsAllowed;
}
}
static class Pairing {
public final Player mPlayer1;
public final Player mPlayer2;
public Pairing(final Player pPlayer1, final Player pPlayer2) {
if (pPlayer1.mID < pPlayer2.mID) {
mPlayer1 = pPlayer1;
mPlayer2 = pPlayer2;
} else {
mPlayer1 = pPlayer2;
mPlayer2 = pPlayer1;
}
}
#Override public String toString() {
return mPlayer1 + "+" + mPlayer2;
}
#Override public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + mPlayer1.mID;
result = prime * result + mPlayer2.mID;
return result;
}
#Override public boolean equals(final Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final Pairing other = (Pairing) obj;
if (mPlayer1 != other.mPlayer1) return false;
if (mPlayer2 != other.mPlayer2) return false;
return true;
}
}
static class PartnerMap {
private final HashMap<Player, ArrayList<Player>> mMap = new HashMap<>();
public PartnerMap(final Iterable<Player> pPlayers) {
for (final Player player : pPlayers) {
final ArrayList<Player> partners = new ArrayList<>();
for (final Player partner : pPlayers) {
if (player != partner) partners.add(partner);
}
mMap.put(player, partners);
}
}
public Player getPartner(final Player pPlayer) {
final ArrayList<Player> possiblePartners = mMap.get(pPlayer);
if (possiblePartners.size() < 1) throw new NotEnoughPartnersException(pPlayer);
return possiblePartners.get((int) (Math.random() * possiblePartners.size()));
}
public void removePartners(final Player pPlayer, final Player pPartner) {
System.out.println("\t\tBadPairingStuff5.PartnerMap.removePartners(" + pPlayer + ", " + pPartner + ")");
System.out.println("\t\t\tRemoving for " + pPlayer);
System.out.println("\t\t\t\tBEFORE: " + toString(mMap.get(pPlayer)));
mMap.get(pPlayer).remove(pPartner);
System.out.println("\t\t\t\tAFTER: " + toString(mMap.get(pPlayer)));
System.out.println("\t\t\tRemoving for " + pPartner);
System.out.println("\t\t\t\tBEFORE: " + toString(mMap.get(pPartner)));
mMap.get(pPartner).remove(pPlayer);
System.out.println("\t\t\t\tAFTER: " + toString(mMap.get(pPartner)));
}
static String toString(final Iterable<Player> pPlayers) {
final StringBuilder sb = new StringBuilder();
sb.append("[");
for (final Player player : pPlayers) {
sb.append(player.mID + " ");
}
sb.append("]");
return sb.toString();
}
public void removePlayerCompletely(final Player pPlayer) {
System.out.println("\t\t\tBadPairingStuff5.PartnerMap.removePlayerCompletely(" + pPlayer + ")");
for (final ArrayList<Player> partnerMap : mMap.values()) {
partnerMap.remove(pPlayer);
}
mMap.get(pPlayer).clear();
}
public void print() {
System.out.println("Partner Map");
for (final Entry<Player, ArrayList<Player>> e : mMap.entrySet()) {
System.out.println("\t" + e.getKey());
for (final Player v : e.getValue()) {
System.out.println("\t\t" + v);
}
}
}
}
public static class NotEnoughPartnersException extends IllegalStateException {
private static final long serialVersionUID = -7249807214069096317L;
private final Player mPlayer;
public NotEnoughPartnersException(final Player pPlayer) {
super("Not enough partners available for " + pPlayer + "!");
mPlayer = pPlayer;
}
public Player getPlayer() {
return mPlayer;
}
}
static class PairingResult {
public final ArrayList<Pairing> mCreatedPairings;
public final ArrayList<Exception> mExceptions;
public PairingResult(final ArrayList<Pairing> pCreatedPairings, final ArrayList<Exception> pExceptions) {
mCreatedPairings = pCreatedPairings;
mExceptions = pExceptions;
}
public boolean isValid() {
return mExceptions.size() < 1;
}
}
public static void main(final String[] args) {
final int players = 10;
final int pairingsAllowed = 4;
final PairingResult result = new BadPairingStuff6(players, pairingsAllowed).createPairings();
System.out.println("All pairings:");
final HashMap<Long, Long> playCounter = new HashMap<>();
for (final Pairing p : result.mCreatedPairings) {
System.out.println("\t" + p);
{
final Long oldCount = playCounter.get(Long.valueOf(p.mPlayer1.mID));
playCounter.put(Long.valueOf(p.mPlayer1.mID), Long.valueOf(oldCount == null ? 1 : (oldCount.longValue() + 1)));
}
{
final Long oldCount = playCounter.get(Long.valueOf(p.mPlayer2.mID));
playCounter.put(Long.valueOf(p.mPlayer2.mID), Long.valueOf(oldCount == null ? 1 : (oldCount.longValue() + 1)));
}
}
System.out.println("Pairings per Player: ");
for (final Entry<Long, Long> e : playCounter.entrySet()) {
System.out.println("\t" + e.getKey() + " -> " + e.getValue());
}
System.out.println("Exceptions:");
System.out.flush();
sleep();
for (final Exception e : result.mExceptions) {
e.printStackTrace();
}
System.err.flush();
sleep();
System.out.println("Valid result: " + result.isValid());
System.out.println("All done.");
}
/*
* OBJECT
*/
final int mPairingsAllowed;
private final ArrayList<Player> mPlayers = new ArrayList<>();
public BadPairingStuff6(final int pPlayersCount, final int pPairingsAllowed) {
mPairingsAllowed = pPairingsAllowed;
// create players
for (int i = 0; i < pPlayersCount; i++) {
mPlayers.add(new Player(i, this));
}
}
public PairingResult createPairings() {
final ArrayList<Pairing> createdPairings = new ArrayList<>();
final ArrayList<Exception> exceptions = new ArrayList<>();
final PartnerMap possiblePairings = new PartnerMap(mPlayers);
final HashSet<Player> playersToHandle = new HashSet<>(mPlayers);
while (!playersToHandle.isEmpty()) {
final ArrayList<Player> removePlayersPerRound = new ArrayList<>();
for (final Player player : playersToHandle) {
if (!player.canPlayAnotherMatch()) {
possiblePairings.removePlayerCompletely(player);
removePlayersPerRound.add(player);
continue;
}
try {
System.out.println("Creating matches for " + player + " (" + player.getMatches() + ")");
final Player partner = possiblePairings.getPartner(player);
if (!partner.canPlayAnotherMatch()) continue;
final Pairing newPairing = new Pairing(player, partner);
if (createdPairings.contains(newPairing)) System.out.println("WARNING! Double hit for " + newPairing);
createdPairings.add(newPairing);
possiblePairings.removePartners(player, partner);
player.incMatches();
partner.incMatches();
System.out.println("\tMatched with " + partner);
if (!partner.canPlayAnotherMatch()) {
possiblePairings.removePlayerCompletely(partner);
removePlayersPerRound.add(partner);
}
} catch (final NotEnoughPartnersException e) {
// the flushes and sleeps are only a cheap shot to keep System.out and System.err outputs in somewhat chronological order.
// this is for proof/debug/answer only, and should NOT be used in production!
System.out.flush();
sleep();
e.printStackTrace();
// throw e; // if you want to abort early
removePlayersPerRound.add(e.getPlayer());
exceptions.add(e);
System.err.flush();
sleep();
}
}
playersToHandle.removeAll(removePlayersPerRound);
}
possiblePairings.print();
return new PairingResult(createdPairings, exceptions);
}
// the sleeps are only a cheap shot to keep System.out and System.err outputs in somewhat chronological order.
// this is for proof/answer only, and should NOT be used in production
static void sleep(final long pMilliSec) {
try {
Thread.sleep(pMilliSec);
} catch (final InterruptedException e1) { /* */ }
}
static void sleep() {
sleep(100);
}
}
I use lots of inner static classes. This is for demonstration purposes only.
If you want to actually use those classes, put each of them into its separate file (remove the "static class", and add a "public class" where it's missing).
Also note that this complexity is needed for random assignments. If the algorithm could always churn out the same combinations, it would be about 1/10th of the code.
Does anyone has any idea on how can I get the value of a function that indicates if there are any empty parking spot on the block or not.
I am using a Queue, and I tried the function nFree() and spaceIndex(), but I get that the two functions are not defined for the type
Hope i understood you question, below is the code that may return all the parking empty spot.
public class Parking {
static int parkingSize = 10;
static Object[] object = new Object[parkingSize];
public static void main(String[] args) {
add("java", 10);
System.out.println(checkEmptyParkingSpot());
emptyParkingSpot(10);
System.out.println(checkEmptyParkingSpot());
}
// add the object in specicif location
public static void add(String info, int position) {
// if the position does not exist an erro will be thow
if (position > object.length ) {
throw new RuntimeException("The possition indicated does not exist in the park");
}
if (object[position - 1] != null) {
throw new RuntimeException("The possition is ocupied");
}
object[position - 1] = info;
}
// to remove an object from the park and free the space
public static void emptyParkingSpot(int position) {
if (position > object.length ) {
throw new RuntimeException("The possition indicated does not exist in the park");
}
if (object[position - 1] == null) {
throw new RuntimeException("The possition isalready empty");
}
object[position - 1] = null;
}
// lists the empty spot
public static String checkEmptyParkingSpot() {
String emptySpace = "".trim();
for (int i = 0; i < object.length; i++) {
// list the empty space
if (object[i] == null) {
emptySpace = emptySpace + (i + 1) + "\n";
}
}
// if there is no space the message will be park full
if (emptySpace.isEmpty()) {
emptySpace = "Park is Full";
}
return emptySpace;
}
}
I'm working on a project for a potential internship to take a String input of bowling scores and add them up to a final score. I'm having difficult passing one of my tests and was wondering if you could help me figure out my fault.
The test that is not working is isNinetySix and it is giving me a result of 98 instead. Please help!
public class Game {
private int roll = 0;
private int[] rolls = new int[21];
public void rolls(String scoreCard) {
for (int i=0; i< scoreCard.length(); i++) {
if (scoreCard.charAt(i) == 'X') {
rolls[roll++] = 10;
} else if (scoreCard.charAt(i) == '/') {
rolls[roll++] = 10;
} else if (scoreCard.charAt(i) == '-') {
} else {
int x = scoreCard.charAt(i);
rolls[roll++] = x - '0';
}
}
}
public int score() {
int score = 0;
int cursor = 0;
for (int frame = 0; frame < 10; frame++) {
if (isStrike(cursor)) {
score += 10 + rolls[cursor+1] + rolls[cursor+2];
cursor ++;
} else if (isSpare(cursor)) {
score += 10 + rolls[cursor+2];
cursor += 2;
} else {
score += rolls[cursor] + rolls[cursor+1];
cursor += 2;
}
}
return score;
}
private boolean isStrike(int cursor) {
return rolls[cursor] == 10;
}
private boolean isSpare(int cursor) {
return rolls[cursor] + rolls[cursor+1] == 10;
}
//Print scores for each frame
public void printFrameScore(int[] frame) {
for (int i = 1; i < frame.length; i++) {
System.out.println(i + ": " + frame[i]);
}
}
public void displayRolls() {
for (int i = 0; i < rolls.length; i++) {
System.out.print(rolls[i] + ", ");
}
}
}
Tests
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.is;
import org.junit.Before;
import org.junit.Test;
public class GameTest {
private Game game;
#Before
public void setUp(){
game = new Game();
}
#Test
public void isPerfect() {
game.rolls("X-X-X-X-X-X-X-X-X-X-XX");
assertThat(game.score(), is(300));
}
#Test
public void isGutter() {
game.rolls("00-00-00-00-00-00-00-00-00-00");
assertThat(game.score(), is(0));
}
#Test
public void isNinety() {
game.rolls("45-54-36-27-09-63-81-18-90-72");
assertThat(game.score(), is(90));
}
#Test
public void isOneFifty(){
game.rolls("5/-5/-5/-5/-5/-5/-5/-5/-5/-5/-5");
assertThat(game.score(), is(150));
}
#Test
public void isNinetySix() {
game.rolls("45-54-36-27-09-63-81-18-90-7/-5");
assertThat(game.score(), is(96));
}
}
The problem here seems to be that your isSpare() function never returns true because you assigned each / a value of 10. The result of the addition of the two rolls in a frame with a spare was more than 10. If I were you I would try to clean up the assignment of / to actually be 10 - prev_role_score. This would be cleaner than making isSpare() check for greater than 10. There are other ways to clean up the code to, you could try to refactor some to impress whoever you submit to.
} else if (scoreCard.charAt(i) == '/') {
int diff = 10 - rolls[roll - 1];
rolls[roll++] = diff;
}
Your code is failing in the below block (after your 9th frame, you're at a score of 81). You're code is looking at the index that contains the value 7 and the / which you represent as 10, thereby giving you 17 rather than 10 for the spare.
...
} else {
score += rolls[cursor] + rolls[cursor+1];
cursor += 2;
}
...
So, if I were making suggestions, and I'm not sure what the expectations are for your project, I would tell you to think about easier ways to traverse your string by splitting, searching, then adding. Below is a quick example:
public void rolls(String scorecard) {
String [] framesets = scorecard.split("-");
//hunt for special cases like spare and strikes
//do work to hold your scores
}
I am trying to write a code that changes a value by either -1 or +1 depending on a random chance. It is basically a person moving through blocks. He starts from 6 and if he ends up in 1 he wins but if he ends up in 11 he loses. The final output would look something like this:
Here we go again... time for a walk!
Walked 37 blocks, and
Landed at Home
Here we go again... time for a walk!
Walked 19 blocks, and
Landed in JAIL
Here we go again... time for a walk!
Walked 13 blocks, and
Landed in JAIL
Here we go again... time for a walk!
Walked 25 blocks, and
Landed in JAIL
I have written the following code:
public class Drunk {
public int street;
public double move;
public int i;
public boolean jail;
public static void drunkWalk() {
do {
street = 6;
move = Math.random();
i++;
if (move > 0.5) {
street++;
} else {
street--;
}
} while (street != 1 && street != 11);
if ( street == 1) {
jail = false;
} else {
jail = true;
}
for (; ; ) { --- } //This is the problem. It treats it as a method.
//How can I fix this?
}
}
How about somethink like:
public static void main(String args[])
{
Drunk drunk = new Drunk();
while (true)
{
DrunkResult result = drunk.drunkWalkToJail();
System.out.println("Walked " + result.getSteps() + " blocks, and Landed at " + (result.isInJail() ? "Jail":"Home"));
}
}
public DrunkResult drunkWalkToJail()
{
int street;
int stepCount = 0;
do
{
street = 6;
double move = Math.random();
stepCount++;
if (move > 0.5)
{
street++;
}
else
{
street--;
}
}
while (street != 1 && street != 11);
return new DrunkResult(street == 11, stepCount);
}
and
public class DrunkResult
{
boolean jail = false;
int stepCount = 0;
public DrunkResult(boolean jail, int stepCount)
{
this.jail = jail;
this.stepCount = stepCount;
}
public boolean isInJail()
{
return jail;
}
public int getSteps()
{
return stepCount;
}
}
You can do walks in parallel (a group of drunk people) and process the results independent.
I'm trying to make a 2d array of an object in java. This object in java has several private variables and methods in it, but won't work. Can someone tell me why and is there a way I can fix this?
This is the exeception I keep getting for each line of code where I try to initialize and iterate through my 2d object.
"Exception in thread "main" java.lang.NullPointerException
at wumpusworld.WumpusWorldGame.main(WumpusWorldGame.java:50)
Java Result: 1"
Here is my main class:
public class WumpusWorldGame {
class Agent {
private boolean safe;
private boolean stench;
private boolean breeze;
public Agent() {
safe = false;
stench = false;
breeze = false;
}
}
/**
* #param args
* the command line arguments
* #throws java.lang.Exception
*/
public static void main(String [] args) {
// WumpusFrame blah =new WumpusFrame();
// blah.setVisible(true);
Scanner input = new Scanner(System.in);
int agentpts = 0;
System.out.println("Welcome to Wumpus World!\n ******************************************** \n");
//ArrayList<ArrayList<WumpusWorld>> woah = new ArrayList<ArrayList<WumpusWorld>>();
for (int i = 0 ; i < 5 ; i++) {
WumpusWorldObject [] [] woah = new WumpusWorldObject [5] [5];
System.out.println( "*********************************\n Please enter the exact coordinates of the wumpus (r and c).");
int wumpusR = input.nextInt();
int wumpusC = input.nextInt();
woah[wumpusR][wumpusC].setPoints(-3000);
woah[wumpusR][wumpusC].setWumpus();
if ((wumpusR <= 5 || wumpusC <= 5) && (wumpusR >= 0 || wumpusC >= 0)) {
woah[wumpusR][wumpusC].setStench();
}
if (wumpusC != 0) {
woah[wumpusR][wumpusC - 1].getStench();
}
if (wumpusR != 0) {
woah[wumpusR - 1][wumpusC].setStench();
}
if (wumpusC != 4) {
woah[wumpusR][wumpusC + 1].setStench();
}
if (wumpusR != 4) {
woah[wumpusR + 1][wumpusC].setStench();
}
System.out.println( "**************************************\n Please enter the exact coordinates of the Gold(r and c).");
int goldR = input.nextInt();
int goldC = input.nextInt();
woah[goldR][goldC].setGold();
System.out.println("***************************************\n How many pits would you like in your wumpus world?");
int numPits = input.nextInt();
for (int k = 0 ; k < numPits ; k++) {
System.out.println("Enter the row location of the pit");
int r = input.nextInt();
System.out.println("Enter the column location of the pit");
int c = input.nextInt();
woah[r][c].setPit();
if ((r <= 4 || c <= 4) && (r >= 0 || c >= 0)) {
woah[r][c].setBreeze();
}
if (c != 0) {
woah[r][c - 1].setBreeze();
}
if (r != 0) {
woah[r - 1][c].setBreeze();
}
if (c != 4) {
woah[r][c + 1].setBreeze();
}
if (r != 4) {
woah[r + 1][c].setBreeze();
}
}
for (int x = 0 ; x < 4 ; x++) {
int j = 0;
while (j < 4) {
agentpts = agentpts + woah[x][j].getPoints();
Agent [] [] k = new Agent [4] [4];
if (woah[x][j].getWumpus() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("You just got ate by the wumpus!!! THE HORROR!! Your score is " + agentpts);
}
if (woah[x][j].getStench() == true) {
k[x][j].stench = true;
System.out.println("You smell something funny... smells like old person.");
}
if (woah[x][j].getBreeze() == true) {
k[x][j].breeze = true;
System.out.println("You hear a breeze. yeah");
}
if (woah[x][j].getPit() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH! you dumb bith, your dead now.");
}
// if breeze or stench, if breeze and stench, if nothing, etc then move.
k[x][j].safe = true;
// if(k[i][j].isSafe()!=true){
// } else { }
}
}
}
}
}
Here is my class object that I'm trying to implement:
package wumpusworld;
/**
*
* #author Jacob
*/
public class WumpusWorldObject {
private boolean stench;
private boolean breeze;
private boolean pit;
private boolean wumpus;
private boolean gold;
private int points;
private boolean safe;
public WumpusWorldObject(){
}
public boolean getPit() {
return pit;
}
public void setPit() {
this.pit = true;
}
public boolean getWumpus() {
return wumpus;
}
public void setWumpus() {
this.wumpus = true;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public boolean getStench() {
return stench;
}
public void setStench() {
this.stench = true;
}
public boolean getBreeze() {
return breeze;
}
public void setBreeze() {
this.breeze = true;
}
public boolean getSafe() {
return safe;
}
public void setSafe() {
this.safe = true;
}
public void setGold(){
this.gold=true;
}
}
Creating array doesn't mean it will be automatically filled with new instances of your class. There are many reasons for that, like
which constructor should be used
what data should be passed to this constructor.
This kind of decisions shouldn't be made by compiler, but by programmer, so you need to invoke constructor explicitly.
After creating array iterate over it and fill it with new instances of your class.
for (int i=0; i<yourArray.length; i++)
for (int j=0; j<yourArray[i].length; j++)
yourArray[i][j] = new ...//here you should use constructor
AClass[][] obj = new AClass[50][50];
is not enough, you have to create instances of them like
obj[i][j] = new AClass(...);
In your code the line
woah[wumpusR][wumpusC].setPoints(-3000);
must be after
woah[wumpusR][wumpusC] = new WumpusWorldObject();
.