How to create object using this given constructor - java

public Life(List<class> classes, int schoolwork) {
super(classes, schoolwork);
}
I am trying to make a Life object out of this code but am not doing it right what I have is
Life life = new Life();
but I can't figure out how to get the parameters right to include classes and schoolwork.

I tried to interpret your problem and I wrote a piece of code where I show you how to create a Life object by passing it the correct parameters.
Maybe your problem was creating the List object (?)
CODE
public class Main {
public static void main(String[] args) throws IOException {
List<CustomClass> customClass = new ArrayList<>();
int schoolwork = 1;
Life life = new Life(customClass, schoolwork);
}
}
class CustomClass {
}
class Life {
/**
* Constructor
*
* #param customClass
* #param schoolwork
*/
public Life(List<CustomClass> customClass, int schoolwork) {
// super(strings, schoolwork);
}
}

Related

How to add to array in main?

I have created an array which I wanted to control from main. My code runs, but I don't know how to add integers to the array from the main class. Also as each ConcreteSubject has its own storage array, how would i change this to store them all in the same array?
public class ConcreteSubject extends AbstractSpy
{
private AbstractSpy[] spies = new AbstractSpy[10];
private int i = 0;
public void addSpy(AbstractSpy s) {
if (i < spies.length) {
spies[i] = s;
System.out.println("spy added at index " + i);
i++;
}
}
}
public class TestClass
{
public static void main(String[] args) {
ConcreteSubject cs = new ConcreteSubject();
AbstractSpy spies = new AbstractSpy() {
#Override
public void addSpy(AbstractSpy spies) {
}
};
cs.addSpy(cs);
spies.addSpy(spies);
}
}
It seems like your program logic is a little borked. This bit in particular doesn't make much sense:
***AbstractSpy spies = new AbstractSpy() {
#Override
public void addSpy(AbstractSpy spies) {
}
};
cs.addSpy(cs);
***spies.addSpy(spies);
What you're doing is creating TWO AbstractSpy instances, one named cs and one named spies. On that last line you're adding spies to itself! That doesn't help you at all.
Note that AbstractSpy is the most granular unit in your setup - it shouldn't have an addSpy() method and its own internal array, it should be the thing that's added to something else's array!
Here's the same code, but cleaned up a bit:
public abstract class AbstractSpy { }
public class ConcreteSpy extends AbstractSpy { }
public class ConcreteSubject {
private AbstractSpy[] spies = new AbstractSpy[10];
private int i = 0;
public void addSpy(AbstractSpy spy) {
if (i < spies.length)
{
spies[i] = spy;
System.out.println("spy added at index " + i);
i++;
}
}
}
public class TestClass {
public static void main(String[] args) {
ConcreteSubject cs = new ConcreteSubject();
AbstractSpy spy = new ConcreteSpy();
cs.addSpy(spy);
}
}
The big difference here is that ConcreteSpy is an implementation of AbstractSpy that you can add to your ConcreteSubject's array of spies. I think you might have been confused by Java's insistence that you can't create an instance of an abstract class on its own unless you supply an anonymous class that inherits from the abstract class.

How do I use value from one class for another class Calling from main method

One.java
public class One {
String asd;
public class() {
asd="2d6"
}
public static void main(String args[]) {
Two a = new Two();
}
}
Two.java
public class Two {
ArrayList<String>data;
String asd;
public Two(String asd){
this.asd=asd;
data.add(this.asd);
}
}
How do I use this asd value of second for third class calling from first class's main method.
**Third class**
Per comments of #Maroun Maroun and #Bennyz, you can create a getter and setter method in your Two class:
import java.util.ArrayList;
public class Two {
ArrayList<String> data;
String asd;
public Two(String asd) {
this.asd = asd;
data = new ArrayList<>(); //<-- You needed to initialize the arraylist.
data.add(this.asd);
}
// Get value of 'asd',
public String getAsd() {
return asd;
}
// Set value of 'asd' to the argument given.
public void setAsd(String asd) {
this.asd = asd;
}
}
A great site to learn about this while coding (so not only reading), is CodeAcademy.
To use it in a third class, you can do this:
public class Third {
public static void main(String[] args) {
Two two = new Two("test");
String asd = two.getAsd(); //This hold now "test".
System.out.println("Value of asd: " + asd);
two.setAsd("something else"); //Set asd to "something else".
System.out.println(two.getAsd()); //Hey, it changed!
}
}
There are also some things not right about your code:
public class One {
String asd;
/**
* The name 'class' cannot be used for a method name, it is a reserved
* keyword.
* Also, this method is missing a return value.
* Last, you forgot a ";" after asd="2d6". */
public class() {
asd="2d6"
}
/** This is better. Best would be to create a setter method for this, or
* initialize 'asd' in your constructor. */
public void initializeAsd(){
asd = "2d6";
}
public static void main(String args[]) {
/**
* You haven't made a constructor without arguments.
* Either you make this in you Two class or use arguments in your call.
*/
Two a = new Two();
}
}
Per comment of #cricket_007, a better solution for the public class() method would be:
public class One {
String asd;
public One(){
asd = "2d6";
}
}
This way, when an One object is made (One one = new One), it has a asd field with "2d6" already.

Should I use an anonymous inner class to simulate 'out' parameters in Java?

I'm still a relative newbie when it comes to Java, coming mainly from a C# background.
I was discussing the lack of 'out' parameters in Java methods with a colleague and how to work around this. He suggested creating a structure/class to hold the various parameters and passing it back.
Sometimes this feels 'wrong' to me - especially if I have a special method that I want to use to return a subset of parameters from a larger class.
So I wondered about using anonymous inline classes instead to achieve this. Code sample below.
Is this a sensible approach? Just wondering what the perceived wisdom is on this.
public class MyClass {
Patient myPatient = null;
// An interface to enable us to return these variables in a single call
public interface VitalStatsResponse { public void returnStats(int bloodPressure, int heartRate); }
public class Patient {
int bloodPressure = 100;
int heartRate = 280;
// Lots of other variables here
public void calculateVitalStats(VitalStatsResponse response)
{
response.returnStats((bloodPressure * 2), (heartRate / 10) ;
}
}
public void doWork()
{
// We want the patient's blood pressure and heart rate returned by a single method call, so use an anonymous inline class
myPatient.calculateVitalStats(new VitalStatsResponse() {
#Override
public void returnStats(int bloodPressure, int heartRate) {
// Handle returned variables here
}
});
}
}
I would go for the simple solution of creating a VitalStats object. If you need the VitalStatus of a patient, then VitalStats is a concept in your application that can be represented as an Object.
public class VitalStatus {
final int bloodPressure;
final int heartRate;
public VitalStats(int bloodPressure, int heartRate) {
this.bloodPressure = bloodPressure;
this.heartRate = heartRate;
}
}
public class Patient {
int bloodPressure = 100;
int heartRate = 280;
// Other variables
public VitalStatus getVitalStatus() {
return new VitalStats(bloodPressured * 2, heartRate / 2);
}
}
Out params is a procedural solution for return times. Java primarily fits the Object Oriented paradigm of programming and as such don't be afraid to make objects. This fits with the S in SOLID if your class is doing a lot of complex things see if you can break it down into smaller more manageable pieces.
I would also use "class to hold the parameters" over "inline anonymous inner class"
public class MyClass implements VitalStatsResponse{
Patient myPatient = null;
private ArrayList<VitalStatsResponse> response;
void MyClass(ArrayList<VitalStatsResponse> response) {
this.response = response;
}
public class Patient {
int bloodPressure = 100;
int heartRate = 280;
// Lots of other variables here
public void calculateVitalStats()
{
for(int i = 0; i < response.length; i++) {
// call returnStats method of every registered callback
response.get(i).returnStats((bloodPressure * 2), (heartRate / 10) ;
}
}
}
// any client can register/unregister callback via these methods
void registerResponse(VitalStatsResponse response) {
this.response.add(response);
}
void unRegisterResponse(VitalStatsResponse response) {
this.response.remove(response);
}
public void doWork()
{
// We want the patient's blood pressure and heart rate returned by a single method call, so use an anonymous inline class
myPatient.calculateVitalStats();
}
public void returnStats(int bloodPressure, int heartRate) {
// implement the body according to this class requirement
}
}

Java "Zero-Argument" Error

I'm building a simulation game using Java. I have an interface, "Critter" and an abstract class "AbstractCritter". All of my "critters" are defined using these two.
Critter
public interface Critter {
// create constants
// each holds a unique integer value
final int NORTH = 1;
final int WEST = 2;
final int SOUTH = 3;
final int EAST = 4;
final int CENTER = 5;
// create abstract methods
public char getChar();
public int getMove(CritterInfo theInfo);
}
AbstractCritter
public abstract class AbstractCritter implements Critter{
// create char to hold a particular critter
private char critterChar;
public AbstractCritter(final char theChar) {
critterChar = theChar;
}
public char getChar() {
return critterChar;
}
}
Example critter:
public class Stone extends AbstractCritter {
public Stone(char S) {
super(S);
// This is the main constructor for stone
}
public int getMove(CritterInfo theInfo) {
// The stone cannot move.
return 5;
}
}
And the main loop:
public final class CritterMain {
/** private constructor to inhibit instantiation. */
private CritterMain() {
// Do not instantiate objects of this class
throw new IllegalStateException();
}
/**
* The start point for the CritterMain application.
*
* #param theArgs command line arguments - ignored
*/
public static void main(String[] theArgs) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
CritterFrame frame = new CritterFrame();
frame.add(100, Stone.class);
frame.add(50, Bat.class);
frame.add(25, Frog.class);
frame.add(25, Mouse.class);
frame.add(25, Turtle.class);
frame.add(25, Wolf.class);
frame.start();
}
});
}
}
Whenever I try to run the main CritterMain, I get this weird error I can't find anywhere on google: "Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: no zero-argument constructor for class Stone"
It has something to do with how I am defining my critters. Can anyone help me figure this out?
When you make an instance of a class, you may use one of the available constructors.
A constructor may have no arguments, or more than zero arguments.
In case you don't declare a constructor with no argument and attempt to instantiate a class with no arguments, you obviously get an an error.
So just making a constructor with no arguments, will stop the error.

Printing a list array which uses threads to a text area in java

I am having problems storing and printing a list array which uses threads. I want to store the list of threads in a list array and print them to a text area where they can be sorted by a user. The code below is my array class and transaction class.
import java.util.ArrayList;
/**
* #author B00533474
*/
public class Array {
ArrayList<Transaction> transactionList = new ArrayList<Transaction>();
// Variables
private final Transaction nextTransaction;
public static int inInt2 = TranAcc.inInt2;
public static int inInt3 = TranAcc.inInt3;
public static String inInt1 = TranAcc.inInt1;
//public static void main(String[] args){
public Array(){
nextTransaction = new Transaction(inInt1, inInt2, inInt3, 2000);
transactionList.add(nextTransaction);
transactionList.get(3);
}
/*public static void main(String[] args){
Array ar = new Array();
ar.add(nextTransaction);
}
*
*/
}
The variables inInt1 etc are from another class called TranAcc which is the main GUI of my project.
package bankassig;
/**
*
* #author B00533474
*/
public class Transaction {
String type;
int amount;
int wkNum;
int balance;
public Transaction(String ty, int am, int wk, int bal)
{
type = ty;
amount = am;
wkNum = wk;
balance = bal;
}
}
My problem is actually implementing/using the list area, I was going to add an action listener to a button on a gui which would call the list area and print the transactions in a text are but I was unsure of the code to write for this ( I know about the action listener just not calling the list array).
Any help would be much appreciated and if I need to provide anymore code I would be happy to do so.
How do I implement the list array and use it to print out the values of the variables which I used?
Overwrite the inherited (from java.lang.Object) toString() method in your Transaction class. In your toString() method, you can put together a String with your variable data in any format that makes sense to a user, and return it. You can then iterate through all the Transactions in your Array class's list, call the toString() method, and put it in your GUI. Something like:
for (Transaction trans : yourArrayObj)
{
yourTextArea.append(trans.toString());
}

Categories