How to get more the one values froma HashMap with getValue - java

I'm writing a program in JAVA and I'm using a HashMap.
private HashMap<Integer,Plane> planes;
Plane is a class I have created:
public class Plane {
private int planeNumber;
private int departureTime;
private int arrivalTime;
private int flightDuration;
private int aerialDrops;
//constructors...
}
I then try to print all the components of the HashMap like that:
public void getAllAircrafts ()
{
Set set = planes.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print("Aircraft ID is: "+ mentry.getKey() + " ");
System.out.println(mentry.getValue());
}
}
The problem is I want to print the values of all the variables that describe plane, but instead I get aircrafts.Plane#15db9742 from mentry.getValue(). How can I solve this problem?

You need to override and add a toString method for Plane class,
#Override
public String toString() {
return "Plane [planeNumber=" + planeNumber +
",departureTime=" + departureTime +
",arrivalTime=" + arrivalTime +
",flightDuration=" + flightDuration +
",aerialDrops=" + aerialDrops + "]";
}
Right now you are using toString method of Object class parent

A slight change would work fine as per you need :
public class Plane {
private int planeNumber;
private int planeNumber;
private int arrivalTime;
private int flightDuration;
private int aerialDrops;
public String toString()
{
return planeNumber +" "+planeNumber+" "+arrivalTime+" "+flightDuration+" "+aerialDrops
}
}

Related

Changing fields of class in java

So, I'm still learning java and coding so the resolution may be obvious but I just can't see it.
I'm writing a code about stars and constelations for uni assignment.
package com.company;
import java.util.*;
public class Main {
static public class Constellation {
public List<Star> constellation;
public String nameOfConstellation;
public Constellation(List<Star> constellation, String nameOfConstellation) {
this.constellation = constellation;
this.nameOfConstellation = nameOfConstellation;
}
public List<Star> getConstellation() {
return constellation;
}
}
static public class Star {
// private String categoryName;
private Constellation constellation;
private String nameOfConstelation;
public String getCategoryName() {
int index = constellation.getConstellation().indexOf(this);
String categoryName;
return categoryName = GreekLetter.values[index] + " " + this.constellation.nameOfConstellation;
}
public void deleteStar(Star x) {
this.constellation.constellation.remove(x);
}
}
public enum GreekLetter {
alfa,
beta,
gamma,
delta,
epsilon,
dzeta,
eta;
static public final GreekLetter[] values = values();
}
public static void main(String[] args)
{
Star x = new Star();
List<Star> fishCon = new ArrayList<>();
Constellation Fish = new Constellation(fishCon, "Fish");
x.constellation=Fish;
fishCon.add(x);
x.getCategoryName();
Star y = new Star();
y.constellation=Fish;
fishCon.add(y);
y.getCategoryName();
x.deleteStar(x);
for (Star w : Fish.constellation)
{
System.out.println(w.getCategoryName());
}
}
}
My point is to Update field categoryName after deleting one star. categoryName value is set in order of adding another star. For example I have first star - the name will be Alfa + nameOfConstelation. Second star - Beta + nameOfConstelation. When I call method deleteStar() I want to update all categoyName of my stars in constelation. Calling methods in deleteStar() doesn't work probably due to add() in setCategoryName. I would really appreciate any hints!
Since this appears to be homework, I am not posting code in this answer but rather giving suggestions that can help you create your own workable code:
Create a class called Constellation that holds the Stars in an List<Star> starList = new ArrayList<>();
Give Constellation a public List<Star> getStarList() method
Give each Star a Constellation field to hold the Constellation that contains this Star
Give each Star a getCategoryName() method that gets the Constellation object, iterates through its starList using a for-loop until it finds the this Star, and then that returns the appropriate name based on the index of the Star in the list.
Thus, if a Star is removed from the starList, the category names of all the other Stars held by that Constellation will update automatically and dynamically
Also,
You can give Constellation a public void deleteStar(Star star) method where it removes the Star parameter from its starList
You can also give Star a public void deleteFromConstellation() method where it checks its Constellation field, constellation, and if not null, calls constellation.deleteStar(this); and then sets the constellation field to null
Get rid of the private String categoryName; field in Star. This should be a calculated field, meaning the public String getCategoryName() does not return a field, but a String based on code (as described above).
It first checks that Star's constellation field is not null
It then gets the index of the Star in the Constellation's starList (I have given my Constellation class a public int getIndexOfStar(Star star) method.
It then uses this, the GreekLetter class, and the constellation.getName() method to create a String to return
Done.
Since you've figured this out, this is another way to code it:
public class SkyMain {
public static void main(String[] args) {
Constellation fish = new Constellation("Fish");
Star x = new Star();
Star y = new Star();
fish.addStar(x);
fish.addStar(y);
System.out.println("before removing x");
System.out.println("x category name: " + x.getCategoryName());
System.out.println("y category name: " + y.getCategoryName());
System.out.println("fish constellation: " + fish);
fish.removeStar(x);
System.out.println();
System.out.println("after removing x");
System.out.println("x category name: " + x.getCategoryName());
System.out.println("y category name: " + y.getCategoryName());
System.out.println("fish constellation: " + fish);
}
}
public class Star {
private Constellation constellation;
public void setConstellation(Constellation constellation) {
this.constellation = constellation;
}
public void removeFromConstellation() {
if (constellation != null) {
constellation.removeStar(this);
}
}
public String getCategoryName() {
if (constellation != null) {
int index = constellation.getIndexOfStar(this);
return GreekLetter.getGreekLetter(index).getName() + " " + constellation.getName();
} else {
return "";
}
}
#Override
public String toString() {
return getCategoryName();
}
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Constellation implements Iterable<Star> {
private String name;
private List<Star> starList = new ArrayList<>();
public Constellation(String name) {
this.name = name;
}
public String getName() {
return name;
}
public List<Star> getStarList() {
return starList;
}
public void addStar(Star star) {
starList.add(star);
star.setConstellation(this);
}
public void removeStar(Star star) {
if (starList.contains(star)) {
starList.remove(star);
star.setConstellation(null);
}
}
public int getIndexOfStar(Star star) {
return starList.indexOf(star);
}
#Override
public Iterator<Star> iterator() {
return starList.iterator();
}
#Override
public String toString() {
return "Constellation [name=" + name + ", starList=" + starList + "]";
}
}
public enum GreekLetter
{
ALPHA("alpha", 0),
BETA("beta", 1),
GAMMA("gamma", 2),
DELTA("delta", 3),
EPSILON("epsilon", 4),
ZETA("zeta", 5),
ETA("eta", 6);
private String name;
private int index;
private GreekLetter(String name, int index) {
this.name = name;
this.index = index;
}
public String getName() {
return name;
}
public int getIndex() {
return index;
}
public static GreekLetter getGreekLetter(int index) {
if (index < 0 || index > values().length) {
throw new IllegalArgumentException("for index " + index);
} else {
return values()[index];
}
}
}

How do I create an instance of another class, load an object with data and print it out?

I am a complete noob (5th day programming) which explains why I have spent countless head-aching hours trying to solve this problem and still have not figured it out yet:
How do you create an instance of CarAndBikes, load it with information of 3 cars and print it out?
Here's my incomplete code to give you an idea of the problem:
public class Vehicle {
String manufacturer, model;
int numberOfWheels;
public Vehicle(String manufacturer, String model, int numberOfWheels) {
this.manufacturer = manufacturer;
this.model = model;
this.numberOfWheels = numberOfWheels;
}
public String getManufacturer() {
return manufacturer;
}
public String getModel() {
return model;
}
public int getNumberOfWheels() {
return numberOfWheels;
}
public String toString() {
return "(" + numberOfWheels +") '" + manufacturer + ", " + model + "'";
}
}
public class CarAndBikes {
private Vehicle[] items;
private int nextFreeItem = 0;
CarAndBikes (int size) {
items = new Vehicle[size];
for(int i = 0; i < size; i++)
items[i] = new Vehicle(manufacturer, model, numberOfWheels);
}
void addVehicle(String man, String mdl, int wheels) {
items[nextFreeItem++].addVehicle(man, mdl, wheels);
}
public String toString() {
return "(" + items + ")";
}
}
public class TestProgram extends CarAndBikes{
TestProgram(int size) {
super(size);
}
public static void main(String[] args) {
Vehicle vehicle1 = new Vehicle("Seat", "Ibiza", 4);
Vehicle vehicle2 = new Vehicle("Reliant", "Robin", 3);
Vehicle vehicle3 = new Vehicle("Honda", "Fireblade", 2);
System.out.println(vehicle1);
System.out.println(vehicle2);
System.out.println(vehicle3);
}
}
In my opinion you'd be better off separating cars and bikes into separating cars and bikes into two seperate classes 'Car' and 'Bike' and then create a 3rd class to house a collection of those objects, that way you can use an List or ArrayList to store them and have a method to just print them out.
import java.util.ArrayList;
Public Class Garage
{
private ArrayList<Vehicle> vehicles;
Public Garage()
{
vehicles = new ArrayList<Vehicle>();
}
public void addVehicle(Vehicle v)
{
vehicles.add(v);
}
public void getVehicles()
{
for(Vehicle v : vehicles)
{
System.out.Println(v.getModel());
}
}
}
You'll notice that the ArrayList accepts objects of type vehicle, well both cars and bikes extend vehicle so they will be accepted.
I notice the toString() method in CarAndBikes is using toString() on an array reference (and arrays don't override toString()). You could use Arrays.toString(Object[]) like
public String toString() {
// return "(" + items + ")";
return Arrays.toString(items);
}
The Object.toString() that you're getting is documented as,
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())

The type of the expression must be an array type but it resolved to

Im new to java. I dont understand why these errors are occurring. trying to make an array list so that it saves each object. The errors im getting are The type of the expression must be an array type but it resolved to ArrayList on the line 'newbug1[i].setspecies();'
Thankyou in advance
import javax.swing.JOptionPane;
import java.util.ArrayList;
public class Abug2 {
private String species;
private String name;
private char symbol = '\0';
private int horposition = 0, verposition = 0, energy = 0, uniqueID = 1, counter;
public Abug2(String species, String name, char symbol)
{
uniqueID = counter;
counter++;
}
public void setspecies(){
species = JOptionPane.showInputDialog(null, "Enter the species: ");
}
public String getspecies(){
return species;
}
public void setname(){
name = JOptionPane.showInputDialog(null, "Enter the name: ");
}
public String getname(){
return name;
}
public void setsymbol(){
symbol = name.charAt(0);
}
public char getsymbol(){
return symbol;
}
public int getid(){
return uniqueID;
}
public int gethorizontal(){
return horposition;
}
public int getvertical(){
return verposition;
}
public int getenergy(){
return energy;
}
//The class ABug has a set of methods: two or more constructors, toString, toText, and getters and setters for the attributes
public String toString(){
String tostring = "\nName: " + name + "\nHorizontal Position: " + horposition + "\nVertical Position: " + verposition + "\n";
return tostring;
}
public String toText(){
String totext = getspecies() + getname() + getsymbol() + getid() + gethorizontal() + getvertical() + getenergy();
return totext;
}
public static void main (String [] args){
ArrayList<Abug2> newbug1 = new ArrayList<Abug2>();
String choice = JOptionPane.showInputDialog(null, "Would you like to add another bug?: ");
do{for (int i = 0; i < 3; i++) {
newbug1.add(new Abug2("Bug", "Spider", 's'));
newbug1[i].setspecies();
newbug1[i].setname();
newbug1[i].setsymbol();
System.out.println(newbug1[i].toString());
} }while(choice != "yes");
}
}
For arraylists use get() instead:
newbug1.get(i).setspecies();
newbug1.get(i).setname();
newbug1.get(i).setsymbol();
Because it stores object references any setFoo calls affect the original object referenced in the arraylist.
In order to access an element in an ArrayList you have to use a method called get.
In your code, replace newbug1[i] by newbug1.get(i)
And moreover, you should store that reference in a variable instead of recalling it again and again:
Abug2 currentBug = newbug1.get(i);
currentBug.setSpecies();
Your code will gain in clarity.

How to use compareTo to arrange flights by descending order

I am creating a flight controller application. A bit of functionality that i want is to be able to tell the user what the next flight is according to a specific airline. I have a hash map which stores strings and planes. In my plane class i am implementing Comparable and i have the compareTo method. Could anyone help me achieve using the compareTo method to arrange the planes in descending order to show the next flight. I want to arrange the flights by the variable overdue.
This is the case in the MainApp that i have to use the compareTo on
switch (nextChoice)
{
case 1:
airlineMap.printAirline("Aer Lingus");
break;
case 2:
airlineMap.printAirline("Brittish Airways");
break;
case 3:
airlineMap.printAirline("Eithad");
break;
case 4:
airlineMap.printAirline("Iberia");
break;
case 5:
airlineMap.printAirline("Quantas");
break;
I hope to add the descending order to a airline print: airlineMap.printAirline("Aer Lingus");
Here is my Plane class:
import java.util.LinkedList;
public class Plane implements Comparable
{
private String flightNumber;
public String airlineName;
private double fuelRemaining;
private int overdue;
private int passengerNumber;
private AIRPLANETYPE planeType;
public enum AIRPLANETYPE
{
AIRBUS("1"), CORPORATE("2"), PRIVATE("3");
private String planeName;
private AIRPLANETYPE(String planeName)
{
this.planeName = planeName;
}
public String getPlaneName()
{
return this.planeName;
}
}
public Plane(String flightNumber, String airlineName, double fuelRemaining, int overdue, int passengerNumber, AIRPLANETYPE planeType) {
this.flightNumber = flightNumber;
this.airlineName = airlineName;
this.fuelRemaining = fuelRemaining;
this.passengerNumber = passengerNumber;
this.overdue = overdue;
this.planeType = planeType;
}
public String getAirlineName() {
return airlineName;
}
public void setAirlineName(String airlineName) {
this.airlineName = airlineName;
}
public void setOverdue(int overdue) {
this.overdue = overdue;
}
public int getOverdue(){
return overdue;
}
public String getFlightNumber() {
return flightNumber;
}
public void setFlightNumber(String flightNumber) {
this.flightNumber = flightNumber;
}
public double getFuelRemaining() {
return fuelRemaining;
}
public void setFuelRemaining(double fuelRemaining) {
this.fuelRemaining = fuelRemaining;
}
public int getPassengerNumber() {
return passengerNumber;
}
public void setPassengerNumber(int passengerNumber) {
this.passengerNumber = passengerNumber;
}
public AIRPLANETYPE getPlaneType() {
return planeType;
}
public void setPlaneType(AIRPLANETYPE planeType) {
this.planeType = planeType;
}
public int compareTo(Object arg0) {
if((arg0 != null) && (arg0 instanceof Plane))
{
Plane p = (Plane) arg0;
return (int)Math.ceil(this.overdue - p.getOverdue());
}
return 0;
}
public String toString() {
return "Plane: flightNumber=" + flightNumber + "."
+ " airlineName=" + airlineName + "."
+ " fuelRemaining=" + fuelRemaining + " litres."
+ " overdue=" + overdue + " minutes."
+ " passengerNumber="+ passengerNumber + "."
+ " airplaneType=" + planeType + ".\n";
}
}
Since HashMap is unordered, you have two ways of going about sorting your planes:
Put them into a sorted container, or
Put them into an ArrayList<Plane> or an array Plane[], and sort that list or array
The first approach can be achieved with a TreeSet<Plane>: put your planes into the set, and iterate them in the "natural" order (i.e. the order consistent with their compareTo method).
The second approach requires copying the planes into a separate container or an array, and then using the sort method (or the Arrays.sort static method if it is an array) to order your planes in accordance with the order set by their compareTo implementation.
EDIT : (based on a comment) One way to deal with a problem of storing planes in a specific order inside a hash map is to make a hash map of tree sets, like this:
Map<String,TreeSet<Plane>> airlineMap = new HashMap<String,TreeSet<Plane>>();
Once you add the planes to each airline, they would be maintained in the order based on your compareTo implementation. with a TreeSet<Plane> in hand, you can easily find the next or the prior Plane by calling higher or lower.
You should use Math.signum rather than Math.ceil in your compareTo method.

Enum within enum

I want to create an enum within an enum for sql query in java. For example I want to say table.create and it would return CREATE TABLE or database.create and it would return CREATE DATABASE. How can I do this?
enum SQL {
table("ALTER,CREATE"),
database("CREATE");
}
Define an enum within the enum:
public static enum SQL {
table(Command.ALTER,Command.CREATE),
database(Command.CREATE);
public static enum Command {
CREATE,
ALTER
}
private final Command[] commands;
private SQL (Command... commands) {
this.commands = commands;
}
public Command[] getCommands() {
return commands;
}
}
Although you can do this, it would be better to declare the Command enum in its own class/file. I haven't seen anyone declare an enum inside another enum before... I almost like it.
Why make it an enum within an enum?
Table.java
public enum Table {
CREATE("CREATE TABLE"),
ALTER("ALTER TABLE");
private String cmd;
Table(String cmd) {
this.cmd = cmd;
}
#Override
public String toString() {
return cmd;
}
}
Database.java
public enum Database {
CREATE("CREATE DATABASE");
private String cmd;
Database(String cmd) {
this.cmd = cmd;
}
#Override
public String toString() {
return cmd;
}
}
With this example, System.out.println(Table.CREATE); prints CREATE TABLE.
This will also aid in readabilty becuase you can produce code like:
String query = Table.CREATE + "(Column1 " + DbType.INTEGER + " " + Column.UNIQUE + " " + Column.PRIMARY_KEY + ")";
Which would be a bit easier to read and understand, IMO.
EDIT
To attempt to get close to what you're after you could do something like:
public enum SQL {
TABLE("TABLE", SQL.CREATE_FLAG | SQL.ALTER_FLAG),
DATABASE("DATABASE", SQL.CREATE_FLAG);
public static final int CREATE_FLAG = 1;
public static final int ALTER_FLAG = 2;
public static final String CREATE_STRING = "CREATE";
public static final String ALTER_STRING = "ALTER";
public static final String INVALID = "INVALID";
private String name;
private boolean create;
private boolean alter;
SQL(String name, int flags) {
create = (flags & CREATE_FLAG) != 0;
alter = (flags & ALTER_FLAG) != 0;
this.name = name;
}
public String create() {
if (create)
return CREATE_STRING + " " + name;
else
return INVALID;
}
public String alter() {
if (alter)
return ALTER_STRING + " " + name;
else
return INVALID;
}
}
Where you can call:
System.out.println(SQL.TABLE.create()); // CREATE TABLE
System.out.println(SQL.TABLE.alter()); // ALTER TABLE
System.out.println(SQL.DATABASE.alter()); // INVALID
System.out.println(SQL.DATABASE.create()); // CREATE DATABASE

Categories

Resources