Stuck in using 2D arrays? - java

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);
}
}

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 can i access a private array with no getter Method from another class? [duplicate]

This question already has answers here:
How to read the value of a private field from a different class in Java?
(14 answers)
Closed 4 years ago.
So guys im trying to access a private Array from another class. Is there a way to access said array without a get-Method for the array?
public class Entity {
private int key;
private int value;
public Entity(int k, int v) {
key = k;
value = v;
}
public int getKey() {
return key;
}
public int getValue() {
return value;
}
public void setValue(int v) {
value = v;
}
public void setKey(int k) // selbst geadded
{
key = k;
}
}
Those are the elements that are contained in the array.
public class Relation {
private Entity[] map;
public Relation(int n) {
map = new Entity[n]; // größe des neuen feldes
}
public int size() {
return map.length;
}
public Entity extract(int i) {
if (i >= map.length || i < 0 || map[i] != null) {
return null;
}
int key = map[i].getKey();
int value = map[i].getValue();
map[i] = null;
return new Entity(key, value);
}
public boolean into(Entity e) {
for (int i = 0; i < size(); i++) {
if (map[i] == null) {
map[i] = e;
return true;
}
}
return false;
}
public static void main(String[] args) {
}
}
Relation is the Method im supposed to use. This class contains the private array which im trying to access.
public class Use {
public static boolean substitute(Relation rel, Entity e) {
if (rel.size() > 0) {
rel.map[0] = e; // "map has private acccess in Relation"
return true;
}
return false;
}
public static Relation eliminate(Relation rel, int k) {
int counter = 0;
for (int i = 0; i < rel.size(); i++) {
if (map[i] != k) // // "cannot find symbol map"
{
counter++;
}
}
}
}
And this is the class in which im trying to access the array. The methods here are not finished yet since im getting errors whenever im trying to access the map in the Relation class in any why since I cant figure it out.
To access fields, you need a FieldInfo:
Type relationType = typeof(Relation);
FieldInfo fieldRelationMap = relationType.GetField("map",
BindingFlags.Instance | BindingFlags.NonPublic);
FieldInfo has a GetValue and a SetValue

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

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.

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.

Can't make my own custom exception. Please help me

When I try and make a catch statement using InvalidTestScore exception java won't allow me. However when I use IllegalArgumentException, java does allow me to make it.
// George Beazer
public class TestScores2 {
public TestScores2(int[] arg) {
System.out.println(average(arg));
}
public int average(int[]arg)
{
int temp=0;
for (int i = 0; i < arg.length; i++) {
if(arg[i]<0 || arg[i]>100)
{
IllegalArgumentException e = new IllegalArgumentException();
throw e;
}
else
{
temp+=arg[i];
}
}
return temp/arg.length;
}
public static void main(String[] args) {
int []ar={4,78,33,89};
TestScores2 ts=new TestScores2(ar);
}
}
Runs fine
However if i run
public class TestScores2 {
public TestScores2(int[] arg) {
System.out.println(average(arg));
}
public int average(int[]arg)
{
int temp=0;
for (int i = 0; i < arg.length; i++) {
if(arg[i]<0 || arg[i]>100)
{
InvalidTestScoreException e = new InvalidTestScore();
throw e;
}
else
{
temp+=arg[i];
}
}
return temp/arg.length;
}
public static void main(String[] args) {
int []ar={4,78,33,89};
TestScores2 ts=new TestScores2(ar);
}
}
I get can't find symbol. What does it take to make your own custom exception .
InvalidTestScoreException e = new InvalidTestScore();
??? shouldn't that be:
InvalidTestScoreException e = new InvalidTestScoreException();
As #Falmarri pointed out, you need to declare an InvalidTestScoreException class
Here is what a revised version might look like:
public class TestScores2 {
public class InvalidTestScoreException extends RuntimeException {
//Constructors go here
}
public TestScores2(int[] arg) {
System.out.println(average(arg));
}
public int average(int[]arg)
{
int temp=0;
for (int i = 0; i < arg.length; i++) {
if(arg[i]<0 || arg[i]>100)
{
InvalidTestScoreException e = new InvalidTestScoreException();
throw e;
}
else
{
temp+=arg[i];
}
}
return temp/arg.length;
}
public static void main(String[] args) {
int []ar={4,78,33,89};
TestScores2 ts=new TestScores2(ar);
}
}

Categories