#Before/#BeforeClass seems not working, objects indicates on null - java

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.

Related

Why is this getter functions only returning the initial value

I'm learning object-oriented programming and started learning about inheritance. The assignment my teacher gave me was to make a counter object with 6 "buttons": Increment, Decrement, Reset, AddMemory, ResetMemory, and Quit. It is fairly straight-forward what each button does.
The requirements are that I have to use the JOptionPane command, I have to make a Counter class with a counter attribute, increment, decrement, reset, and quit methods, I have to make a MemoryCounter class with a memory attribute, restMemory, and addMemory method. I also have to make a MemoryCounterConsoleMenu class which makes the input box from the JOptionPane command and executes the appropriate method. The final thing I have to do is make a MemoryCounterTest class that brings the MemoryCounterConsoleMenu and MemoryCounter classes together
So I did all that and here it is:
The first one is the Counter class
public class Counter
{
private int counter = 0;
public void increment()
{
setCounter(getCounter() + 1);
}
public void decrement()
{
setCounter(getCounter() - 1);
}
public void reset()
{
setCounter(0);
}
public void setCounter(int counter) {
this.counter = counter;
}
public int getCounter() {
return counter;
}
}
This is the MemoryCounter class
public class MemoryCounter extends Counter
{
private int memory = 0;
public void resetMem()
{
setMemory(0);
}
public void addMem()
{
setMemory(getCounter());
}
public void setMemory(int memory)
{
this.memory = memory;
}
public int getMemory()
{
return memory;
}
}
Next is the MemoryConsoleMenu
public class MemoryCounterConsoleMenu
{
static MemoryCounter memCounter = new MemoryCounter();
static Counter counter = new Counter();
public static int console()
{
System.out.println(memCounter.getMemory());
Object[] options = {"Reset Mem", "Add Mem", "Increment", "Decrement", "Reset", "Quit" };
int objectIndex = JOptionPane.showOptionDialog(null, "Counter = " + counter.getCounter() + "Memory = "
+ memCounter.getMemory(), "MemoryCounter",JOptionPane.PLAIN_MESSAGE,
JOptionPane.PLAIN_MESSAGE, null, options, options[5]);
return objectIndex;
}
public static int change(int objectIndex)
{
if(objectIndex == 0)
{
memCounter.resetMem();
return 1;
}
else if(objectIndex == 1)
{
memCounter.addMem();
return 2;
}
else if(objectIndex == 2)
{
counter.increment();
return 3;
}
else if(objectIndex == 3)
{
counter.decrement();
return 4;
}
else if(objectIndex == 4)
{
counter.reset();
return 5;
}
else
{
return 6;
}
}
}
Finally, there is the MemoryCounterTest
public class MemoryCounterTest
{
public static void main(String[] args)
{
MemoryCounterConsoleMenu memoryConsole = new MemoryCounterConsoleMenu();
for(int i = 0; i != 6;)
{
i = memoryConsole.change(memoryConsole.console());
}
}
}
Everything works properly except for the memory value. It stays at a constant zero. I've done some troubleshooting myself and found that the only problem in the code is in the "addMem()" method is the MemoryCounter class particularly the implementation of the "getCounter()" method. It will only return 0 for some reason.
After figuring this out I have made no ground on why the problem is occuring or how to fix it
It stays at 0 because they are two separate counters.
MemoryCounter class extends the Counter class, so you don't need a separate
static Counter counter = new Counter();
Just do everything via memCounter.

How to pass my object into another objects field?

I am trying to fill UCFCourse courseOne in my constructor with a courses[] object in fillWithCourses().UCFCourse courseOne does populate outside of the constructor but will not go into it.
public class UCFSemester<courses> {
private static UCFCourse courseOne;
private static double totalSemesters;
private static double completionTime;
static boolean fillSemester = true;
public UCFSemester(UCFCourse courseOne, UCFCourse[] coursetwo) {
this.courseOne = courseOne;
}
public static UCFCourse getcourseOne() {
return courseOne;
}
public static void setCoursesone(UCFCourse courses) {
courseOne = courses;
}
public static void fillWithCourses(UCFCourse courses[], int l) {
int x = 0;
while (fillSemester) {
for (int n = 0; n < 5; n++) {
if (x != n && courses[x].getCourseLevel() < courses[n].getCourseLevel()) {
setCoursesone(courses[x]);
}
}
fillSemester = false;
}
}
}
Side question.How can I access this all in a non-static way?I need the entire thing to be non-static but no matter what I do I can't get it.Thanks!
You can simply do it by creating a List like this:
public class UCFSemester {
private List<UCFCourse> courseList = new ArrayList<>();
public UCFCourse getCourse(int index) {
return courseList.get(index);
}
public void addCourses(UCFCourse[] courses) {
for(int x = 0; x < courses.length; x++) {
courseList.add(courses[x]);
}
}
}
Here, I'm assuming that you are passing the UCFCourse[] array with all the course details that are there in that particular semester.
addCourses() function will take this array and then add all the corresponding courses to the List.
getCourse() function will return you any particular course from the List (Using Index). You can also modify the search in any way you want.

Stuck in using 2D arrays?

I am not good with arrays.In the below code there are 2 methods which takes the data from two 2D Arrays.The first method COMBINATION is working correctly.But the second Method doesn't.
Am I doing anything wrong in the array Declaration ???
The Below Methods takes the KeyEvent from the Array & perform the Keypress & keyRelease according to the KeyEvents in the array.
For Example :
Combination.UNICODE_COPY, KeyEvent.VK_CONTROL, KeyEvent.VK_C
The above line presses CTRL+C. It performs the Copy Function.
I think that in the Second Method i am passing 3 KeyEvents.Is that a Problem ???
private static final int[][] COMBINATION = {
{
Combination.UNICODE_CUT, KeyEvent.VK_CONTROL, KeyEvent.VK_X
}, {
Combination.UNICODE_COPY, KeyEvent.VK_CONTROL, KeyEvent.VK_C
}, {
Combination.UNICODE_PASTE, KeyEvent.VK_CONTROL, KeyEvent.VK_V
}
};
private static final int[][] COMBINATIONS = {
{
Combinations.UNICODE_TASK, KeyEvent.VK_CONTROL, KeyEvent.VK_ALT, KeyEvent.VK_DELETE
}
};
private void keyboardCombination(Combination action)
{
boolean exception = false;
for (int i = 0; i < COMBINATION.length; i++)
{
if (action.unicode == COMBINATION[i][0])
{
exception = true;
this.application.getRobot().keyPress(COMBINATION[i][1]);
this.application.getRobot().keyPress(COMBINATION[i][2]);
// this.application.getRobot().keyPress(COMBINATION[i][3]);
this.application.getRobot().keyRelease(COMBINATION[i][1]);
this.application.getRobot().keyRelease(COMBINATION[i][2]);
// this.application.getRobot().keyRelease(COMBINATION[i][3]);
break;
}
}
if (!exception)
{
pressUnicode(this.application.getRobot(), action.unicode);
}
}
private void keyboardCombinations(Combinations action)
{
boolean exception = false;
for (int i = 0; i < COMBINATIONS.length; i++)
{
if (action.unicode == COMBINATIONS[i][0])
{
exception = true;
this.application.getRobot().keyPress(COMBINATIONS[i][1]);
this.application.getRobot().keyPress(COMBINATIONS[i][2]);
this.application.getRobot().keyPress(COMBINATIONS[i][3]);
this.application.getRobot().keyRelease(COMBINATIONS[i][1]);
this.application.getRobot().keyRelease(COMBINATIONS[i][2]);
this.application.getRobot().keyRelease(COMBINATIONS[i][3]);
break;
}
}
if (!exception)
{
pressUnicode(this.application.getRobot(), action.unicode);
}
}
COMBINATIONS
public class Combinations extends ControllerDroidAction
{
public static final int UNICODE_TASK = 40;
public int unicode;
public Combinations(int unicode)
{
this.unicode = unicode;
}
public static Combinations parse(DataInputStream dis) throws IOException
{
int unicode = dis.readInt();
return new Combinations(unicode);
}
public void toDataOutputStream(DataOutputStream dos) throws IOException
{
dos.writeByte(COMBINATIONS);
dos.writeInt(this.unicode);
}
}

Calling variables between different classes through methods

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

Add weapons to inventory

I am trying to add weapons to a player inventory. It's kind of hard to explain, so I'll try my best. What I have are a class for each weapon, a class for Combat, and a class for the Player. I am trying to get it to where when the Random number equals a certain number, it will add a weapon to the player inventory. I will put my code Below.
Combat Class:
public class Combat {
M4 m4 = new M4();
M16 m16 = new M16();
M9 m9 = new M9();
Glock glock = new Glock();
SCAR Scar = new SCAR();
Player player = new Player();
final int chanceOfDrop = 3;
static boolean[] hasWeapon = {false, true};
public static int ranNumberGen(int chanceOfDrop) {
return (int) (Math.random()*5);
}
private void enemyDead() {
boolean canDrop = false;
if(ranNumberGen(chanceOfDrop)==0){
canDrop = true;
}
if(canDrop == true){
if(ranNumberGen(0) == 1) {
Player.addInvetory(m4.weaponName(wepName), m4.weaponAmmo(wepAmmo)); //Issues here. wepName & wepAmmo cannot be resolved into variable
//Should I just delete the line?
//Trying to get it to add the weapon M4 to the player inventory.
//Maybe use an ArrayList? If so I need a couple pointers on how to implement this.
}
}
}
}
M4 Class:
public class M4 implements Armory {
//Weapon classes are practically identical except for differences in the name wepDamage and wepAmmo.
public Integer weaponAmmo(int wepAmmo) {
wepAmmo = 10;
return wepAmmo;
}
public Integer weaponDamage(int wepDamage) {
wepDamage = 5;
return wepDamage;
}
public String weaponName(String wepName) {
wepName = "M4";
return wepName;
}
Player Class:
public class Player {
public static int health = 100;
//Player Class.
public static void addInvetory(String wepName, int wepAmmo) {
Player.addInvetory(wepName, wepAmmo);
}
public static void removeInventory(String wepName, int wepAmmo) {
Player.addInvetory(wepName, wepAmmo);
}
public static void removeAll(String wepName, int wepAmmo) {
Player.removeAll(wepName, wepAmmo);
}
Interface:
public interface Armory {
//Interface implemented by all of the weapons classes.
public Integer weaponAmmo(int wepAmmo);
public Integer weaponDamage(int wepDamage);
public String weaponName(String wepName);
Hope you can help!
class Weapon {
private final String name;
private final int damage;
private final int ammo;
public Weapon(final String name,final int damage,final int ammo) {
this.name = name;
this.damage = damage;
this.ammo = ammo;
}
public Weapon clone() {
return new Weapon(this.name,this.damage,this.ammo);
}
public String getName() {
return this.name;
}
public int getAmmo() {
return this.ammo;
}
public int getDamage() {
return this.damage;
}
}
class WeaponFactory {
static WeaponFactory factory;
public static WeaponFactory getWeaponFactory() {
if(factory == null) {
factory = new WeaponFactory();
}
return factory;
}
private ArrayList<Weapon> weapons = new ArrayList<Weapon>();
private Random random;
private WeaponFactory() {
//TODO: Fix Ammo and Damage
weapons.add(new Weapon("M4",0,0));
weapons.add(new Weapon("M16",0,0));
weapons.add(new Weapon("M9",0,0));
weapons.add(new Weapon("Glock",0,0));
weapons.add(new Weapon("SCAR",0,0));
}
public Weapon getWeapon() {
int w = random.nextInt(weapons.length);
return weapons.get(w).clone();
}
}
class Combat {
...
private void enemyDead() {
if(ranNumberGen(chanceOfDrop)==0){
Player.addInventory(WeaponFactory.getWeaponFactory().getWeapon());
}
}
}
You can use an array of Armory and the generate a random number from 0 to the size of the array as an index to the array to decide which weapon to add.
Okay dude, since your question about creating a programming language was closed, I'm answering it through here:
I think that your idea is great! Don't give up on it, yet don't get too excited. I would try all the options that you have heard of(interpreted route AND the Compiled route). If you can get either of those to work, then you may proceed to go into further detail with the language creation. It's going to take a while though. Be patient!

Categories