Storing multiple values from the same object in an Array - java

I am trying to create an Array with all these values form the Detail Class. Is there a better way of creating this array?
Details[] DetailsArray = new Details[10];
Details Details = new Details();
Details Details2 = new Details();
Details Details3 = new Details();
Details Details4 = new Details();
Details Details5 = new Details();
Details Details6 = new Details();
Details.setNumber(new Integer(1));
Details2.setEmployeeID(new Double(300));
Details3.setCurrency("Euro");
Details4.setSize(new Double (400));
Details5.setEvent("Something");
Details6.setId(new Integer(10));
DetailsArray[0] = Details;
DetailsArray[1] = Details2;
DetailsArray[2] = Details3;
DetailsArray[3] = Details4;
DetailsArray[4] = Details5;
DetailsArray[5] = Details6;
System.out.println(DetailsArray);
EmployeeDetails.setDetails(DetailsArray);

Use a for loop?
Details[] detailsArray = new Details[10];
for (int i = 0; i < detailsArray.length; i++)
detailsArray[i] = new Details();
detailsArray[0].setNumber(New Integer(1));
...
That being said ... rarely in real code would you have a static array that you're populating like this manually. If you did, you might want to have the data for those objects in an external file, or really some other data structure completely.

Well it's pretty odd code to start with to be honest, but this would work:
// Why are you creating an array with 10 elements but only using 6?
Details[] detailsArray = new Details[10];
for (int i = 0; i < 6; i++) {
detailsArray[i] = new Details();
}
detailsArray[0].setNumber(new Integer(1));
detailsArray[1].setEmployeeID(new Double(300));
detailsArray[2].setCurrency("Euro");
detailsArray[3].setSize(new Double (400));
detailsArray[4].setEvent("Something");
detailsArray[5].setId(new Integer(10));
Do you really want to set a different property on each object? Are you sure you don't really want to set multiple properties on a single object?

You could use a list instead of an array, but if I understand what you are trying to achieve, you maybe want this instead, where your details object holds all the information for that employee:
Details details = new Details();
details.setNumber(new Integer(1));
details.setEmployeeID(new Double(300));
details.setCurrency("Euro");
details.setSize(new Double (400));
details.setEvent("Something");
details.setId(new Integer(10));
System.out.println(details);
EmployeeDetails.setDetails(details);

Create constructor that accepts all needed parameters. Then do something like this:
deatilsArray = new DetailsArray[] {
new Details(1, 300, "Euro", 400, "Something"),
new Details(2, 400, "Dollar", 500, "Something else"),
..................
};
Alternatively you can create other class DetailsBuilder that initiates details' fields:
Details d =
new DetailsBuilder().create().setName("aaa").setEmployeeId(123).setCurrency("Euro").getInstance();
In this case the code above will look like:
DetailsBuilder builder = new DetailsBuilder();
deatilsArray = new DetailsArray[] {
builder.create().setName("aaa").setEmployeeId(123).setCurrency("Euro").getInstance(),
builder.create().setName("bbb").setEmployeeId(123).setCurrency("Euro").getInstance(),
};
BTW according to java naming convention variable names always start with small letter.

Solution using a temporary inner class.
class Pwn {
final Details d = new Details();
}
Details[] detailsArray = new Details[] {
(new Pwn (){{ d.setNumber(new Integer(1)); }}).d,
(new Pwn (){{ d.setEmployeeID(new Double(300)); }}).d,
(new Pwn (){{ d.setCurrency("Euro"); }}).d,
(new Pwn (){{ d.setSize(new Double (400)); }}).d,
(new Pwn (){{ d.setEvent("Something"); }}).d,
(new Pwn (){{ d.setId(new Integer(10)); }}).d
}
:)

Related

Custom DataProvider Nattable

I create nattable the following way. But I can get access to the cells only through getters and setters in my Student class. How else can I access cells? Should I create my own BodyDataProvider or use IDataProvider? If it is true, could someone give some examples of implementing such providers?
final ColumnGroupModel columnGroupModel = new ColumnGroupModel();
ColumnHeaderLayer columnHeaderLayer;
String[] propertyNames = { "name", "groupNumber", "examName", "examMark" };
Map<String, String> propertyToLabelMap = new HashMap<String, String>();
propertyToLabelMap.put("name", "Full Name");
propertyToLabelMap.put("groupNumber", "Group");
propertyToLabelMap.put("examName", "Name");
propertyToLabelMap.put("examMark", "Mark");
DefaultBodyDataProvider<Student> bodyDataProvider = new DefaultBodyDataProvider<Student>(students,
propertyNames);
ColumnGroupBodyLayerStack bodyLayer = new ColumnGroupBodyLayerStack(new DataLayer(bodyDataProvider),
columnGroupModel);
DefaultColumnHeaderDataProvider defaultColumnHeaderDataProvider = new DefaultColumnHeaderDataProvider(
propertyNames, propertyToLabelMap);
DefaultColumnHeaderDataLayer columnHeaderDataLayer = new DefaultColumnHeaderDataLayer(
defaultColumnHeaderDataProvider);
columnHeaderLayer = new ColumnHeaderLayer(columnHeaderDataLayer, bodyLayer, bodyLayer.getSelectionLayer());
ColumnGroupHeaderLayer columnGroupHeaderLayer = new ColumnGroupHeaderLayer(columnHeaderLayer,
bodyLayer.getSelectionLayer(), columnGroupModel);
columnGroupHeaderLayer.addColumnsIndexesToGroup("Exams", 2, 3);
columnGroupHeaderLayer.setGroupUnbreakable(2);
final DefaultRowHeaderDataProvider rowHeaderDataProvider = new DefaultRowHeaderDataProvider(bodyDataProvider);
DefaultRowHeaderDataLayer rowHeaderDataLayer = new DefaultRowHeaderDataLayer(rowHeaderDataProvider);
ILayer rowHeaderLayer = new RowHeaderLayer(rowHeaderDataLayer, bodyLayer, bodyLayer.getSelectionLayer());
final DefaultCornerDataProvider cornerDataProvider = new DefaultCornerDataProvider(
defaultColumnHeaderDataProvider, rowHeaderDataProvider);
DataLayer cornerDataLayer = new DataLayer(cornerDataProvider);
ILayer cornerLayer = new CornerLayer(cornerDataLayer, rowHeaderLayer, columnGroupHeaderLayer);
GridLayer gridLayer = new GridLayer(bodyLayer, columnGroupHeaderLayer, rowHeaderLayer, cornerLayer);
NatTable table = new NatTable(shell, gridLayer, true);
As answered in your previous question How do I fix NullPointerException and putting data into NatTable, this is explained in the NatTable Getting Started Tutorial.
If you need some sample code try the NatTable Examples Application
And from knowing your previous question, your data structure does not work in a table, as you have nested objects where the child objects are stored in an array. So this is more a tree and not a table.

Convert string to object name Java

it might be a simple question or even impossible without any kind of Interface (Arrays, Maps etc.) but I would like to know if there's any possibility of converting an object name to String so I can pass as argument. I have two classes Paciente and Sintomas with multiple objects that I need to pass as argument to a function but I don't want to use arrays (it must be like that) and I can't figure any other way of doing so without manually make an insert for each one.
Paciente Paciente1 = new Paciente("001", "Ana Melo", 33, "");
Paciente Paciente2 = new Paciente("002", "Rui Costa", 13, "");
Paciente Paciente3 = new Paciente("003", "Joana Martins", 85, "");
Paciente Paciente4 = new Paciente("004", "Pedro Torres", 53, "");
Paciente Paciente5 = new Paciente("005", "Ana Gomes", 93, "");
Paciente Paciente6 = new Paciente("006", "Jorge Costa", 56, "");
Sintomas Sintoma1 = new Sintomas("001", "febre");
Sintomas Sintoma2 = new Sintomas("001", "dores");
Sintomas Sintoma3 = new Sintomas("001", "machas");
Sintomas Sintoma4 = new Sintomas("002", "febre");
Sintomas Sintoma5 = new Sintomas("002", "manchas");
Sintomas Sintoma6 = new Sintomas("003", "febre");
Sintomas Sintoma7 = new Sintomas("003", "dores");
Sintomas Sintoma8 = new Sintomas("004", "febre");
Sintomas Sintoma9 = new Sintomas("006", "manchas");
Sintomas Sintoma10 = new Sintomas("006", "dores");
// now I would like to pass to a function as argument something like this:
for(int i = 0 ; i < 6 ; i++)
kSession.insert("Paciente"+(i+1));
// instead of making
kSession.insert(Paciente1);
kSession.insert(Paciente2);
kSession.insert(Paciente3);
// and so on.
Something like this should work(asuming you mean no array because of size constraints), note that there has to be somewhere you add the data, it's also possible to load it from a txt or something, but it has to be defined at some point
List<Paciente> pacientes = new ArrayList<>(); // no size constraints, automatically expands if too small
pacientes.add(new Paciente("", "", ""));
for (Paciente paciente : pacientes) { // loop all Patientes in pacientes
kSession.insert(paciente); // add a paciente to the session, for every entry
}
ofcource same can be done for any class, or object
It all really comes down to, how do you wish to store and access the data, and where do you need to store and access it. Using ArrayList and Map's offer the utility of easily changing the size and content of a list of data, but as any data it must be initially inserted
As a side note if the patients have an ID then using a Map
Map<String, Paciente> pacientes = new HashMap<>();
provides a way to acces the patiens very fast, and the TreeMap structure is sorted on key, should that be needed.
Other options could be
Wrapper classes that manage the data, will work similarily to an ArrayList<> but you can define, rules for adding, deleting, and such from the list.
public class Wrapper{
private List<Paciente> pacientes = new ArrayList<>();
public void addPaciente(Paciente paciente){
if(!this.pacientes.contains(paciente)) // prevent multi entries
paciente.add(paciente);
}
public void addPacientes(List<Paciente> pacientes){
for(Paciente paciente : pacientes) // add all patients using the add method
this.addPaciente(paciente);
}
public List<Paciente> getPacientes(){
return this.pacientes;
}
}
You can then add the patients to the kSession, as earlier described
Finally, there is no reason why Paciente, can have the list of Sintomas, such that
public class Paciente{
private List<Sintomas> sintomas = new ArrayList<>();
public addSintomas(Sintomas sintomas){
if(!this.sintomas.contains(sintomas))
this.sintomas.add(sintomas);
}
// rest is the same principle as above in "Wrapper"
}
This way you can get a Paciente, and add a Sintomas, and then when you wish to check a Pacientes Sintomas you can just get the list of Sintomas from that Paciente

RandomForest with Weka in Java

I am working on a project and I need some examples how to implement RandomForest in Java with weka? I did it with IBk(), it worked. If I do it with RandomForest in the same way, it does not work.
Does anyone have a simple example for me how to implement RandomForest and how to get probability for each class (i did it with IBk withclassifier.distributionForInstance(instance) Function and it returned me probabilities for each class). How can I do it for RandomForest? I will need to get probability of every tree and to combine it?
//example
ConverrterUtils.DataSource source = new ConverterUtils.DataSource ("..../edit.arff);
Instances dataset = source.getDataSet();
dataset.setClassIndex(dataset.numAttributes() - 1);
IBk classifier = new IBk(5); classifier.buildClassifier(dataset);
Instance instance = new SparseInstance(2);
instance.setValue(0, 65) //example data
instance.setValue(1, 120); //example data
double[] prediction = classifier.distributionForInstance(instance);
//now I get the probability for the first class
System.out.println("Prediction for the first class is: "+prediction[0]);
You can calculate the the infogain while buidling the Model in the RandomForest. It is much slower and requires alot of memory while buidling model. I am not so sure about the documentation. you can add options or setValues while buiilding the model.
//numFolds in number of crossvalidations usually between 1-10
//br is your bufferReader
Instances trainData = new Instances(br);
trainData.setClassIndex(trainData.numAttributes() - 1);
RandomForest rf = new RandomForest();
rf.setNumTrees(50);
//You can set the options here
String[] options = new String[2];
options[0] = "-R";
rf.setOptions(options);
rf.buildClassifier(trainData);
weka.filters.supervised.attribute.AttributeSelection as = new weka.filters.supervised.attribute.AttributeSelection();
Ranker ranker = new Ranker();
InfoGainAttributeEval infoGainAttrEval = new InfoGainAttributeEval();
as.setEvaluator(infoGainAttrEval);
as.setSearch(ranker);
as.setInputFormat(trainData);
trainData = Filter.useFilter(trainData, as);
Evaluation evaluation = new Evaluation(trainData);
evaluation.crossValidateModel(rf, trainData, numFolds, new Random(1));
// Using HashMap to store the infogain values of the attributes
int count = 0;
Map<String, Double> infogainscores = new HashMap<String, Double>();
for (int i = 0; i < trainData.numAttributes(); i++) {
String t_attr = trainData.attribute(i).name();
//System.out.println(i+trainData.attribute(i).name());
double infogain = infoGainAttrEval.evaluateAttribute(i);
if(infogain != 0){
//System.out.println(t_attr + "= "+ infogain);
infogainscores.put(t_attr, infogain);
count = count+1;
}
}
//iterating over the hashmap
Iterator it = infogainscores.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey()+" = "+pair.getValue());
System.out.println(pair.getKey()+" = "+pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}

RunTime error solution

I have all the classes compiled and i create an array of Items(superclass of all) and i put different kinds of products:
aItems[1] = new Motherboard("970a",2014,200.0,"GIGABYTE","INTEL",64,5);
aItems[2] = new Motherboard("gb4",2012,150.0,"ASROCK","AMD",32,4);
aItems[3] = new Proccesor("I5",2010,180.0,"INTEL",3.3,4);
aItems[4] = new Proccesor("I7",2014,900.0,"INTEL",4.0,4);
aItems[5] = new Gcard("RADEON",2012,300.0,"GIGABYTE","AMD",4) ;
aItems[6] = new Gcard("RADEON",2010,200.0,"SAPPHIRE","NVIDIA",2);
aItems[7] = new Ram("IO",2010,100.0,"ASUS","DDR",4,1600);
aItems[8] = new Ram("RADIOACTIVE X",2012,160.0,"CRUCIAL","DDR3",8,2000);
aItems[9] = new HardDrive("E2",2013,100.0,"WD","SSD",2.5,750);
aItems[10] = new HardDrive("LM",2012,150.0,"HP","HDD",3.5,1000) ;
aItems[11] = new Monitor("CFA90",2014,180.0,"SAMSUNG","LCD","23,5","1080","HDMI");
aItems[12] = new Monitor("27EA",2013,280.0,"ASUS","LED","28","1080","HDMI");
aItems[13] = new Mouse("Taipan",2013, 80.0, "Razer","Optical", "wired");
aItems[14] = new Mouse("M9Q",2013, 80.0, "Microsoft","laser", "wireless");
aItems[15] = new Keyboard("Blackwidow", 2014, 130.0, "Razer", "wired");
aItems[16] = new Keyboard("GK10", 2013, 100.0, "CM Storm", "wireless");
aItems[17] = new Printer("PS3H", 2012, 90.0, "HP", "laser" , "colored");
aItems[18] = new Printer("SPP5", 2013, 190.0, "SAMSUNG", "inkjet" , "black and white");
Then i want to take each object of the array and by calling methods get i want to create a txt file with the details of these items. But it gives me this runtime error:
Exception in thread "main" java.lang.ClassCastException: Keyboard cannot be cast
to Mouse
at mainApp3.run(mainApp3.java:930)
at acm.program.Program.runHook(Program.java:1592)
at acm.program.Program.startRun(Program.java:1581)
at acm.program.Program.start(Program.java:838)
at acm.program.Program.start(Program.java:1250)
at acm.program.Program.main(Program.java:1340)
You're trying to cast the Keyboard class to Mouse. Something like
Keyboard kybrd = new Keyboard();
Mouse mse = (Mouse) kybrd;
Something like that, I am not sure what you have there.
And that is causing the expection.
Keyboard cannot be cast to Mouse
You should need to check what is the error that the compiler is showing to you at the line 1006,
at mainApp3.run(mainApp3.java:1006)
It is a reference to the error location. Trying hovering over to it.

How would i go about adding to my array through JOptionpanes?

At the moment I have to manually add items to my array but I would like to enable users to do this themselves perhaps through JOptionPanes, what would be the best way to go about this? Here is my current code.
public class Main {
public static void main(String[] args){
//Create new Person objects
Address p[] = new Address[3];
p[0] = new Address("27","Abbey View","Hexham","NE46 1EQ");
p[1] = new Address("15", "Chirdon Crescent", "Hexham", "NE46 1LE");
p[2] = new Address("6", "Causey Brae", "Hexham", "NE46 1DB");
Details c[] = new Details[3];
c[0] = new Details ("3", "175,000", "Terraced");
c[1] = new Details ("6", "300,000", "Bungalow");
c[2] = new Details ("4", "250,000", "Detached");
//Send some messages to the objects
c[0].setBeds("3 ");
c[1].setBeds("6");
c[2].setBeds("4");
c[0].setPrice("175,000");
c[1].setPrice("300,000");
c[2].setPrice("250,000");
c[0].setType("Terraced");
c[1].setType("Bungalow");
c[2].setType("Detached");
//Set up the association
p[0].ownsDetails(c[0]);
p[1].ownsDetails(c[1]);
p[2].ownsDetails(c[2]);
//print details
p[1].printDetails();
p[2].printDetails();
p[3].printDetails();
}
System.exit(0);
}
}
You could use the showXXXX methods on JOptionPane and keep prompting the user just as you would on the console.
However, I suggest just creating a simple JFrame that would have controls that allows the user to enter multiple items instead of showing one dialog after another.

Categories

Resources