Loading hashmap values in another method - java

I've a method called setupTroop that stores the data through hashmap. How do I go about loading this data in getTroopDetails, so whenever the key has been called, its value gets loaded.
So if the key IW1 gets called, the values 1, "Twisters", 200, 200 are outputted and if any other key gets called it gives the output "No such troop".
private void setupTroop()
{
HashMap<String, troop>Troop= new HashMap<String, troop>();
Troop.put("IW1", new troop(1, "Twisters", 200, 200));
}
public String getForceDetails(String ref)
{
return "\nNo such force";
}
public class troop{
int FleetRef;
String FullName;
int ActivationFee;
int BattleStrength;
public troop(int FRef, String FName, int AFee, int BStrength)
{
FleetRef = FRef;
FullName = FName;
ActivationFee = AFee;
BattleStrength = BStrength;
}
public int getFleetRef()
{
return FleetRef;
}
public String getFullName()
{
return FullName;
}
public int getActivationFee()
{
return ActivationFee;
}
public int BattleStrength()
{
return BattleStrength;
}

It's impossible to return a non string object on a String method. But there is a way of returning a troop if the "IW1" key is called.
The way of doing it is declaring the Troop HashMap outside of the setupTroop method, and then creating it inside the setupTroop method, like this:
HashMap<String, troop> Troop;
//Code you have
private void setupTroop() {
Troop = new HashMap<String, troop>();
Troop.put("IW1", new troop(1, "Twisters", 200, 200));
}
//Other code
public troop getForceDetails(String ref) {
if(ref.equals("IW1") {
return Troop.get(ref);
}
return null;
}
Then in whatever other method you have where you called the getForceDetails() method, you would have
if(getForceDetails("Some string") == null) {
doSomething;
}

Related

How to add parent class attributes to sub class

I have a parent class named Set representing a set of a tennis matches.
public class Set {
private String set1;
private String set2;
private String set3;
//private Object[] match;
public Set() {
setSet1(set1);
setSet2(set2);
setSet3(set3);
}
public void setSet1(String set1) {
this.set1 = set1;
}
public String getSet1() {
return set1;
}
public void setSet2(String set2) {
this.set2 = set2;
}
public String getSet2() {
return set2;
}
public void setSet3(String set3) {
this.set3 = set3;
}
public String getSet3() {
return set3;
}
public String toString(){
return String.format("set1: %s, set2: %s, set3: %s", set1, set2, set3);
}
}
and a sub class of Set named SingleSet where I try to add the sets into an array named `game.
public class SingleSet extends Set{
private Object homePlayer;
private Object awayPlayer;
private String[] game;
public SingleSet(Object homePlayer, Object awayPlayer){
super();
game = new String[3];
game[0] = super.getSet1();
game[1] = super.getSet2();
game[2] = super.getSet3();
setHomePlayer(homePlayer);
setAwayPlayer(awayPlayer);
}
public void setHomePlayer(Object homePlayer) {
this.homePlayer = homePlayer;
}
public Object getHomePlayer() {
return homePlayer;
}
public void setAwayPlayer(Object awayPlayer) {
this.awayPlayer = awayPlayer;
}
public Object getAwayPlayer() {
return awayPlayer;
}
public void setGame(String[] game) {
this.game = game;
}
public String[] getGame() {
return game;
}
public String toString(){
return String.format("Player: %s Vs. Player: %s, Single set game: %s, %s, %s", homePlayer, awayPlayer, game[0], game[1], game[2]);
}
}
This is where I am trying to add the Sets from my parents class into my sub class (this is for FXML, so the code is in my controller):
public void submit() {
SingleSet game1 = new SingleSet(homePlayer1Dropdown.getValue(), awayPlayer1Dropdown.getValue());
game1.setSet1(set1Box1.getText());
game1.setSet2(set1Box2.getText());
game1.setSet3(set1Box3.getText());
System.out.println(game1);
}
When I print the result, my array values are null. I tried printing them individually and that worked fine, so I know the set1Box.getText() is working fine.
The reason you are seeing null values when you print is because they are actually null.
SingleSet game1 = new SingleSet(homePlayer1Dropdown.getValue(), awayPlayer1Dropdown.getValue()); is creating a new SingleSet, which extends Set.
SingleSet constructor makes a super() call to Set constructor.
When Set is created for the first time, all its values are null. Then constructor kicks in, but Set constructor actually does nothing, so Set's instance variables remain null.
Ten SingleSet carries on on building your object with parameter given, which do nothing for setting a value for set1, set2, set3.
game1.setSet1(set1Box1.getText());
game1.setSet2(set1Box2.getText());
game1.setSet3(set1Box3.getText());
They actually set a value to set1, set2, set3 (since you are saying that set1Box1.getText() and others are working). So why you are still seeing null when printing?
public String toString(){
return String.format("Player: %s Vs. Player: %s, Single set game: %s, %s, %s", homePlayer, awayPlayer, game[0], game[1], game[2]);
}
That's why: you are printing game[0], and so on, that are actually null because when you set your game array, those values where null!
public SingleSet(Object homePlayer, Object awayPlayer){
super(); //setting null values to set1, set2, set3
game = new String[3];
game[0] = super.getSet1(); //this returns null!
game[1] = super.getSet2(); //this returns null!
game[2] = super.getSet3(); //this returns null!
setHomePlayer(homePlayer);
setAwayPlayer(awayPlayer);
}
Print some values when you build your object and will see :)
To solve, one way is to use a parametrized constructor public Set(String set1, String set2, String set3), use a parametrized child constructor public SingleSet(String set1, String set2, String set3, Object homePlayer, Object awayPlayer) and a parametrized call to super, super(set1, set2, set3)
Then you should set values when creating game1
SingleSet game1 = new SingleSet(set1Box1.getText(), set1Box1.getText(), set1Box1.getText()homePlayer1Dropdown.getValue(), awayPlayer1Dropdown.getValue());
You are not setting anything in Set's default constructor
Should really find a better name for your class as "Set" is confusing with collections Set.
Make use of immutable for both of your classes to save yourself from trouble - remove all the setters and initialize in constructor.
I'm not that good at tennis scoring rules, but to my best knowledge a "set" has number of "games", and "match" consists from a number of sets. What is the logic for this relation "Set <- SingleSet"? What if you change your hierarchy in this way (in pseudo-code, will skip most method bodies for brevity):
class Player{
private String name;
public Player(String name);
}
class Match{
private Player homePlayer;
private Player awayPlayer;
private List<Set> sets;
public Match(Player homePlayer, Public awayPlayer);
public List<Set> getSets(){
if(sets == null){
sets = new ArrayList<>();
}
return sets;
}
}
class Set{
public Set(Game... games);
}
class Game{
// game score details
public Game(int scoreHomePlayer, int scoreAwayPlayer);
}
So that in your Controller, you could use it like this:
Match match = new Match(new Player("Williams"), new Player("Johnson"))
match.getSets().add(new Set(
new Game(6, 1),
new Game(4, 6),
new Game(7, 0)
// etc.
))
You could further refactor #4 hierarchy and spare all these "new ()" constructor calls using Builder Pattern, something along the line:
Match match = new MatchBuilder("Williams","Johnson").addSet()
.addGame(6,1).addGame(4,6).addGame(7,0)
.build()
you should override set method .Instead of in the set after the constructor is instantiated
public SingleSet(Object homePlayer, Object awayPlayer) {
super();
game = new String[3];
// game[0] = super.getSet1();
// game[1] = super.getSet2();
// game[2] = super.getSet3();
setHomePlayer(homePlayer);
setAwayPlayer(awayPlayer);
}
#Override
public void setSet1(String set1) {
this.game[0]=set1;
super.setSet1(set1);
}
#Override
public void setSet2(String set2) {
this.game[1]=set2;
super.setSet2(set2);
}
#Override
public void setSet3(String set3) {
this.game[2]=set3;
super.setSet3(set3);
}

How to Insert ArrayList data to the DataBase

Im try to insert data into Database using ArrayList.there is a Erro msg.
That is my Custmer.class method. this is what i got from when i going to pass ArrayList into another class.
incompatible types: ArrayList<String> cannot be converted to ArrayList<Inquiries>
I want to know how to do this using correct Using OOP concept
public void passingMsg(ArrayList<Inquiries> arrlist){
try {
System.out.println("Method "+arrlist);
String sq = "INSERT INTO Inquiries (name,mail,tp,msg)VALUES(?,?,?)";
PreparedStatement pr = con.prepareStatement(sq);
for(int i=0;i<arrlist.size();i++){
pr.setString(1,arrlist.get(i).getName());
pr.setString(2,arrlist.get(i).getMail());
pr.setString(3,arrlist.get(i).getTp());
pr.setString(4,arrlist.get(i).getMsg());
}
pr.executeQuery();//executeBatch();
} catch (SQLException ex) {
}
}
and this is how i get values from user
String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<String> arrInq = new ArrayList<String>();
arrInq.add(name);
arrInq.add(mail);
arrInq.add(tp);
arrInq.add(msg);
Custmer c =new Custmer();
if( c.passingMsg(arrInq)){
try {
JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unsuccesss!!");
e.printStackTrace();
}
}
and this is my Inquiries.class :
public class Inquiries {
private String name;
private String mail;
private String tp;
private String msg;
public Inquiries(String name,String mail,String tp,String msg){
this.name = name;
this.mail = mail;
this.tp = tp;
this.msg = msg;
}
//
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTp() {
return tp;
}
public void setTp(String tp) {
this.tp = tp;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
Can Some one please explain whats wrong with this. please ?
Reason For Error
This was simply telling you that your types were incompatible for the operation you were trying to perform. In your passingMsg() method, you have its header as: public void passingMsg(ArrayList<Inquiries> arrlist). However, inside your "how i get values from user" area, which I will now refer to as "2nd Snippet", you have your method call declared as: if( c.passingMsg(arrInq)). This means that you are implying that your parameter being passed, arrInq in this case, is of the type ArrayList<Inquiries>, but it's not. It's being initialized in your 2nd Snippet as: ArrayList<String> arrInq = new ArrayList<String>();
Simple Fix
I take no responsibility for this code; use at your own risk. To fix this, you would want to change that entire 2nd Snippet to something similar to the following:
String name = txtName.getText();
String mail = txtEmail.getText();
String tp = txtTp.getText();
String msg = txtMsg.getText();
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));
Custmer c = new Custmer();
try {
c.passingMsg(arrInq);
JOptionPane.showMessageDialog(this, "Successs!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Unsuccesss!!");
e.printStackTrace();
}
You would also want to change the method header to either return a boolean, or fix it up a little bit to actually throw the exception. Such as:
public void passingMsg(ArrayList<Inquiries> arrlist) {
System.out.println("Method " + arrlist);
String sq = "INSERT INTO Inquiries(name,mail,tp,msg) VALUES(?,?,?)";
PreparedStatement pr = con.prepareStatement(sq);
for (Inquiries inquiries : arrlist) {
pr.setString(1, inquiries.getName());
pr.setString(2, inquiries.getMail());
pr.setString(3, inquiries.getTp());
pr.setString(4, inquiries.getMsg());
}
pr.executeQuery();//executeBatch();
}
Let's talk in O-O-P way.
Here Inquiries is your model, model is nothing but simple class that has instance members and public methods to get and set value of model's instance variable.
Generally we put all database related operations code in their respective models.
e.g. I have model "Model" which typically maps to database table say it as "TableModel" ,I would do something like this:
public class Model{
private int id;
private String attr;
//other properties of the model
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
//other getters and setters
//here we write methods to performs database operations
public void save(){
//use "this" to get properties of object
//logic to save to this object in database table TableModel as record
}
public void delete(int id){
//logic to delete this object i.e. from database table TableModel
}
public Model get(int id){
//retrieve record from table TableModel with this id
}
//other methods to get data from database.
}
Now question is how I can use this in some another class. Let's say I have list of Model objects and I wish to insert them in to database.I will do it something like this:
public class AnotherClass{
public void someMethod(){
//create list of models objects e.g. get them from user interface
ArrayList<Model> models=new ArrayList<>();
for(int i=0;i<3;i++){
Model model=new Model();
model.setId(i);
model.setAttr("attr"+i);
models.add(model);
}
SomeOtherClass obj=new SomeOtherClass();
obj.insert(models);
}
}
public class SomeOtherClass{
//other code above.....
//my method that inserts each Model object in database
//Note: this is sample method , you should do it in optimized way
// e.g. batch insert
public void insert(ArrayList<Model> models){
for(Model myModel:models){
myModel.save();
}
}
//other code below.....
}
You are using the wrong type parameter for the ArrayList. Instead of ArrayList<String> you need ArrayList<Inquiries>. To fix the problem, you should remove this code ...
ArrayList<String> arrInq = new ArrayList<String>();
arrInq.add(name);
arrInq.add(mail);
arrInq.add(tp);
arrInq.add(msg);
... and replace it with this code:
ArrayList<Inquiries> arrInq = new ArrayList<Inquiries>();
arrInq.add(new Inquiries(name, mail, tp, msg));

Sorting ArrayList Hashmap

I have an ArrayList<HashMap<String,String>> and I want to sort it. My ArrayList output in Logcat is like this:
[{num=0, username=p, startPoliPro=A, finalPoliPro=B, diff=0},
{num=1, username=e, startPoliPro=C, finalPoliPro=D, diff=548.0Km},
{num=2, username=e, startPoliPro=E, finalPoliPro=F, diff=3.0Km}]
I want to sort the list based on "diff" value by ascending order so that Logcat has to be like:
[{num=0, username=p, startPoliPro=A, finalPoliPro=B, diff=0},
{num=2, username=e, startPoliPro=E, finalPoliPro=F, diff=3.0Km},
{num=1, username=e, startPoliPro=C, finalPoliPro=D, diff=548.0Km}]
I have read many similar topics and tried something like
Collections.sort(final_itinList, new Comparator<HashMap< String,String >>() {
#Override
public int compare(HashMap<String, String> lhs, HashMap<String, String> rhs) {
// Do your comparison logic here and retrn accordingly.
return lhs.get("diff").compareTo(rhs.get("diff"));
}
});
with no success. Any help would be appreciated
Currently, you are trying to compare two String Objects:
return lhs.get("diff").compareTo(rhs.get("diff"));
What you really want to do is comparing the returned Integers, so you would need to do something like this:
return (Integer.parseInt(lhs.get("diff")) - Integer.parseInt(rhs.get("diff")));
Your Comparator is comparing two Strings. That's probably why the list is not sorted correctly. The "diff" string should be parsed as an integer (or float) to compare it.
If your objects always have the same structure, I would advise to create a List of a custom object (where the diff is an integer representing the number of kilometers) instead of using a List of Maps. In that case, you could make your custom object implement Comparable.
Something like :
public class MyCustomObject implements Comparable<MyCustomObject> {
private String mNum;
private String mUsername;
private String mStartPoliPro;
private String mFinalPoliPro;
private int mDiff;
#Override
public int compareTo(MyCustomObject another) {
return mDiff - another.getDiff();
}
public String getNum() {
return mNum;
}
public void setNum(String num) {
mNum = num;
}
public String getUsername() {
return mUsername;
}
public void setUsername(String username) {
mUsername = username;
}
public String getStartPoliPro() {
return mStartPoliPro;
}
public void setStartPoliPro(String startPoliPro) {
mStartPoliPro = startPoliPro;
}
public String getFinalPoliPro() {
return mFinalPoliPro;
}
public void setFinalPoliPro(String finalPoliPro) {
mFinalPoliPro = finalPoliPro;
}
public int getDiff() {
return mDiff;
}
public void setDiff(int diff) {
mDiff = diff;
}
}
and then simply call
List<MyCustomObject> myList = // create your object list
Collections.sort(myList);

Java Swing Object[][] getData() confusion

Hi I'm having some trouble getting started with a problem in a Java course learning Swing and starting on JTables and getting data into them. It's going to be hard to explain so I'm just going to post the code I was given, along with the question.
The question is:
The getData() method needs to return an Object[][] containing the data represented by the class.
The first class is MusicAlbum
class MusicAlbum {
private String id;
private String name;
private String genre;
private boolean isCompilation;
private int track_count;
public MusicAlbum(String id, String name, String genre, boolean isCompilation, int track_count) {
this.id = id;
this.name = name;
this.genre = genre;
this.isCompilation = isCompilation;
this.track_count = track_count;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getGenre() {
return genre;
}
public boolean isCompilation() {
return isCompilation;
}
public int getTrackCount() {
return track_count;
}
public boolean equals(Object obj) {
if (obj instanceof MusicAlbum)
return this.id.equalsIgnoreCase(((MusicAlbum)obj).id);
return super.equals(obj);
}
}
The class I have to implement the methods in is MusicDataObject (at the bottom)
import java.util.Random;
import java.util.Scanner;
public class MusicDataObject {
private List<MusicAlbum> albums = new ArrayList<>();
private Random random = new Random(); // for generating IDs
public void addAlbum(MusicAlbum album) throws IllegalArgumentException {
if (searchAlbum(album.getId()) != null)
throw new IllegalArgumentException("Album ID is not new!");
albums.add(album);
}
public MusicAlbum searchAlbum(String id) {
for (MusicAlbum album : albums) {
if (album.getId().equalsIgnoreCase(id)) {
return album;
}
}
return null;
}
public MusicAlbum removeAlbum(String id) {
MusicAlbum album = searchAlbum(id);
albums.remove(album);
return album;
}
public void updateAlbum(MusicAlbum album)
throws IllegalArgumentException {
if (removeAlbum(album.getId()) == null)
throw new IllegalArgumentException("Album ID does not exist!");
addAlbum(album);
}
public String generateID() {
String formatter = "A%0" + (int)Math.ceil(Math.log10(albums.size() * 2) + 1) + "d";
String ID;
do {
ID = String.format(formatter, random.nextInt(albums.size() * 2 + 1));
} while (searchAlbum(ID) != null);
return ID;
}
public void saveData(String fileName) throws IOException {
// make sure that the file exists or try to create it
File fout = new File(fileName);
if (!fout.exists() && !fout.createNewFile())
return;
PrintWriter out = new PrintWriter(fout);
for (MusicAlbum album: albums) {
out.println(serializeAlbum(album));
}
out.close();
}
public String serializeAlbum(MusicAlbum album) {
return String.format(
"%s;%s;%s;%b;%d",
album.getId(),
album.getName(),
album.getGenre(),
album.isCompilation(),
album.getTrackCount());
}
public void loadFile(String fileName) throws FileNotFoundException {
albums = new ArrayList<>();
Scanner in = new Scanner(new File(fileName));
while (in.hasNext()) {
// --- split the next line with the character ";"
String line = in.nextLine();
String[] tokens = line.split(";");
// --- construct a new MusicAlbum using the resulting tokens. NOTE: This isn't very robust.
// If a line doesn't contain enough data or the data is invalid, this will crash
albums.add(new MusicAlbum(
tokens[0],
tokens[1],
tokens[2],
Boolean.parseBoolean(tokens[3]),
Integer.parseInt(tokens[4])
));
}
}
// ----- these methods need to be implemented
public Object[][] getData() {
// TODO
}
public String[] getColumnNames() {
// TODO
}
}
The sample data being used is in a txt file, formatted as so:
A01;Defiance;Soundtrack;true;24
A02;Insomniac;Punk Rock;false;14
A03;A Great Day For The Race;Gypsy Jazz;false;10
A04;Viva La Internet;Ska;false;31
A05;New Surrender;Rock;false;17
So basically it's this getData() method they want me to implement that is giving me grief. I don't fully understand what they want me to do, nor do I fully understand what the Object[][] does.
I hope I have been clear enough, and I will appreciate all help given. Also please try to explain things as best you can and dumb them down as much as possible, I'm new to a lot of this :)
Thanks for your time.
Object[][] is a 2-dimensional array. Each of its element is an Object[], a one-dimensional array.
Your task is to create a 2 dimensional array, having one element (Object[]) for each of your MusicAlbum. An Object[] should hold the properties of a MusicAlbum like id, name, genre, isCompilation and track_count.
You can create an object array like this:
Object[] arr = new Object[] { "some", "values", 23, true };
You can create a 2 dimensional array like this:
Object[][] arr2d = new Object[size][];
And you can iterate over all your MusicAlbums, create an Object[] for each of them containing the properties of that music album, and set it in the arr2d.
You can set/get elements of a 2-dimensional array just like any other arrays:
// Set first element:
arr2d[0] = arr;
// Get first element:
Object[] firstElement = arr2d[0];
The getColumnNames() method should just return a String[] (a String array) containing the column names, the names of the properties.
And it might be obvious but note that the order you return the column names and the order of the property values (in the elements of the Object[]) should be the same.

problem with setSelectedValue Method for JList

i am having troubles when i run the main class for the application. The fact is that the setSelectedValue method doesn't work.
the code for the main class is the following:
DatabaseConnection.getInstance().connect("org.sqlite.JDBC", "jdbc:sqlite:db/Universidad.sqlite");
DatabaseTableManagers managers = DatabaseTableManagers.getInstance();
DataBaseManagerJList.getInstance().setSelectedValue("Alumnos");
system.out.println(DataBaseManagerJList.getInstance().devolver() + "1");
AlumnosTableManager atm = AlumnosTableManager.getInstance();
System.out.println(DataBaseManagerJList.getInstance().devolver() + "2");
CarrerasTableManager ctm = CarrerasTableManager.getInstance();
System.out.println(DataBaseManagerJList.getInstance().devolver() + "3");
managers.add(atm);
System.out.println(DataBaseManagerJList.getInstance().devolver() + "4");
managers.add(ctm);
System.out.println(DataBaseManagerJList.getInstance().devolver() + "5");
DataBaseManagerJFrame dbmf = new DataBaseManagerJFrame();
System.out.println(DataBaseManagerJList.getInstance().devolver() + "6");
dbmf.setVisible(true);
}
}
and i get the following result in console which shows me that the method doesn't set the default value i've put:
null1
null2
null3
null4
null5
null6
the code for the jlist class is the following:
public class DataBaseManagerJList extends JPanel
{
private static final long serialVersionUID = 1L;
private static JList tablas;
DefaultListModel model;
DatabaseTableManagers dtm = DatabaseTableManagers.getInstance();
private static DataBaseManagerJList instance = null;
public static DataBaseManagerJList getInstance()
{
if (instance == null)
{
instance = new DataBaseManagerJList();
}
return instance;
}
public DataBaseManagerJList()
{
model = new DefaultListModel();
ArrayList<String> aux = new ArrayList<String>(dtm.getTableNames());
for(int i =0;i<aux.size();i++)
{
model.addElement(aux.get(i));
}
tablas = new JList(model);
//tablas.setSelectedValue("Alumnos",true);
add(tablas);
}
public String devolver()
{
return (String) tablas.getSelectedValue();
}
public void setSelectedValue(String name)
{
tablas.setSelectedValue(name, true);
}
}
The problem you are describing usually means that the object wasn't found in the list.
The setSelectedValue() method works doing calls to object.equals() (in your case String.equals()), so the probable cause is that the strings contained in aux are capitalized in a different way than the string you are trying to select.
For instace aux may contain the string "alumnos" instead of "Alumnos". There are two alternatives for this, if you don't care about capitalization (then change the string "Alumnos" to whatever is inside aux) if you do care about the capitalization and you still want to use strings, you could simple create a MyString class that extends String and overrides the equals method, something like:
public class MyString extends String {
#Override
public boolean equals(Object obj){
if (obj instanceof String){
String obj2 = (String)obj;
return this.equalsIgnoreCase(obj2);
}
return false;
}
}
Another alternative (perhaps a nicer one) is to create a wrapper object for your list.
public class MyWrapper {
private String payload;
public MyWrapper(String payload){
this.payload = payload;
}
#Override
public String toString(){
return payload;
}
#Override
public boolean equals(Object obj){
if (obj instanceof MyWrapper){
MyWrapper obj2 = (MyWrapper)obj;
return payload.equalsIgnoreCase(obj2.payload);
}
return false;
}
}

Categories

Resources