How to call to a list of established objects? (JAVA) - java

I have this code (and excuse the language) that my friend made for a game we are working on. The code is meant to create a list of possible weapons to pick up throughout the game, however it always returns a null value. So I made a method arms.printAllGuns(), which printed ever gun and then "null" at the very bottom without giving my a null point error(since it was only returning the name). So it seems to successfully establish every object as intended, but it creates an extra null Gun object, and can't properly return any object in the array.
This is giving the null
import java.util.*;
public class Soldier
{
//BASE
private ArrayList <Gun> gunsCarried;
private GunsAvalible arms = new GunsAvalible();
private Armor armor;
private int size;
private int bodyTempature;//1-10
private int health = 100;
private int numberOfSpecials;
public Soldier(int s, int g)
{
Gun temp = arms.get(g);
temp.getGunName();
final int size = s;
}
public void takeDamage(int damage)
{
health -= damage;
}
}
And then here is the List of guns
public class GunsAvalible
{
Gun [] gunsArray = new Gun [40];
public GunsAvalible()
{
//(Name, ClipSize, Power)
gunsArray[0] = new Gun("Hucker", 13, 10);//PISTOL
gunsArray[1] = new Gun("Rafile", 10, 15);//RIFLE
gunsArray[2] = new Gun("Slumper", 14, 14);//PISTOL
gunsArray[3] = new Gun("Normality", 3, 40);//SHOTGUN
gunsArray[4] = new Gun("Feminest Friendly", 1, 1);//TAZER
gunsArray[5] = new Gun("China Man", 32, 5);//MACHINEGUN
gunsArray[6] = new Gun("Bax", 6, 25);//SNIPER
gunsArray[7] = new Gun("Regicidal Tyranus", 7, 20);//SPECIAL
gunsArray[8] = new Gun("Blaking", 12, 15);//RIFLE
gunsArray[9] = new Gun("Olive Branch", 4, 50);//SNIPER
gunsArray[10] = new Gun("DYL-SCHO", 0,0);//SNIPER
gunsArray[11] = new Gun("Forrest Burrner",0,0 );//FLAMETHROWER
gunsArray[12] = new Gun("Sahaka",0,0);//Hose
gunsArray[13] = new Gun("Chirper", 16, 7);//PISTOL
gunsArray[14] = new Gun("Gourd", 1, 100);
gunsArray[15] = new Gun("Fohell", 0, 0);
gunsArray[16] = new Gun("Candle Stick", 0, 0);
gunsArray[17] = new Gun("Rock Wing",0 ,0);
gunsArray[18] = new Gun("Busting Pain", 0 ,0);
gunsArray[19] = new Gun("Wosham's Anahe",0,0);
gunsArray[20] = new Gun("Fucker", 13, 10);//PISTOL
gunsArray[21] = new Gun("Rafiphile", 10, 15);//RIFLE
gunsArray[22] = new Gun("Humper", 14, 14);//PISTOL
gunsArray[23] = new Gun("Reality", 3, 40);//SHOTGUN
gunsArray[24] = new Gun("Dick Frier", 1, 1);//TAZER
gunsArray[25] = new Gun("Yellow River", 32, 5);//MACHINEGUN
gunsArray[26] = new Gun("Bax-Stabber", 6, 25);//SNIPER
gunsArray[27] = new Gun("Regicidal Tyranus II", 7, 20);//SPECIAL
gunsArray[28] = new Gun("Faking", 12, 15);//RIFLE
gunsArray[29] = new Gun("Broken Branch", 4, 50);//SNIPER
gunsArray[30] = new Gun("DYL-DO", 0,0);//SNIPER
gunsArray[31] = new Gun("Worrld Burrner",0,0 );//FLAMETHROWER
gunsArray[32] = new Gun("Water Will",0,0);//Hose
gunsArray[33] = new Gun("Chirper", 16, 7);//PISTOL
gunsArray[34] = new Gun("Budai", 1, 100);//RPG
gunsArray[35] = new Gun("Fovaehan",0,0);
gunsArray[36] = new Gun("Candle Stick",0,0);
gunsArray[37] = new Gun("Rock Wing",0,0);
gunsArray[38] = new Gun("Riding Vain",0,0);
gunsArray[39] = new Gun("IF-EA",0,0);
}
public Gun get(int gunNumber)
{
return gunsArray[gunNumber];
}
}
and lastly the gun class
public class Gun
{
private String name = ("");
private int ammo = 0;
private int clipSize = 0;
private int clip = 0;
private int power = 0;
private Gun [] gunsArray = new Gun [20];
private Gun [] gunsRankIIArray = new Gun [20];
public Gun(String n, int cs, int p)
{
final int clipSize = cs;
clip = 1 + (int)(3.14 * 5 * Math.random());
power = p;
name = n;
if(clip > clipSize)
clip = clipSize;
}
public void ammoPickup(int a)
{
ammo += a;
}
public int fire()
{
if(clip == 0)
{
reload();
return 0;
}
clip--;
int damage = 0;
double critical = Math.random();
if(critical < .5)
{
damage = (int)(power * (1+critical));
}
else
{
damage = power * 2;
}
return damage;
}
public boolean reload()
{
if(ammo > 0)
{
ammo -= clipSize;
clip += clipSize;
return true;
}
else
{
return false;
}
}
public String getGunName()
{
return name;
}
}
I appreciate any help or tips, because I'm sorta at a stand still

I think you're missing
gunsCarried = new ArrayList<>();
gunsCarried.add(temp);
in your Soldier constructor.

Related

Simplify Switch with multiple variables in Java

I have this monster of code, because depending on the length of the list, it is the number of times that I have to add that result to the menu.
Does anyone know how to simplify these entries to the list? I cannot use the same variable since the method overwrites the last input...
//This list receives a list of values
List<LBUResumen> lbu = CargarTabla.cargarTablaLBUResumen();
//This for loop generates a menuitem for each value in the list lbu
for (int a = 0; a < lbu.size(); a++) {
MenuItem menu = null;
String supervisor = lbu.get(a).getSupervisor();
//This is a model of a table, we store a value that helps us
//make reference to another table in the database
modr.setIdArea(lbu.get(a).getIdArea());
//This list saves the results of the query
List<Puesto> lbuP = CargarTabla.cargarTablaPuesto(modr);
//Conditions according to the size of the query
switch (lbuP.size()) {
case 1: {
String puesto = lbuP.get(0).getNombre_Puesto();
int propuestoP = lbu.get(0).getPropuesto();
int propuestoS = lbu.get(a).getPropuesto();
MenuItem submenu1 = new MenuItem(puesto, propuestoP, null);
menu = new MenuItem(supervisor, propuestoS, null,
submenu1);
addMenu(menu);
break;
}
case 2: {
String puesto1 = lbuP.get(0).getNombre_Puesto();
String puesto2 = lbuP.get(1).getNombre_Puesto();
int propuestoP1 = lbu.get(0).getPropuesto();
int propuestoP2 = lbu.get(1).getPropuesto();
int propuestoS = lbu.get(a).getPropuesto();
int propuestoD = lbu.get(a).getDiferencia();
int propuestoP = lbu.get(a).getPlantilla();
int A = lbu.get(a).getTurnoA();
int B = lbu.get(a).getTurnoB();
int C = lbu.get(a).getTurnoC();
int D = lbu.get(a).getTurnoD();
int LV = lbu.get(a).getTurnoLV();
SubMenuItem submenu1 = new SubMenuItem(puesto1, 0, 0, 0,
0, 0, 0, 0, 0, null);
SubMenuItem submenu2 = new SubMenuItem(puesto2, 0, 0, 0,
0, 0, 0, 0, 0, null);
menu = new MenuItem(supervisor, propuestoS, propuestoD, propuestoP,
A, B, C, D, LV,
null, submenu1, submenu2);
addMenu(menu);
break;
}
case 3: {
String puesto1 = lbuP.get(0).getNombre_Puesto();
String puesto2 = lbuP.get(1).getNombre_Puesto();
String puesto3 = lbuP.get(2).getNombre_Puesto();
int propuestoP1 = lbu.get(0).getPropuesto();
int propuestoP2 = lbu.get(1).getPropuesto();
int propuestoP3 = lbu.get(2).getPropuesto();
int propuestoS = lbu.get(a).getPropuesto();
MenuItem submenu1 = new MenuItem(puesto1, propuestoP1, null);
MenuItem submenu2 = new MenuItem(puesto2, propuestoP2, null);
MenuItem submenu3 = new MenuItem(puesto3, propuestoP3, null);
menu = new MenuItem(supervisor, propuestoS, null,
submenu1, submenu2, submenu3);
addMenu(menu);
break;
}
So I wanted to know if it is possible in some way to simplify the statements so that I don't have so many lines of code in the switch,Thanks in advance <3
This is the method that receives the submenus, it makes an instance of itself
private void addMenu(MenuItem... menu) {
for (int i = 0; i < menu.length; i++) {
frm.jPanel1.add(menu[i]);
ArrayList<MenuItem> subMenu = menu[i].getSubMenu();
for (MenuItem m : subMenu) {
addMenu(m);
}
}
frm.jPanel1.revalidate();
}
This is the constructor class to MenuItem
public MenuItem(String menuName, int propuesto, ActionListener act, MenuItem... subMenu) {
initComponents();
lbName.setText(menuName);
lbPropuesto.setText(menuName);
if (act != null) {
this.act = act;
}
this.setSize(new Dimension(Integer.MAX_VALUE, 60));
this.setMaximumSize(new Dimension(Integer.MAX_VALUE, 60));
this.setMinimumSize(new Dimension(Integer.MAX_VALUE, 60));
for (int i = 0; i < subMenu.length; i++) {
this.subMenu.add(subMenu[i]);
subMenu[i].setVisible(false);
}
}

How would I implement this Serialised parking lot simulation using to Executor services

I'm trying to understand the benefits of multithreading much better. I have with me a serialised implementation of a parking lot simulation. I want to make it so that the program uses Executor services instead, how would I go about doing that?
Below is my parking-lot class, the implementation could definitely be refined, I just can't seem to figure out how to.
public class Parking {
public static void main(String[] args) throws InterruptedException {
Parking parkingObj = new Parking();
parkingObj.runSimulation();
}
public void runSimulation() throws InterruptedException{
int numOfRuns = 101;//100 runs
int currentRuns = 1;
securityGuard myGuard = new securityGuard();
//spot mySpot = new spot();
ArrayList<ticketClass> ticketArray = new ArrayList<>();
int bouncedCustomers = 1;
spot availableSpot = new spot();
//Random randomExit = new Random();
while (currentRuns < numOfRuns){
Random randomSleep = new Random();
//Car object instantiation
carClass vehicle = new carClass();
//ticketClass ticketObj = new ticketClass();
//Random time generator
Random randomTime = new Random();
//instantiation of the info geneatator class
infoGenerator info = new infoGenerator();
//Generaring random Car info
String plateNumber = info.plateGenerator();
String carModel = info.modelGenerator();
String color = info.colorGenerator();
if (availableSpot.getSpotNum() == 15 ){
System.out.println("Carpark full, No cars allowed unitl a space is free");
//Customers waiting for free space
Thread.sleep(9000);
System.out.println("Total Waiting customers: " + bouncedCustomers);
bouncedCustomers += 1;
}
else{
//System.out.println("Customer Exiting");
Thread.sleep(randomTime.nextInt(5000));
meterClass myMeter = new meterClass();
ticketClass myTicket = myGuard.ticketGenerator(vehicle, myMeter);
//ticketClass myTicket = new ticketClass();
myTicket.setmeter(myMeter);
myTicket.setCar(vehicle);
myTicket.getCar().plateSetter(plateNumber);
myTicket.getCar().colorSetter(color);
myTicket.getCar().modelSeter(carModel);
myTicket.getCar().minSetter(randomTime.nextInt(100));
//Details are only set if there is space available
//The assumption is that users cannot stay longer than 2 days. The reality-to-simulation time ratio is 1 unit:10min
myMeter.setPurchasedMinutes(randomTime.nextInt(72));
System.out.println("\n\nCar " + currentRuns + " has entered the car park");
System.out.println("\nCAR DETAILS:");
System.out.println(carModel);
System.out.println(plateNumber);
System.out.println(color);
int spotAvail = availableSpot.assignSpot();
myTicket.setSlotNum(spotAvail);
//Set the time the car entered
String timeIn = info.timeMonitor();
//myTicket.
ticketArray.add(myTicket);
System.out.println("\n\n===Total customers: " + ticketArray.size());
System.out.println(timeIn+"\n");
availableSpot.spotLog();
}
//Cars leaving at random times
for (int i= 0; i < ticketArray.size();i++ ){
meterClass meterOut = ticketArray.get(i).getMeter();
carClass ExitCar = ticketArray.get(i).getCar();
if(myGuard.checkParking(ExitCar,meterOut)){
System.out.println("\nCustomer " + ExitCar.plateGetter()+ " is exiting the carpark...");
double penaltyVal = ticketArray.get(i).getPenalty();
System.out.println("FINE: " + penaltyVal);
System.out.println("==================================================================");
Thread.sleep(randomTime.nextInt(4000));
ticketArray.remove(ticketArray.remove(i));
availableSpot.spotFree(i);
}
}
currentRuns += 1;
}
}
}
TLDR: I need to optimise the following code, both structure-wise and in terms of speed (Specifically using multithreading with Executor service)
As it currently is, it runs in an infinite loop, and the fine value is 0. The security guard class which is responsible for this calculation is as such;
public class securityGuard{
public String badgeNumber;
public String guardName;
securityGuard(){}
securityGuard(String badgeNumber, String guardName){
this.badgeNumber = badgeNumber;
this.guardName = guardName;
}
public void setBadgeNumber(String badgeNumber){
this.badgeNumber = badgeNumber;
}
public String getBadgeNumber(){
return badgeNumber;
}
public void setguardName(String guardName){
this.guardName = guardName;
}
public String getGuardName(){
return guardName;
}
public boolean checkParking(carClass car,meterClass meter){
return car.minGetter() > meter.getPurchasedMinutes();
}
public ticketClass ticketGenerator(carClass car, meterClass meterVar){
ticketClass myTicket = new ticketClass(car,this);
int timeRemaining = car.minGetter() - meterVar.getPurchasedMinutes();
if(checkParking(car,meterVar)){
if (timeRemaining < 60){
myTicket.penalty = 50;
}
else {
myTicket.penalty = 50 + (10 * (timeRemaining/60));
}
}
return myTicket;
}
}
Please let me know if you require any additional information regarding the other classes or if I left anything out .Thank you in advance

How can I make the following parkinglot simulation asynchronous use RabbitMQ?

I'm trying to learn and undertand the different approaches to concurrency in java. I have with me a serialised implementation of a parking lot simulation. I want to make it so that the program uses Rabbitmq instead, how would I go about doing that?
Below is my parking-lot class, which, implementation wise could also be improved.
EDIT: I've realised that my main question is actually, how can I do the Pub/sub in a loop.2. Is pub/sub even necessary?
public class Parking {
public static void main(String[] args) throws InterruptedException {
Parking parkingObj = new Parking();
parkingObj.runSimulation();
}
public void runSimulation() throws InterruptedException{
int numOfRuns = 101;//100 runs
int currentRuns = 1;
securityGuard myGuard = new securityGuard();
//spot mySpot = new spot();
ArrayList<ticketClass> ticketArray = new ArrayList<>();
int bouncedCustomers = 1;
spot availableSpot = new spot();
//Random randomExit = new Random();
while (currentRuns < numOfRuns){
Random randomSleep = new Random();
//Car object instantiation
carClass vehicle = new carClass();
//ticketClass ticketObj = new ticketClass();
//Random time generator
Random randomTime = new Random();
//instantiation of the info geneatator class
infoGenerator info = new infoGenerator();
//Generaring random Car info
String plateNumber = info.plateGenerator();
String carModel = info.modelGenerator();
String color = info.colorGenerator();
if (availableSpot.getSpotNum() == 15 ){
System.out.println("Carpark full, No cars allowed unitl a space is free");
//Customers waiting for free space
Thread.sleep(9000);
System.out.println("Total Waiting customers: " + bouncedCustomers);
bouncedCustomers += 1;
}
else{
//System.out.println("Customer Exiting");
Thread.sleep(randomTime.nextInt(5000));
meterClass myMeter = new meterClass();
ticketClass myTicket = myGuard.ticketGenerator(vehicle, myMeter);
//ticketClass myTicket = new ticketClass();
myTicket.setmeter(myMeter);
myTicket.setCar(vehicle);
myTicket.getCar().plateSetter(plateNumber);
myTicket.getCar().colorSetter(color);
myTicket.getCar().modelSeter(carModel);
myTicket.getCar().minSetter(randomTime.nextInt(100));
//Details are only set if there is space available
//The assumption is that users cannot stay longer than 2 days. The reality-to-simulation time ratio is 1 unit:10min
myMeter.setPurchasedMinutes(randomTime.nextInt(72));
System.out.println("\n\nCar " + currentRuns + " has entered the car park");
System.out.println("\nCAR DETAILS:");
System.out.println(carModel);
System.out.println(plateNumber);
System.out.println(color);
int spotAvail = availableSpot.assignSpot();
myTicket.setSlotNum(spotAvail);
//Set the time the car entered
String timeIn = info.timeMonitor();
//myTicket.
ticketArray.add(myTicket);
System.out.println("\n\n===Total customers: " + ticketArray.size());
System.out.println(timeIn+"\n");
availableSpot.spotLog();
}
//Cars leaving at random times
for (int i= 0; i < ticketArray.size();i++ ){
meterClass meterOut = ticketArray.get(i).getMeter();
carClass ExitCar = ticketArray.get(i).getCar();
if(myGuard.checkParking(ExitCar,meterOut)){
System.out.println("\nCustomer " + ExitCar.plateGetter()+ " is exiting the carpark...");
double penaltyVal = ticketArray.get(i).getPenalty();
System.out.println("FINE: " + penaltyVal);
System.out.println("==================================================================");
Thread.sleep(randomTime.nextInt(4000));
ticketArray.remove(ticketArray.remove(i));
availableSpot.spotFree(i);
}
}
currentRuns += 1;
}
}
}
TLDR: I need to optimise the following code, both structure-wise and in terms of speed (Specifically using multithreading with RabbitMQ)
As it currently is, it runs in an infinite loop, and the fine value is 0. The security guard class which is responsible for this calculation is as such;
public class securityGuard{
public String badgeNumber;
public String guardName;
securityGuard(){}
securityGuard(String badgeNumber, String guardName){
this.badgeNumber = badgeNumber;
this.guardName = guardName;
}
public void setBadgeNumber(String badgeNumber){
this.badgeNumber = badgeNumber;
}
public String getBadgeNumber(){
return badgeNumber;
}
public void setguardName(String guardName){
this.guardName = guardName;
}
public String getGuardName(){
return guardName;
}
public boolean checkParking(carClass car,meterClass meter){
return car.minGetter() > meter.getPurchasedMinutes();
}
public ticketClass ticketGenerator(carClass car, meterClass meterVar){
ticketClass myTicket = new ticketClass(car,this);
int timeRemaining = car.minGetter() - meterVar.getPurchasedMinutes();
if(checkParking(car,meterVar)){
if (timeRemaining < 60){
myTicket.penalty = 50;
}
else {
myTicket.penalty = 50 + (10 * (timeRemaining/60));
}
}
return myTicket;
}
}
Please let me know if you require any additional information regarding the other classes or if I left anything out .Thank you in advance
EDIT:
Below is my attempt at a producer implementation. I tried using a for loop in the run method with the goal of publishing 100 random messages
public class entrySimulation implements Runnable {
int numOfRuns = 100;//1000 runs
int currentRuns = 1;
securityGuard_exp_1 myGuard = new securityGuard_exp_1();
//System.out.println("Customer Exiting");
//Thread.sleep(randomTime.nextInt(5000));
meterClass_exp_1 myMeter = new meterClass_exp_1();
//Details are only set if there is space available
//The assumption is that users cannot stay longer than 2 days. The reality-to-simulation time ratio is 1 unit:10min
//instantiation of the info generator class
infoGenerator_exp_1 info = new infoGenerator_exp_1();
//Generating random Car info
//spot_exp_1 mySpot = new spot_exp_1();
//Use an iterator
List<ticketClass_exp_1> ticketArray = new ArrayList<>();
Iterator<ticketClass_exp_1> iter = ticketArray.iterator();
public final spot_exp_1 availableSpot = new spot_exp_1();
//Random time generator
Random randomTime = new Random();
public static void main(String[] args) {
String exchangeName = "entryExchange";
String routingKey = "exitKey";
String message = "";
//Creating a connection factory
ConnectionFactory factory = new ConnectionFactory();
//Creating new connection
try(Connection conVar = factory.newConnection();){
Channel channelCon = conVar.createChannel();
//Exchange declaration
channelCon.exchangeDeclare(exchangeName,"customerExit");
channelCon.basicPublish(exchangeName,routingKey,null,message.getBytes(StandardCharsets.UTF_8));
System.out.println("Customer Exited");
}catch(Exception e){}
}
#Override
public void run() {
for (int i = 0; i < numOfRuns; i++) {
//System.out.println(i);
String plateNumber = info.plateGenerator();
String carModel = info.modelGenerator();
String color = info.colorGenerator();
myMeter.setPurchasedMinutes(randomTime.nextInt(30));
carClass_exp1_1 vehicle = new carClass_exp1_1(carModel, color, plateNumber, randomTime.nextInt(2880));
ticketClass_exp_1 myTicket = myGuard.ticketGenerator(vehicle, myMeter);
//Generating details
myTicket.setmeter(myMeter);
myTicket.setCar(vehicle);
myTicket.getCar().plateSetter(plateNumber);
myTicket.getCar().colorSetter(color);
myTicket.getCar().modelSeter(carModel);
myTicket.getGuard().setguardName("Phill");
myTicket.getGuard().setBadgeNumber("AF170");
int spotAvail = availableSpot.assignSpot();
myTicket.setSlotNum(spotAvail);
//Set the time the car entered
String timeIn = info.timeMonitor();
//message
System.out.println("\n\nCar " + currentRuns + " has entered the car park");
System.out.println("\nCAR DETAILS:");
System.out.println(carModel);
System.out.println(plateNumber);
System.out.println(color);
System.out.println("Penalty" + myTicket.getPenalty());
ticketArray.add(myTicket);
System.out.println("============================================|");
System.out.println("TIME IN: " + timeIn);
//System.out.println("\n\n===Total customers: " + myTicket.slotNum);
//message
availableSpot.spotLog();
}
}
}
However, I'm not sure how to. Please if anyone can help in any way. Sorry, this is a very new concept to me

Java Object values not consistent

I couldn't find any other solutions to my problem because I'm unsure of how to describe it in few enough words.
When I assign activeList, which is a field of currentActiveList a randomly generated Rectangle in the ActiveList class it receives the value just fine.
public class ActiveList {
Rectangle[] activeList = new Rectangle[10];
public ActiveList() {
for(int i = 0; i < activeList.length; i++)
activeList[i] = null;
}
public void addToList(Rectangle x) {
for(int i = 0; i < this.activeList.length; i++) {
if(this.activeList[i] == null) {
this.activeList[i] = x;
i = this.activeList.length+1;
}
else
this.activeList[activeList.length-1] = x;
}
}
public Rectangle[] getActiveList() {
return this.activeList;
}
public int getLength() {
//System.out.print(this.activeList.length);
return this.activeList.length;
}
public void deleteFromList(int x) {
this.activeList[x] = null;
}
public Rectangle getFromList(int x) {
Rectangle retVal = this.activeList[x];
//System.out.println("Returning getFromList(int x): " +retVal);
return retVal;
}
public void genRandomRectangle() {
Random randomNumberGenerator = new Random();
double[] pointVal = new double[4];
double randomInt = randomNumberGenerator.nextInt(400-10);
pointVal[0] = randomInt;
randomInt = randomNumberGenerator.nextInt(400-10);
pointVal[1] = randomInt;
randomInt = randomNumberGenerator.nextInt((int) (400-pointVal[0]));
if(randomInt < 5) {
randomInt = randomInt+pointVal[0]+5;
}
else
pointVal[2] = randomInt+pointVal[0];
randomInt = randomNumberGenerator.nextInt((int) (400-pointVal[1]));
if(randomInt < 5) {
randomInt = randomInt+pointVal[1]+5;
}
else
pointVal[3] = randomInt+pointVal[1];
Rectangle newRandom = new Rectangle(pointVal[0], pointVal[1], pointVal[2], pointVal[3]);
//System.out.println(pointVal[0]);
//System.out.println(pointVal[1]);
//System.out.println(pointVal[2]);
//System.out.println(pointVal[3]);
System.out.println("New Random: " +newRandom);
addToList(newRandom);
}
}
However, when I try to use those values in my main class GraphicGen, the currentActiveList returns null values for all of its indexes.
public class GraphicGen extends JPanel {
ActiveList currentActiveList = new ActiveList();
public static int gridSpaceX = 400;
public static int gridSpaceY = 400;
static JFrame mainFrame = new JFrame();
protected void paintComponent(Graphics g) {
//super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//int w = getWidth();
//int h = getHeight();
// Draw ordinate.
//g2.draw(new Line2D.Double(PAD, PAD, PAD, h-PAD));
// Draw abcissa.
//g2.draw(new Line2D.Double(PAD, h-PAD, w-PAD, h-PAD));
//double xInc = (double)(w - 2*PAD)/(data.length-1);
//double scale = (double)(h - 2*PAD)/maxValue();
// Mark data points.
//g2.setPaint(Color.red);
double[] coords = new double[4];
//g2.fill(new Ellipse2D.Double(coords[0], coords[1], 4, 4));
//g2.fill(new Ellipse2D.Double(coords[2], coords[3], 4, 4));
//g2.fill(new Ellipse2D.Double(100, 100, 4, 4));
System.out.println("Graphic Gen Active List Obj: " +currentActiveList);
System.out.println("Ya drew a new Main GUI!");
System.out.println("currentActiveList.getActiveList(): " +currentActiveList.getActiveList());
for(int i = 0; i < currentActiveList.getLength(); i++) {
//System.out.println("currentActiveList.getFromList(i): "+currentActiveList.getFromList(i));
//System.out.println("Graphic Gen Active List Obj: " +currentActiveList);
//System.out.println(activeList.getFromList(i).getTopLeftX());
if(currentActiveList.getFromList(i) != null) {
coords[0] = currentActiveList.getFromList(i).getTopLeftX();
System.out.println(coords[0]);
coords[1] = currentActiveList.getFromList(i).getTopLeftY();
System.out.println(coords[1]);
coords[2] = currentActiveList.getFromList(i).getBottomRightX();
System.out.println(coords[2]);
coords[3] = currentActiveList.getFromList(i).getBottomRightY();
System.out.println(coords[3]);
g2.draw(new Line2D.Double(coords[0], coords[1], coords[2], coords[1]));
g2.draw(new Line2D.Double(coords[0], coords[1], coords[0], coords[3]));
g2.draw(new Line2D.Double(coords[2], coords[1], coords[2], coords[3]));
g2.draw(new Line2D.Double(coords[0], coords[3], coords[2], coords[3]));
}
}
/*double x = 50;
double y = 50;
g2.fill(new Ellipse2D.Double(x, y, 4, 4));*/
/*for(int i = 0; i < data.length; i++) {
double x = PAD + i*xInc;
double y = h - PAD - scale*data[i];
g2.fill(new Ellipse2D.Double(x-2, y-2, 4, 4));
}*/
}
/*private int maxValue() {
int max = data[0];
for(int i = 0; i < data.length; i++) {
if(data[i] > max)
max = data[i];
}
return max;
}*/
public void callRepaintOnMain() {
mainFrame.repaint();
}
public void callGenRandom() {
currentActiveList.genRandomRectangle();
}
public static void main(String[] args) {
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new GraphicGen());
mainFrame.setSize(gridSpaceX, gridSpaceY);
ButtonPrompt buttonPrompter = new ButtonPrompt();
mainFrame.setLocation(200,200);
mainFrame.setVisible(true);
}
}
The random generator method is called by the action listener.
public class ButtonPrompt extends GraphicGen {
ActionListener actionListenerRandom = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
//currentActiveList.genRandomRectangle();
callGenRandom();
callRepaintOnMain();
}
};
JButton randomBtn = new JButton("Add Random Rectangle");
JButton inputCoordinates = new JButton("Input Rectangle Coordinates");
public ButtonPrompt() {
JFrame f = new JFrame("Add Rectangles");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BoxLayout boxLayout = new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS);
f.setLayout(boxLayout);
randomBtn.addActionListener(actionListenerRandom);
f.setSize(200, 200);
f.setLocation(600, 200);
f.setVisible(true);
f.add(randomBtn);
f.add(inputCoordinates);
f.pack();
}
}
Is this a scoping or referencing problem? I'm really at a loss here.
Here:
public static void main(String[] args) {
...
mainFrame.add(new GraphicGen());
...
ButtonPrompt buttonPrompter = new ButtonPrompt();
}
ButtonPrompt extends GraphicGen, which is a JPanel. In ButtonPrompt's constructor, you created a JFrame and added two JButtons to it.
So when your app starts, there will be two JFrames on the screen, one is mainFrame which contains a GraphicGen, the other is buttonPrompter which contains two buttons.
When you click on the button, the actionPerformed() is called and it's actually calling the callGenRandom() of the buttonPrompter -- if the random generation logic is correct, the generated Rectangles are added to buttonPrompter. But you didn't add this buttonPrompter to any one of the JFrames, you won't see it.
What you may want:
ButtonPrompt doesn't extend GraphicGen, instead, give ButtonPrompt a reference of the GraphicGen you added to the mainFrame.
public class ButtonPrompt extends GraphicGen {
JButton randomBtn = new JButton("Add Random Rectangle");
JButton inputCoordinates = new JButton("Input Rectangle Coordinates");
final GraphicGen gg;
public ButtonPrompt(GraphicGen gg) {
this.gg = gg;
......
ActionListener actionListenerRandom = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
gg.callGenRandom();
gg.callRepaintOnMain();
}
};
randomBtn.addActionListener(actionListenerRandom);
......
}
}
and in your main():
public static void main(String[] args) {
...
GraphicGen gg = new GraphicGen();
mainFrame.add(gg);
...
ButtonPrompt buttonPrompter = new ButtonPrompt(gg);
}
What's more, the code has other problems.
For example, GraphicGen is a JPanel, main class and it has a field of a JFrame which actually contains the GraphicGen instance when app runs -- this looks bad. I don't know much of Swing... Is it a must to call the containing JFrame's repaint() instead of just calling the JPanel's repaint(), if it has?
Your actual problem is quite unclear, but just reading the first two methods is enough to find what, I suppose, is a bug:
public ActiveList() {
for(int i = 0; i < activeList.length; i++)
activeList[i] = null;
}
the above code is completely useless. The default value of an element of an array of objects is null. So the loop assigns null to a variable wich is already null.
public void addToList(Rectangle x) {
for(int i = 0; i < this.activeList.length; i++) {
if(this.activeList[i] == null) {
this.activeList[i] = x;
i = this.activeList.length+1;
}
else
this.activeList[activeList.length-1] = x;
}
}
If your list only contains null, the rectangle will be stored at index 0, and the loop will stop. For all the susequent calls to this method, the loop will find that the element at index 0 is not null, and will thus store x at the last index of the array, and then at the first non-null index.
I don't know exactly what you're trying to achieve, and what the actual problem is, but you should probably forget about implementing your own list based on an array, and use an ArrayList instead.

Java, if statement is not returning true boolean [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm trying to debug this project and during testing, in the Test class, although the criteria for the checkModuleSelection() method to return True has been met and this is not happening. I want the driver class to run the checkModuleSelection() method using the test data supplied and return a true.
Test class
public class Test {
public static void main (String [] args)
{
Module csc8001 = new Module("CSC8001", "Programming and data structures", 15, 0, 0, 6);//1: 60, 2: 60
Module csc8002 = new Module("CSC8002", "Test Module", 0, 15, 0, 7);
Module csc8003 = new Module("CSC8001", "Programming and data structures", 0, 0, 0, 7);
Module csc8004 = new Module("CSC8002", "Test Module", 15, 0, 0, 7);
Module csc8005 = new Module("CSC8001", "Programming and data structures", 0, 15, 0, 7);
Module csc8006 = new Module("CSC8002", "Test Module", 0, 0, 0, 7);
Module csc8007 = new Module("CSC8001", "Programming and data structures", 15, 0, 0, 7);
Module csc8008 = new Module("CSC8002", "Test Module", 0, 15, 0, 7);
Module csc8009 = new Module("CSC8001", "Programming and data structures", 0, 0, 0, 7);
Module csc8010 = new Module("CSC8002", "Test Module", 15, 0, 0, 7);//lvl 7 150
Module csc8011 = new Module("CSC8001", "Programming and data structures", 0, 15, 0, 7);
Module csc8012 = new Module("CSC8002", "Test Module", 0, 0, 60, 7);
Module csc8013 = new Module("CSC8001", "Programming and data structures", 0, 0, 0, 7);
Student chris = new Student("Chris", "1");
System.out.println(chris.getName());
chris.addModule(csc8001);
chris.addModule(csc8002);
chris.addModule(csc8003);
chris.addModule(csc8004);
chris.addModule(csc8005);
chris.addModule(csc8006);
chris.addModule(csc8007);
chris.addModule(csc8008);
chris.addModule(csc8009);
chris.addModule(csc8010);
chris.addModule(csc8011);
chris.addModule(csc8012);
chris.addModule(csc8013);
System.out.println(chris.checkModuleSelection());
}
}
Student class
public boolean checkModuleSelection() {
int sumLevel6Credits = 0;
int sumLevel7Credits = 0;
int sumOtherCredits = 0;
int sem1Credits = 0;
int sem2Credits = 0;
int sem3Credits = 0;
boolean projectModule = false;
for (int i = 0; i < MAX_NUMBER_OF_MODULES; i++) {
System.out.println("The value of sem1Credits is: " + sem1Credits);
if (moduleRecords[i] != null) {
if (moduleRecords[i].getModule().getLevel() == Module.MSC_MODULE_LEVEL) {
sumLevel7Credits += moduleRecords[i].getModule()
.getSemesterOneCredits();
System.out.println();
} else if (moduleRecords[i].getModule().getLevel() == Module.STAGE_3_MODULE_LEVEL) {
sumLevel6Credits += moduleRecords[i].getModule()
.getTotalCredits();
}
projectModule = moduleRecords[i].getModule().getTotalCredits() >= MINIMUM_PROJECT_CREDITS;
sem1Credits += moduleRecords[i].getModule()
.getSemesterOneCredits();
sem2Credits += moduleRecords[i].getModule()
.getSemesterTwoCredits();
sem3Credits += moduleRecords[i].getModule()
.getSemesterThreeCredits();
}
}
// check that there is at least one project module, there isn't too many
// level 6 credits, there is enough total credits and enough credits in
// each semester
return !((sumOtherCredits > 0)
|| !projectModule
|| (sumLevel6Credits < MAXIMUM_LEVEL_6_CREDITS)
|| (sumLevel6Credits + sumLevel7Credits != VALID_NUMBER_OF_REGISTERED_CREDITS)
|| sem1Credits < 50 || sem1Credits > 70 || sem2Credits < 50
|| sem2Credits > 70 || sem3Credits < 50 || sem3Credits > 70);
}
EDIT
As requested, the Module class is below
package Project1;
//This class represents a module
public class Module {
public final static int MSC_MODULE_PASS_MARK = 50;
public final static int UG_MODULE_PASS_MARK = 40;
public final static int MSC_MODULE_LEVEL = 7;
public final static int STAGE_3_MODULE_LEVEL = 6;
private String moduleCode;
private String moduleTitle;
private int sem1Credits;
private int sem2Credits;
private int sem3Credits;
private int moduleLevel;
public Module(String code, String title, int sem1, int sem2, int sem3, int level)
{
moduleCode = code;
moduleTitle = title;
sem1Credits = sem1;
sem2Credits = sem2;
sem3Credits = sem3;
moduleLevel = level;
}
//method to return the module code
public String getCode()
{
return moduleCode;
}
//method to return the module title
public String getTitle()
{
return moduleTitle;
}
//method to return the Semester 1 credits
public int getSemesterOneCredits()
{
return sem1Credits;
}
//method to return the Semester 2 credits
public int getSemesterTwoCredits()
{
return sem2Credits;
}
//method to return the Semester 3 credits
public int getSemesterThreeCredits()
{
return sem3Credits;
}
//method to return the total credits across all the semesters
public int getTotalCredits()
{
// return sem2Credits + sem3Credits;
return sem1Credits + sem2Credits + sem3Credits;
}
//method to return the module level
public int getLevel()
{
return moduleLevel;
}
}
Use .equals() method to compare, do not use == for comparing objects.
== will check both references are referring same object in the memory, while .equals() used for comparing both objects are meaninfully equal.
if (moduleRecords[i].getModule().getLevel().equals(Module.MSC_MODULE_LEVEL)) {}

Categories

Resources