package hw1;
public class CyrideBus {
public static final int BUS_GARAGE = -1;
private int currentCapacity;
private int numStops;
private int numPassengers;
private int currentStop;
private boolean inService;
keeps track of bus stops
public CyrideBus(int givenMaxCapacity, int givenNumStops) {
currentCapacity = givenMaxCapacity;
numStops = givenNumStops;
currentStop = BUS_GARAGE;
inService = true;
}
public int getCurrentCapacity() {
return currentCapacity;
}
public int getCurrentStop() {
return currentStop;
}
public int getNumPassengers() {
return numPassengers;
}
public int getTotalRiders() {
return numPassengers + currentCapacity+ 1;
}
public boolean isInService() {
return inService;
}
public void nextStop (int peopleOff, int peopleOn) {
currentStop= (currentStop + 1)% numStops;
peopleOff = Math.max(0, peopleOff);
peopleOn = Math.max(0, peopleOn);
numPassengers -= Math.min(peopleOff, numPassengers);
int requiredCapacity = numPassengers + peopleOn;
numPassengers = Math.min(requiredCapacity, currentCapacity);
}
public void placeInService() {
inService = true;
}
public void removeFromService() {
inService = false;
}
}
trying to make a bus route program that keeps track of people on the bus at each stop. this bus route also has a bus garage. The number one issue I am having right now is that I can not get the right amount of people on my bus keep getting
for new bus with three stops, after nextStop() six times, current stop should be 2, expected 2 but was 5
for new bus with seven stops, fter nextStop() 137 times, current stop should be 3. expected 3 but was 136
and so on
Related
i'm learning junit and problem have occured at the beginning.
At the start i want to initialize objected which will be used in tests.
But #BeforeClass doesn't do that.
public class InitTests {
private Croupier croupier;
private Player p1, p2;
#BeforeClass
public void setUp() {
croupier = new Croupier();
croupier.PlayersInit(5, 100);
p1 = croupier.getPlayer(0);
p2 = croupier.getPlayer(1);
} #Test // p1,p2, croupier = null, have no idea why.
public void PlayerInitTest() {
assertEquals(0, p1.getId());
assertEquals(1, p2.getId());
}}
Other classes :
public class Player {
private ArrayList<Card> hand = new ArrayList<>();
private int coins = 0;
private static int playerNumber = 0;
private int id;
private boolean inGame = true;
public Player(int coins) {
this.coins = coins;
id = ++playerNumber;
}
public int addCoins(int amount) {
coins+=amount;
return amount;
}
public int substractCoins(int substract) {
coins-=substract;
return substract;
}
public int getCoins() {
return coins;
}
public int getId() {
return id;
}
public boolean isInGame() {
return inGame;
}
public void setGameStatus(boolean status) {
if(getCoins() < 0 )
inGame = false;
else
inGame = status;
}
public void clearHand() {
hand.clear();
}}
public class Croupier {
private String name;
private ArrayList<Card> deck = new ArrayList<>();
private ArrayList<Player> allPlayers = new ArrayList<>();
private ArrayList<Player> actual = new ArrayList<>();
private int stack = 0;
private int bigPlayerStack = 0;
private int smallPlayerStack = 0;
public Croupier() {
System.out.println("tutej.");
}
public Croupier CroupierInit() {
// static
PlayersInit(5, 100);
return new Croupier();
}
private void CreateDeck() {
String[] suits = { "hearts", "spades", "diamonds", "clubs" };
for (int i = 0; i < suits.length; i++)
for (int j = 2; j < 15; j++)
deck.add(new Card(j, suits[i]));
}
private void DeckShuffle() {
Collections.shuffle(deck);
}
public boolean TurnPlayed() {
if (!preparedGame())
return false;
return true;
}
public void StartGame() {
preparedGame();
System.out.println("Game ended.");
}
public boolean preparedGame() {
clearTable();
if(!setActualPlayers())
return false;
setSmallAndBig();
takeFromSmallAndBig();
CreateDeck();
DeckShuffle();
return true;
}
// set players who are playing
public boolean setActualPlayers() {
for (Player e : allPlayers)
if (e.isInGame())
actual.add(e);
if (actual.size() < 2)
return false;
return true;
}
// take coisn from small and big blind
public void takeFromSmallAndBig() {
stack += actual.get(bigPlayerStack).substractCoins(20);
stack += actual.get(smallPlayerStack).substractCoins(10);
}
// set who has small or big blind
public void setSmallAndBig() {
bigPlayerStack++;
if (bigPlayerStack > actual.size())
bigPlayerStack = 0;
smallPlayerStack = bigPlayerStack - 1;
if(smallPlayerStack < 0 )
smallPlayerStack = actual.size() -1;
}
// clear table before game
public void clearTable() {
actual.clear();
for (Player e : allPlayers)
e.clearHand();
}
public void PlayersInit(int numberOfPlayers, int coins) {
for (int i = 0; i < numberOfPlayers; i++) {
allPlayers.add(new Player(coins));
}
}
public Player getPlayer(int index) {
return allPlayers.get(index);
}}
I'm sure these tests are correct because when i put setUp method ( code from that method) inside #Test it just works.
I hope it's a simple syntax problem which as a beginner can't set at the moment.
Greetings.
Your test class uses a mix of JUnit 4 and 5 annotations.
The JUnit 5 API is not compatible with prior versions of the library, and defines a new set of annotations. Assuming your test executes, you are probably using a JUnit 5 launcher and therefore need to use annotations from org.junit.jupiter.api package.
If you wish to use JUnit 5
Try #org.junit.jupiter.api.BeforeEach or#org.junit.jupiter.api.BeforeAll, with a static method for the latter. Their semantic is defined here.
If you wish to use JUnit 4
You need revert all the annotations to JUnit 4 - which implies using org.junit.Test.
Your JUnit launcher needs to be configured for JUnit 4.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So I'm working on an assignment that is trying to output the energy consumption of appliances within a house. I have created an Appliance called ElectricCooker and an Appliance called ElectricShower. They both have exactly the same code apart from different variable names yet some how produce different outputs.
Here is the relevant code: (Sorry about the amount of code, this reproduces the program)
ElectricCooker
public class ElectricCooker extends Appliance
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
#Override
public int currentState()
{
if (varPass == 0)
return isOff;
else
{
return isOn;
}
//returns isOn;
}
#Override
public void useTime(int defaultTime)
{
defaultTime = 15;
incrementTime = 4;
}
public void cook()
{
//add code
}
#Override
public void timePasses()
{
if(varPass == isOff)
varPass = 0;
else
{
ElectricMeter.getInstance().incrementConsumed(electricityUse);
ElectricMeter.getInstance().incrementConsumed(5);
int getCookerConsumed = ElectricMeter.getInstance().getElectricityUsed();
System.out.println("Electric cooker electricity consumption = " + getCookerConsumed);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 5 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 0 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
ElectricShower
public class ElectricShower extends Appliance
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
#Override
public int currentState()
{
if (varPass == 0)
return isOff;
else
{
return isOn;
}
//returns isOn;
}
#Override
public void useTime(int defaultTime)
{
defaultTime = 15;
incrementTime = 4;
}
#Override
public void timePasses()
{
if(varPass == isOff)
varPass = 0;
else
{
ElectricMeter.getInstance().incrementConsumed(electricityUse);
ElectricMeter.getInstance().incrementConsumed(5);
int getShowerConsumed = ElectricMeter.getInstance().getElectricityUsed();
System.out.println("Electric shower electricity consumption = " + getShowerConsumed);
}
}
ElectricShower(int electricityUse, int gasUse, int waterUse, int timeOn)
{
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 5 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 0 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
Appliance
abstract public class Appliance
{
public int varPass;
public int isOn;
public int isOff;
public int electricityUse, gasUse, waterUse, timeOn;
public abstract void useTime(int defaultTime);
public int currentState()
{
if (varPass == 0)
return isOff;
else
{
return isOn;
}
//returns isOn;
}
public abstract void timePasses();
Appliance(int electricityUse,int gasUse,int waterUse,int timeOn)
{
electricityUse = 0;
gasUse = 0;
waterUse = 0;
timeOn = 0;
}
}
ElectricMeter
public class ElectricMeter
{
ElectricMeter() {}
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() { return instance; }
private int electricityUsed = 0;
public void incrementConsumed(int value)
{
electricityUsed += value;
}
public int getElectricityUsed()
{
return electricityUsed;
}
}
House
import java.util.ArrayList;
public class House
{
ArrayList<Appliance> applianceList = new ArrayList<>();
ElectricShower calleShower = new ElectricShower(1, 1, 1, 1);
ElectricCooker calleCooker = new ElectricCooker(1, 1, 1, 1);
public void addAppliance()
{
applianceList.add(calleShower);
applianceList.add(calleCooker);
}
public void timePasses()
{
calleShower.timePasses();
calleCooker.timePasses();
//this method is called as part of the simulation to trigger a new fifteen minute period
//in the house. When it is called, it will in turn call timePasses() on all the Appliances in the House.
}
}
public class CourseworkTest {
public static void main(String[] args)
{
House callHouse = new House();
callHouse.timePasses();
}
}
Output
Electric shower electricity consumption = 5
Electric cooker electricity consumption = 10
I've been working on this for hours and I just don't understand how the exact same code can somehow produce different results? I don't see how one can be 10 and other 5 when they do the exact same thing and go through the same process. Any help is very much appreciated, thanks.
The ElectricMeter class is a singleton, meaning that one (same) instance will exist throughout the execution of your application.
First, from ElectricShower.timePasses(), you make the following call:
ElectricMeter.getInstance().incrementConsumed(5);
Then, you again make this call from ElectricCooker.timePasses(). Hence, when you output the consumption the second time, it is being reported as 10.
Using a singleton to represent the common shared electric meter for a house seems like a reasonable design decision.
Apologies if this is trivial to most but I just can't figure this issue out!!
I am creating a mock game where I have a start, end, and hops along. There are portals where if you go on a white portal you jump further ahead and there are black ones where you go backwards. I have set up the class as a POJO;
private int totalSize;
private int minDice;
private int maxDice;
private int whitePortalStart;
private int whitePortalEnd;
private int blackPortalStart;
private int blackPortalEnd;
private int startPosition = 1;
private int currentPosition;
public GameObject(){}
public int getTotalSize() {
return totalSize;
}
public void setTotalSize(int totalSize) throws Exception {
if(totalSize <= 0){
throw new Exception("Can't have a total distance of less than or equal to 0");
} else {
this.totalSize = totalSize;
}
}
public int getMinDice() {
return minDice;
}
public void setMinDice(int minDice) throws Exception {
if(minDice <= 0){
throw new Exception("Can't have a min dice value of less than or equal to 0");
} else {
this.minDice = minDice;
}
}
public int getMaxDice() {
return maxDice;
}
public void setMaxDice(int maxDice) throws Exception {
if(getMinDice() > maxDice){
throw new Exception("Cant have minimum dice number greater than the larger dice number");
} else {
this.maxDice = maxDice;
}
}
public int getWhitePortalStart() {
return whitePortalStart;
}
public void setWhitePortalStart(int whitePortalStart) throws Exception {
this.whitePortalStart = whitePortalStart;
}
public int getWhitePortalEnd() {
return whitePortalEnd;
}
public void setWhitePortalEnd(int whitePortalEnd) throws Exception {
this.whitePortalEnd = whitePortalEnd;
}
public int getBlackPortalStart() {
return blackPortalStart;
}
public void setBlackPortalStart(int blackPortalStart) throws Exception {
this.blackPortalStart = blackPortalStart;
}
public int getBlackPortalEnd() {
return blackPortalEnd;
}
public void setBlackPortalEnd(int blackPortalEnd) throws Exception {
this.blackPortalEnd = blackPortalEnd;
}
public GameObject builder(int n) throws Exception {
setTotalSize(n);
return this;
}
public GameObject whitePortal(int m, int o) throws Exception {
setWhitePortalStart(m);
setWhitePortalEnd(o);
return this;
}
public GameObject blackPortal(int o, int m) throws Exception {
setBlackPortalStart(o);
setBlackPortalEnd(m);
return this;
}
public GameObject dice(int i, int j) throws Exception {
setMinDice(i);
setMaxDice(j);
return this;
}
public int rollDice(){
Random random = new Random();
int min = getMinDice();
int max = getMaxDice();
return random.nextInt(max - min + 1) + min;
}
public void build(){
int totalDistance = getTotalSize();
currentPosition = startPosition;
while(currentPosition < totalDistance){
int diceValue = rollDice();
if(currentPosition + diceValue > getTotalSize()){
System.out.println("CurrentPosition : " + (currentPosition + diceValue) + ", is larger than the total size of the road - " + totalSize);
continue;
} else if(currentPosition + diceValue == getWhitePortalStart()){
System.out.println("You landed on a white portal. Advancing from position " + (currentPosition + diceValue) + " to " + getWhitePortalEnd());
currentPosition = getWhitePortalEnd();
} else if(currentPosition + diceValue == getBlackPortalStart()){
System.out.println("You landed on a black portal. Moving from position " + (currentPosition + diceValue) + " to " + getBlackPortalEnd());
currentPosition = getBlackPortalEnd();
} else {
System.out.println("You landed on " + (currentPosition + diceValue));
currentPosition += diceValue;
}
}
}
So in my main method I call the it like create and call this class like;
WorldOfOz oz = new WorldOfOz();
oz.go.builder(30)
.dice(1, 4)
.whitePortal(5, 12)
.blackPortal(13, 2)
.build();
My issue is when I want to add in more than 1 whitePortal/blackPortal
WorldOfOz oz = new WorldOfOz();
oz.go.builder(30)
.dice(1, 4)
.whitePortal(5, 12)
.whitePortal(18, 26)
.blackPortal(13, 2)
.build();
The values 18 - 26 override 5 - 12. How can I set this up so I can have multiple white and black portals?
It seems that your data structure is not enough to solve this problem.
You need to define a collection of whitePortals and a collection of blackPortals. If you do so calling the method whitePortal(5, 12) add a new white portal insted of setting the white portal values of the only white existing portal.
You need to define a class Portal
public class Portal {
private int portalStart;
private int portalEnd;
...
public Portal(int s, int e) {
this.portalStart = s;
this.portalEnd = e;
}
}
Then you can use it in the GameObject as follow:
public GameObject {
List<Portal> whitePortals;
List<Portal> blackPortals;
public GameObject() {
whitePortals = new ArrayList<Portal>();
blackPortals = new ArrayList<Portal>();
}
public GameObject addWhitePortal(int m, int o) throws Exception {
whitePortals.add(new Portal(m, o));
return this;
}
...
// You need to change other methods to follow a different data structure
}
Well, you can use the following approach:
Introduce a new "Portal" type with start/end attributes
Replace white/black portal attributes in your class with lists for white and black portals (or any other type of collection you like)
Replace getWhite/Black methods with access to lists
Refactor whitePortal and blackPortal method to create new instances of a portal object and add them to an appropriate collection
You can, of course, use arrays instead of collections, but that's a bit more cumbersome.
Also, assuming portals are collections, you probably need to add helper methods for operating on those. Depending on what your actual needs are.
public class Portal
{
private int start;
private int end;
public Portal(int start, int end) { ... }
public getStart() {...}
public getEnd() {...}
public setStart(int end) {...}
public setEnd(int start) {...}
}
public class GameObject
{
...
private List<Portal> whitePortals = new ArrayList<Portal>();
private List<Portal> blackPortals = new ArrayList<Portal>();
...
public GameObject whitePortal(int m, int o) throws Exception {
whitePortals.add(new Portal(m, o));
return this;
}
public GameObject blackPortal(int o, int m) throws Exception {
blackPortals.add(new Portal(m, o));
return this;
}
...
}
I have to create an application which simulates concurrent threads. The "server" creates a number of "threads" and stores them in a queue. Each "thread" has defined a time to finish his execution. The server polls each "thread" from the queue to do his job for 10 ms. If the thread has finished his job, it is removed from the queue. If not, it is added at the end of the queue. I used for this application PriorityQueue. The problem is that the code i wrote is not giving the expected output; a "thread" is executed until his execution time ends.
How can I solve this problem?
SimulatedThread class
public class SimulatedThread {
private int executionTime;
private Integer id;
private int executedTime;
private boolean finished;
public SimulatedThread(){
executedTime = 0;
executionTime = 0;
setFinished(false);
}
//getters and setters
}
Server class
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Random;
public class Server {
final int TIME = 10;
final int TH_NO = 10;
//priority
final int MIN_P = 1;
final int MAX_P = 100;
//execution time
final int MIN_E = 10;
final int MAX_E = 100;
private PriorityQueue<SimulatedThread> activeThreads;
public Server() {
Comparator<SimulatedThread> comparator = new SimulatedThreadComparator();
activeThreads = new PriorityQueue<SimulatedThread>(10,comparator);
}
public void createThreads(){
for( int i = 0; i < TH_NO; i++){
SimulatedThread th = new SimulatedThread();
th.setExecutionTime(generator(MAX_E, MIN_E));
th.setId(generator(MAX_P,MIN_P));
System.out.println("New thread has been created");
System.out.println(th.toString());
activeThreads.add(th);
}
}
public void executeThreads(){
while(!activeThreads.isEmpty()){
SimulatedThread th = activeThreads.poll();
if(!th.isFinished()){
try {
Thread.sleep(TIME);
th.setExecutedTime(th.getExecutedTime() + TIME);
System.out.println(th.toString());
if((th.getExecutionTime() - th.getExecutedTime()) <= 0 ){
th.setFinished(true);
} else{
activeThreads.add(th);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
activeThreads.removeAll(activeThreads);
}
private int generator(int max, int min){
Random rand = new Random();
return rand.nextInt((max - min) + 1) - min;
}
public static void main(String[] args){
Server s = new Server();
s.createThreads();
s.executeThreads();
}
EDIT
SimulatedThreadComparator class
import java.util.Comparator;
public class SimulatedThreadComparator implements Comparator<SimulatedThread> {
#Override
public int compare(SimulatedThread o1, SimulatedThread o2) {
return o1.getId().compareTo(o2.getId());
}
}
That explains it: since the priority is the ID, the last thread that was activated will return to the head of the queue, and be the next activated, until it's finished.
Perhaps you should compare the executed time instead of the ID?
I'm doing an assignment for my computer science class.
I've done quite a bit of the assignment, but I'm having a little bit of trouble pulling the individual variables from the classes. We are just getting into classes and objects and this is our first assignment regarding them so I don't completely understand all of it. So far I've been able to print out the teams, but I haven't been able to pull the individual wins, losses, OTL and OTW so that I can compute whether or not each individual team is a winning team.
What I have done so far is create a class called winningRecord and getPoints, which returns a boolean deciding whether it's a winning team or not. (The formula for a winning team is if the points are > Games Played * 1.5 (as that is an even record).
I don't know how to pull the stats, as it has to be written in the HockeyTeam class. I have set it up so that the constructor sets the variables publicly so that the can be accessed, but as far as accessing them, I'm stumped.
As far as storing them once I am able to access them, would I just make a parallel method that has the points for each team, with just one digit assigned to each bin?
Here is all of the code, thanks for looking.
public class A1Q2fixed {
public static void main(String[] parms) { // main method
processHockeyTeams();
}
/*****************************/
public static void processHockeyTeams() { // processing method
boolean[] winningRecord;
HockeyTeam[] hockeyTeams;
hockeyTeams = createTeams();
printTeams(hockeyTeams);
System.out.print("*********************\n");
printWinningTeams();
winningRecord = HockeyTeam.winningRecord(hockeyTeams);
// printWinningTeams(hockeyTeams);
}
/*********************************/
public static void printTeams(HockeyTeam[] hockeyTeams) {
for (int i = 0; i < hockeyTeams.length; i++) {
System.out.println(hockeyTeams[i]);
}
}
public static void printWinningTeams() {
}
public static HockeyTeam[] createTeams() {
HockeyTeam[] teams;
HockeyTeam team;
int count;
teams = new HockeyTeam[HockeyTeams.getNumberTeams()];
team = HockeyTeams.getTeam();
for (count = 0; (count < teams.length) && (team != null); count++) {
teams[count] = team;
team = HockeyTeams.getTeam();
}
return teams;
}
}
/* hockey team class *******/
class HockeyTeam {
public String name;
public int wins;
public int otw;
public int otl;
public int losses;
public HockeyTeam(String name, int wins, int otw, int otl, int losses) {
this.name = name;
this.wins = wins;
this.otw = otw;
this.otl = otl;
this.losses = losses;
}
public String toString() {
System.out.println(name);
return " W:" + wins + " OTW:" + otw + " OTL:" + otl + " L:" + losses;
}
public static boolean[] winningRecord(HockeyTeam[] hockeyTeam) {
boolean array[] = new boolean[hockeyTeam.length];
String name;
int wins;
int otw;
int otl;
int losses;
for (int i = 0; i < hockeyTeam.length; i++) {
System.out.println(HockeyTeam.name);
}
return array;
}
public static int getPoints() {
int points = 0;
return points;
}
}
/* hockey teams class *******************/
class HockeyTeams {
private static int count = 0;
private static HockeyTeam[] hockeyTeams = {
new HockeyTeam("Canada", 5, 3, 0, 0),
new HockeyTeam("Russia", 5, 1, 1, 2),
new HockeyTeam("Finland", 3, 2, 1, 3),
new HockeyTeam("Sweden", 4, 1, 1, 4),
new HockeyTeam("USA", 1, 2, 2, 3), };
public static int getNumberTeams() {
return hockeyTeams.length;
}
public static HockeyTeam getTeam() {
HockeyTeam hockeyTeam;
hockeyTeam = null;
if (count < hockeyTeams.length) {
hockeyTeam = hockeyTeams[count];
count++;
}
return hockeyTeam;
}
}
Thanks,
Matt.
Sorry but I was only able to understand only a part of your question,from what I understood it seems you are not able to access individual wins, losses, OTL and OTW. I hope this answers your question if not please clarify a bit
To access OTL,OTW have a loop as below:
public class A1Q2fixed
{
public static void main(String[] parms) // main method
{
processHockeyTeams();
}
/*****************************/
public static void processHockeyTeams() // processing method
{
boolean[] winningRecord;
HockeyTeam[] hockeyTeams;
hockeyTeams = createTeams();
printTeams(hockeyTeams);
System.out.print("*********************\n");
printWinningTeams();
winningRecord = HockeyTeam.winningRecord(hockeyTeams);
for(HockeyTeam h:hockeyTeams)
{
System.out.println(h.losses);//To access and print losses
System.out.println(h.otw);//To access and print otw
System.out.println(h.otl);//To access and print otl
}
// printWinningTeams(hockeyTeams);
}
/*********************************/
public static void printTeams(HockeyTeam[] hockeyTeams)
{
for (int i = 0; i < hockeyTeams.length; i++)
{
System.out.println(hockeyTeams[i]);
}
}
public static void printWinningTeams()
{
}
public static HockeyTeam[] createTeams()
{
HockeyTeam[] teams;
HockeyTeam team;
int count;
teams = new HockeyTeam[HockeyTeams.getNumberTeams()];
team = HockeyTeams.getTeam();
for (count=0; (count<teams.length) && (team!=null); count++)
{
teams[count] = team;
team = HockeyTeams.getTeam();
}
return teams;
}
}
Also declare name as Static in HockeyTeam