what I am trying to do is create an itinerary of flight paths using JGraphT. The problem I am facing is converting the string times I have set into actual times that I can then do calculations over multiple days i.e. if a flight leaves at 16.00 and arrives at 18.30 but then the connecting flight leaves at 14.00 and arrives at the final destination at 16.00 it will have been 24 hours (i.e. one day). I am lost in this as I have tried to parse the string to a date in the Flight class and also used The simple date format which is causing errors.
My code as follows;
Flight3.java
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
import org.jgrapht.alg.DijkstraShortestPath;
import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.SimpleDirectedWeightedGraph;
public class Flight3
{
private static ArrayList<String[]> myEdges;
private static ArrayList<Flight> flight;
public Flight3()
{
}
public static void main(String [] args)
{
myEdges = new ArrayList<String[]>();
flight = new ArrayList<Flight>();
SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> Graph = createGraph();
System.out.println("Airlines!");
Scanner sc = new Scanner(System.in);
System.out.println("Enter the airport you wish to fly from");
String startVertex = sc.nextLine();
while(!Graph.containsVertex(startVertex))
{
System.out.println("Sorry, that airport does not exist. Please select another;");
startVertex = sc.nextLine();
}
System.out.println("Enter destination airport");
String endVertex = sc.nextLine();
while(!Graph.containsVertex(endVertex))
{
System.out.println("Sorry, that airport does not exist. Please select another;");
endVertex = sc.nextLine();
}
calculatePath(Graph, startVertex, endVertex);
}
private static SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> createGraph()
{
SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> g =
(SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>) new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class);
{
g.addVertex("London");
g.addVertex("France");
g.addVertex("Spain");
createTwoWayWeightedEdge(g, "London", "France", 80);
generateFlight("1600", "1830", "EH445", "0000", 80);
generateFlight("0400", "0600", "HE452", "0000", 80);
createTwoWayWeightedEdge(g, "France", "Spain", 130);
generateFlight("1400", "1600", "HD123", "0400", 130);
generateFlight("0400", "0600", "DH712", "0000", 130);
}
return g;
}
private static void createTwoWayWeightedEdge(SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> g, String vertex1, String vertex2, double weight)
{
g.addEdge(vertex1, vertex2);
g.addEdge(vertex2, vertex1);
g.setEdgeWeight(g.getEdge(vertex1, vertex2), weight);
g.setEdgeWeight(g.getEdge(vertex2, vertex1), weight);
String[] tmp1 = {vertex1, vertex2};
myEdges.add(tmp1);
String[] tmp2 = {vertex2, vertex1};
myEdges.add(tmp2);
}
private static void generateFlight(String depTime, String arrTime, String flightNo, String locTime, int duration)
{
Flight f = new Flight(depTime, arrTime, flightNo, locTime, duration);
flight.add(f);
}
private static String textToPrint(String[] format)
{
String text = " ";
for(int i = 0; i < format.length; i++)
{
switch(i)
{
case 0:
text = text + format[i];
for(int j = format[i].length(); j < 6 ; j++)
text = text + " ";
break;
case 1:
text = text + format[i];
for(int j = format[i].length(); j < 15 ; j++)
text = text + " ";
break;
case 2:
text = text + format[i];
for(int j = format[i].length(); j < 10 ; j++)
text = text + " ";
break;
case 3:
text = text + format[i];
for(int j = format[i].length(); j < 10 ; j++)
text = text + " ";
break;
case 4:
text = text + format[i];
for(int j = format[i].length(); j < 15 ; j++)
text = text + " ";
break;
case 5:
text = text + format[i];
for(int j = format[i].length(); j < 10 ; j++)
text = text + " ";
break;
case 6:
text = text + format[i];
for(int j = format[i].length(); j < 10 ; j++)
text = text + " ";
break;
}
}
return text;
}
private static void calculatePath(SimpleDirectedWeightedGraph<String, DefaultWeightedEdge> g, String startVertex, String endVertex)
{
DijkstraShortestPath path = new DijkstraShortestPath(g, startVertex, endVertex);
path.getPath();
List<Object> edges = path.getPathEdgeList();
String item;
int count = 1;
double totalDuration = 0;
if(edges!=null)
{
System.out.println("\n The lowest cost route is:");
String[] labels = {"Flight.", "Leave from", "At", "On", "Arrive", "At", "Local Time"};
System.out.println(textToPrint(labels));
for(Object edge : edges)
{
item = edge.toString();
StringTokenizer st = new StringTokenizer(item, ":");
String firstAirport = st.nextToken().trim().substring(1);
String secondAirport = st.nextToken().trim();
secondAirport = secondAirport.substring(0, secondAirport.length()-1);
String depTime = null;
String arrTime = null;
String flightNo = null, locTime = null;
double price, flightDuration;
for(int i=0;i<flight.size();i++)
{
if(firstAirport.equals(myEdges.get(i)[0]) && secondAirport.equals(myEdges.get(i)[1]))
{
Flight details = flight.get(i);
flightNo = details.flightNo;
depTime = details.depTime;
arrTime = details.arrTime;
price = details.price;
flightDuration = details.duration;
totalDuration = totalDuration + details.getDuration();
locTime = details.getLocTime();
String[] flightInfo = {count+".", firstAirport, depTime, flightNo, secondAirport, arrTime, locTime};
System.out.println(textToPrint(flightInfo));
}
}
count++;
}
System.out.println("Cost of route = £"+path.getPathLength());
System.out.println("Total time in the air = "+totalDuration +"hrs");
}
else
System.out.println("Sorry you can't fly there from " + startVertex);
}
Flight.java
import java.text.SimpleDateFormat;
public class Flight {
String depTime;
String arrTime;
String flightNo;
String locTime;
double duration;
int price;
public Flight(String depTime, String arrTime, String flightNo, String locTime, int duration){
this.depTime = depTime;
this.arrTime = arrTime;
this.flightNo = flightNo;
this.locTime = locTime;
this.duration = duration;
}
public double getDuration(){
double duration = Integer.parseInt(arrTime) - Integer.parseInt(depTime);
return duration / 100;
}
public String getLocTime(){
int value = Integer.parseInt(locTime) + Integer.parseInt(arrTime);
locTime = ""+value;
return locTime;
}
public String getFlightNo(){
return flightNo;
}
public double getPrice(){
return price;
}
}
Your Question is not exactly clear. But here are some general tips.
Departure + Duration = Arrival
Do not focus on arrival. The arrival time is a result of [arrival + duration]. In other words, output not input. This solves your problem with rotating around the clock crossing midnight.
Use objects, not strings
Use objects, not strings. Java has an excellent industry-leading date-time framework in the java.time classes. Use them. But do not use the notoriously troublesome old legacy date-time classes, the ones outside the java.time package. Use strings only as needed in the user-interface and for serializing data.
In particular, you should be looking at the LocalTime and Duration classes. See Oracle Tutorial.
ISO 8601
And for serializing, stick to the standard ISO 8601 formats such as HH:MM for a time-only value with the colon being optional for the “basic” version though I recommend keeping the colon for the “extended” version. The java.time classes use the extended version of ISO 8601 by default when parsing and generating strings that represent date-time values.
Make Flight ignorant of charting, and vice-versa
Separate out your data model from the chart drawing. Define Flight as just the flight info and functions, without thinking about the charting.
class Flight {
LocalTime departure;
Duration duration;
LocalTime getArrival() {
LocalTime arrival = departure.plus( duration );
// If called *many* times, and you account for changing-data and thread-safety, you could cache this result for performance.
return arrival;
}
Flight( LocalTime departureArg , Duration durationArg ) {
this.departure = departureArg;
this.duration = durationArg;
}
}
To produce the exact data needed by chart, either use getter methods on Flight or a mediating class between Flight and chart. Keep the classes as cleanly separated as possible. Your car’s radio-stereo does not need to know anything about the air-conditioner which in turn does not need to know about the engine’s fuel-oxygen mixture ratio.
Time Zone
The big elephant in the room is time zone. You have not made clear your intentions here.
Generally best to work in UTC. Translate to a local time zone only as needed for presentation to the user.
Not much more to say on this until you clarify the intention of your business context.
Search Stack Overflow for the Java classes LocalDateTime, OffsetDateTime, ZonedDateTime, ZoneOffset, and ZoneId to learn much more.
We might have to append/prefix some format of today's date (examples here : https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) before doing the duration computation.
so when we have the start time of "0430" we will prefix some format of today's date as well . For example:
startDate = "0430"
becomes
startDateModified = new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + startDate;
startDateObject = new SimpleDateFormat("yyyy/MM/dd HH:mm").parse(statDateModified)
similarly we do so for the end date (we might have to use some other value of new Date() because the arrival time be for the next day etc)
And then we do the computation.
Now regarding your question, we will have to some how figure out the connecting flight departure date value is not
new Date(); //today
but
new Date(System.currentTimeMillis() + 24*3600); //tomorrow
We might, in fact, have to have another shorthand notation to denote that the flight leaves today and reaches tomorrow (like "+1 0430" to denote +1 day etc)
Related
In my program, I have a Vendor class and a Hospital class and store instances of these classes in arraylists called vendors and hospitals. My Vendor class has a string array with names of hospitals that correspond to instances of the Hospital class. I'm trying to find a way to go from the name of the hospital in the string array that is part of the Vendor class, to getting the index value of that hospital for the hospitals arraylist. Apologies if this post doesn't make much sense, I'm very new to coding. Any help would be greatly appreciated.
Edit: Please Ctrl+F with the following to jump to the particular lines of code in question
//check if hospital
Vendor Class
package com.company;
import java.util.Arrays;
import java.util.Scanner;
public class Vendor {
//static variables are the same for all vendor instances
static int numOfHospitals;
static int numOfAppointments;
//non-static variables are specific to one vendor instance
int priorityNum;
String salespersonName;
String vendorCompanyName;
String [] vendorPicks;
String[] vendorSchedule;
public void printVendorSchedule() {
System.out.println(Arrays.toString(vendorSchedule));
}
public void printVendorPicks () {
System.out.println(Arrays.toString(vendorPicks));
}
public String getVendorSchedule (int appointmentSlot) {
return vendorSchedule [appointmentSlot];
}
public String getVendorPick (int currentHospitalPick) {
return vendorPicks[currentHospitalPick];
}
public boolean checkVendorSchedule (int appointmentSlot) {
return ((vendorSchedule[appointmentSlot]).equals("open"));
}
public void setVendorAppointment (int appointmentSlot, String hospitalName) {
vendorSchedule[appointmentSlot] = hospitalName;
}
public Vendor createNewVendor(int priorityNum, int numOfAppointments, int numOfHospitals, String salespersonName, String vendorCompanyName){
this.priorityNum=priorityNum;
this.salespersonName=salespersonName;
this.vendorCompanyName=vendorCompanyName;
this.vendorPicks = new String[numOfHospitals];
this.vendorSchedule = new String[numOfAppointments];
for (int i = 0; i <numOfAppointments; i++) {
this.vendorSchedule[i] = "open";
}
Scanner input = new Scanner(System.in);
Vendor vendorToAdd = new Vendor();
//loop to add vendor's hospital picks
int counter = 0;
while (counter < numOfHospitals) {
System.out.println("Enter the #" +(counter+1) +" hospital for "+salespersonName+". If there are no more hospitals for this vendor, enter Done.");
String placeHolder = input.nextLine();
if (placeHolder.equalsIgnoreCase("done")) {
break;
}
vendorPicks[counter]=placeHolder;
counter++;
}
return vendorToAdd;
}
}
Hospital Class
package com.company;
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
public class Hospital {
//static variables here
int numOfAppointments;
int numOfHospitals;
//non-static variables here
String nameHospital;
String nameDirector;
String [] hospitalSchedule;
public void printHospitalSchedule () {
System.out.println(Arrays.toString(hospitalSchedule));
}
public String getHospitalSchedule(int appointmentSlot) {
return hospitalSchedule[appointmentSlot];
}
public boolean checkHospitalSchedule (int appointmentSlot) {
return ((hospitalSchedule[appointmentSlot]).equals("open"));
}
public void setHospitalAppointment (int appointmentSlot, String nameVendor) {
hospitalSchedule[appointmentSlot] = nameVendor;
}
public Hospital createNewHospital(int numOfAppointments, int numOfHospitals,
String nameHospital, String nameDirector) {
Hospital h1 = new Hospital();
this.nameDirector=nameDirector;
this.nameHospital=nameHospital;
this.hospitalSchedule = new String[numOfAppointments];
for (int i=0; i < numOfAppointments; i++) {
hospitalSchedule[i] = "open";
}
return h1;
}
}
Main Class
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Inputting #vendors, #hospitals
int vendorCounter=1;
System.out.println("Enter the total number of appointment slots.");
Scanner myScanner = new Scanner(System.in);
int numOfAppointments = Integer.parseInt(myScanner.nextLine());
System.out.println("Enter the total number of hospitals in the draft.");
int numOfHospitals = Integer.parseInt(myScanner.nextLine());
ArrayList<Hospital> hospitals = new ArrayList<Hospital>();
//creating hospitals
int hospitalCounter = 1;
while (hospitalCounter <=numOfHospitals) {
System.out.println("Enter the name of hospital #" + hospitalCounter);
String currentHospitalName = myScanner.nextLine().toLowerCase(Locale.ROOT).trim();
System.out.println("Enter the director's name for " + currentHospitalName + ".");
String currentDirectorName = myScanner.nextLine().toLowerCase(Locale.ROOT).trim();
Hospital h1 = new Hospital();
h1.createNewHospital(numOfAppointments, numOfHospitals, currentHospitalName, currentDirectorName);
hospitals.add(h1);
hospitalCounter++;
}
//creating vendors
ArrayList<Vendor> vendors = new ArrayList<Vendor>();
Scanner myInput = new Scanner(System.in);
while (vendorCounter != 2000){
System.out.println("Are you entering a new vendor? Enter Yes or No");
String isAddingNewVendor;
isAddingNewVendor= myScanner.nextLine();
if (isAddingNewVendor.equalsIgnoreCase("yes"))
{
System.out.println("Enter the name of the salesperson.");
String salespersonName = myInput.nextLine();
System.out.println("Enter the company name for "+salespersonName+".");
String vendorCompanyName = myInput.nextLine();
Vendor v1 = new Vendor();
v1.createNewVendor(vendorCounter, numOfAppointments, numOfHospitals,salespersonName,vendorCompanyName);
vendors.add(v1);
vendorCounter++;
}
else vendorCounter = 2000;
}
/* System.out.println(vendors.get(0).vendorCompanyName);
System.out.println(hospitals.get(0).nameHospital);
System.out.println(vendors.get(0));
vendors.get(0).printVendorSchedule();
vendors.get(0).printVendorPicks();
hospitals.get(0).printHospitalSchedule();
if (vendors.get(0).checkVendorSchedule(0)) {
System.out.println ("This appointment slot is open for the vendor.");
}
if (hospitals.get(0).checkHospitalSchedule(0)) {
System.out.println("This appointment slot is open for the hospital.");
}*/
for (int i = 0; i < numOfHospitals; i++) {
System.out.println("Information for hospital #" + i);
System.out.println("Hospital name: " +hospitals.get(i).nameHospital);
System.out.println("Director's name: " + hospitals.get(i).nameDirector);
System.out.println("The hospital's initial schedule:");
hospitals.get(i).printHospitalSchedule();
}
for (int i = 0; i < vendors.size(); i++) {
System.out.println("Information for vendor #" + i);
System.out.println("Salesperson's name: "+vendors.get(i).salespersonName);
System.out.println("Company name: " + vendors.get(i).vendorCompanyName);
System.out.println("The vendor's hospital choices:");
vendors.get(i).printVendorPicks();
System.out.println("The vendor's initial schedule:");
vendors.get(i).printVendorSchedule();
}
//draft loop logic
int draftRound = 1;
while (draftRound <= numOfAppointments) {
if (draftRound % 2 == 1) {
//insert code for odd-numbered draft rounds here.
//these rounds should start with picker 1, then 2, 3, etc.
int currentVendor = 0; //starts this round with the first vendor
while (currentVendor < vendors.size()){
//this while loop continues running through a single draft round until all vendors get a pick
int currentAppointmentSlot = 0;
int currentVendorPickSlot=0;
while (currentVendorPickSlot < numOfHospitals) { //this loops through a single vendor until all appointments checked or appt assigned
//check if hospital and vendor are both open
String currentHospital = vendors.get(currentVendor).vendorPicks[currentVendorPickSlot];
System.out.println(currentHospital);
int currentHospitalsIndex = hospitals.indexOf(currentHospital); //indexof is returning -1 creating the exceptionoutofbounds
System.out.println("Current hospital index:"+ currentHospitalsIndex);
if ( hospitals.get(currentHospitalsIndex).checkHospitalSchedule(currentAppointmentSlot) != vendors.get(currentVendor).checkVendorSchedule(currentAppointmentSlot)) {
currentAppointmentSlot++;
}
else {
vendors.get(currentVendor).setVendorAppointment(currentVendorPickSlot, hospitals.get(currentHospitalsIndex).nameHospital);
hospitals.get(currentHospitalsIndex).setHospitalAppointment(currentVendorPickSlot, vendors.get(currentVendor).salespersonName);
break; // does this break the loop?
}
}
currentVendor++;
}
draftRound++;
}
if (draftRound % 2 == 0) {
//insert code for even-numbered draft rounds here.
//these rounds should start with the last picker and go down by 1 each turn until 1st picker.
int currentVendor = vendors.size()-1; //starts this draft round with the last vendor
while (currentVendor >= 0) {
//this while loop continues running through a single draft round until all vendors get a pick
int currentAppointmentSlot = 0; //looping through the hospital choices for a single vendor
int currentVendorPickSlot=0;
while (currentVendorPickSlot < numOfHospitals) {
//check if hospital and vendor are both open
String currentHospital = vendors.get(currentVendor).vendorPicks[currentVendorPickSlot];
int currentHospitalsIndex = hospitals.indexOf(currentHospital);
if (hospitals.get(currentHospitalsIndex).checkHospitalSchedule(currentAppointmentSlot) != vendors.get(currentVendor).checkVendorSchedule(currentAppointmentSlot)) {
currentAppointmentSlot++;
//continuing the loop if the appointment slot doesn't work
}
else {
vendors.get(currentVendor).setVendorAppointment(currentAppointmentSlot, hospitals.get(currentHospitalsIndex).nameHospital);
hospitals.get(currentHospitalsIndex).setHospitalAppointment(currentAppointmentSlot, vendors.get(currentVendor).salespersonName);
currentVendor++;
break; // does this break the loop?
}
}
currentVendor++;
}
draftRound++;
}
else break;
}
for (int i = 0; i < numOfHospitals; i++) {
System.out.println("Information for hospital #" + i);
System.out.println("Hospital name: " +hospitals.get(i).nameHospital);
System.out.println("Director's name: " + hospitals.get(i).nameDirector);
System.out.println("The hospital's final schedule:");
hospitals.get(i).printHospitalSchedule();
}
for (int i = 0; i < vendors.size(); i++) {
System.out.println("Information for vendor #" + i);
System.out.println("Salesperson's name: "+vendors.get(i).salespersonName);
System.out.println("Company name: " + vendors.get(i).vendorCompanyName);
System.out.println("The vendor's final schedule:");
vendors.get(i).printVendorSchedule();
}
}}
First using stream we will Iterate through hospitals list,
find out the hospital from the list whose name equals currentHospital name, take out the first result using findFirst.
Since the result may be or may not be available it returns Optional.
So on Optional, we will say if it's (the hospital object which we were looking for) present we will get the hospital out of it using the get method
Optional<Hospital> result = hospitals.stream().filter(h -> h.nameHospital.equals(currentHospital)).findFirst();
if(result.isPresent()){
Hospital hospital = result.get();
}
Having some problems with this program. I am new to Java and am trying to make a league scheduler. I have got to the point where the user can enter a number of teams needed, expected league start date and end date. Once the user selects the end date, a number of rounds are suggested to the user as this would be the number of weeks the league would need to go on for. Currently though, when the league generates, the dates print altogether, my question is how can I can the dates to print like - "round 1 05/06/2018". Also, how can I change my program so an odd number can be accepted, similar to a 'bye'?
I apologise for my ill knowledge of the subject, I have included a snippet of my code and a picture of my GUI so it gives more context.
Many thanks,
Jack
void cyclicRoll(int cycle[], int teams) {
int tmp = cycle[1];
for(int i=1;i<teams-1;i++) {
int pr = cycle[i+1];
cycle[i+1] = tmp;
tmp = pr;
}
cycle[1] = tmp;
}
void scheduleTournament(int teams, int round) {
if (((teams%2 != 0) && (round != teams - 1))||(teams <= 0))
throw new IllegalArgumentException();
int[] cycle = new int[teams];
int n = teams /2;
for (int i = 0; i < n; i++) {
cycle[i] = i + 1;
cycle[teams - i - 1] = cycle[i] + n;
}
Date startDate = (jXDatePicker1.getDate());
Date endDate = (jXDatePicker2.getDate());
LocalDate dates = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate firstdate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
DayOfWeek dayOfWeeek = dates.getDayOfWeek();
LocalDate datee = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
String listrep ="";
String firstDateToPrint = firstdate.toString();
while (!dates.equals(datee)) {
jTextArea1.removeAll();
if(dayOfWeeek == dayOfWeeek) {
dates = dates.plusDays(7);
}
String[] Itdates = {dates.toString()
};
for(String replacement : Itdates) {
if ("".equals(listrep)) {
listrep += replacement;
} else {
listrep += ", \n" + replacement ;
}
}
}
jTextArea1.append(firstDateToPrint + "\n");
jTextArea1.append(listrep);
for(int d = 1; d <= round; d++)
{
jTextArea1.append(String.format("Round %d\n", d ));
for (int i = 0; i < n; i++)
{
jTextArea1.append(String.format("team %d - team %d\n",cycle[i],cycle[teams - i - 1]));
}
//Roll the cycle keeping the first constant
cyclicRoll(cycle,teams);
}
}
String ref;
String teams;
String rounds;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextArea1.selectAll();
jTextArea1.replaceSelection("");
teams = jTextField1.getText();
int teamsToEnter = Integer.parseInt(teams);
rounds = jTextField2.getText();
int roundsToEnter = Integer.parseInt(rounds);
ref = jTextField3.getText();
jTextArea1.append("Ref "+ref + "\n");
scheduleTournament(jTextField2,roundsToEnter);
}
Using for loop to compare the input value with the hashmap if it matches any value in the hash-map then the code prints all the related values with that time.
The result shows out for me NULL
System.out.println("Please enter time :");
Scanner scan = new Scanner(System.in);
String value = scan.nextLine();//Read input-time
Measurement measurement = measurements.get(value);//there can only be 1 Measurement for 1 time
if(measurement != null){
System.out.println(measurement);
}}
Class Measurement:
public void getTimeInfo(String value)
{
value = Measurements.get(time);
if (value == null) {
throw new MeasurementException();
}
System.out.println("The detailed info : " + this.time + "-" + this.temp+ " "+ this.wind+ "-" + this.humid );
}
}
}
Following the 3 steps (ignoring the Json part) u mentioned and reusing some of your code i can provide u this code:
Main.java:
public class Main {
static HashMap<String, Measurement> measurements = new HashMap();
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {//Create 3 measurements
String time = ""+i;
measurements.put(time, new Measurement(time, (float) i, (float) i, (float) i));
}
System.out.println("Please enter time :");
Scanner scan = new Scanner(System.in);
String value = scan.nextLine();//Read input-time
Measurement measurement = measurements.get(value);//there can only be 1 Measurement for 1 time
if(measurement != null){
System.out.println(measurement);
}
}
}
Measurement.java:
public class Measurement {
String time ;
Float temp;
Float wind;
Float humid;
int iD;
public Measurement(String d, Float t, Float w, Float h){
this.time = d;
this.temp = t;
this.wind = w;
this.humid = h;
}
#Override
public String toString() {
return "The detailed info : " + this.time + "-" + this.temp+ " "+ this.wind+ "-" + this.humid;
}
}
It might not fit exactly your needs but it can be a help.
Java is returning string values when reading off a text file, but it will only return "0" for my integer values and "0.0" for my doubles.
Cars car[] = new Cars[5];
int cnt = 0;
String line = inF.readLine();
while(line != null){
String[] field = line.split("\\s+");
int yrData = Integer.parseInt(field[2]);
double disData = Double.parseDouble(field[3]);
car[cnt] = new Cars(field[0], field[1], yrData, disData);
cnt++;
line = inF.readLine();
}
for(int i=0; i<cnt; i++){
System.out.println(i+1 +": "+ car[i]);
}
Example:
What Java Returns--->
1: Name: Opel Model: Astra Year: 0 Disp: 0.0
What is in the text file:Opel Astra 1997 2.8
This is my constructor:
Cars(String dataForName, String dataForModel, int dataForYear, double dataForDisp){name = dataForName; model = dataForModel; int year = dataForYear; double disp = dataForDisp;}
This is my toString method:
public String toString(){String s = "Name: "+name+" Model: "+model+" Year: "+year+" Disp: "+disp; return s;}
The delimiter of the text is space(s).
The problem is in your constructor:
Cars(String dataForName, String dataForModel, int dataForYear, double dataForDisp){
name = dataForName;
model = dataForModel;
int year = dataForYear;
double disp = dataForDisp;
}
you declare a new variable year and disp inside the constructor instead of setting the field in your class. As a result, those values are never set so they use the default values of 0 and 0.0 respectively.
changing it to
Cars(String dataForName, String dataForModel, int dataForYear, double dataForDisp){
name = dataForName;
model = dataForModel;
year = dataForYear;
disp = dataForDisp;
}
should work.
Everytime I run this program to create a new object it is supposed to start at 1000 and each time it is created increment by one. How do I increment the count of this independant of the count of the array.
Right now each time i run the program it outputs an Id of 1000 for each
Please be as simple as possible I don't understand java that well. thanks
Main program
import javax.swing.JOptionPane;
public class useConcert {
private static Concert[] concert = new Concert[100];
private static int numConcert = 0;
public static void main (String[] args){
String userInput = "";
boolean testResult;
do {
userInput = mainMenu();
if (userInput.equals("1")) {
do{
String artist = getStringInput("Artist or Group name?");
int month = getIntegerInput("Enter month in XX format ");
int day = getIntegerInput("Enter day in XX format ");
int year = getIntegerInput("Enter year in XXXX format");
int ticketCost = getIntegerInput("Enter cost per ticket ($25 - $250)");
int quantTickets = getIntegerInput("Enter Number of tickets available (Max 10,000)");
int concertId = 1000;
concert[numConcert++] = new Concert(artist,quantTickets,ticketCost,month,day,year,concertId);
}while (JOptionPane.showConfirmDialog(null, "Add another concert?")==JOptionPane.YES_OPTION);
} else if (userInput.equals("2")) {
listConcert();
}
} while (!userInput.equals("0"));
public static String concertList(){
String outputString = "";
for (int idx =0; idx < numConcert; idx++){
outputString += concert[idx].shortString() + "\n";
}
return outputString;
}
public static void listConcert() {
EZJ.dialog(concertList());
}
}
Class
public class Concert {
private String artist = "";
private int quantTickets = 0;
private int ticketCost = 0;
private int month = 0;
private int day = 0;
private int year = 0;
private int numConcert = 0;
private int concertId = 1000;
public Concert(String artist, int quantTickets, int ticketCost, int month, int day, int year, int concertId){
this.artist = artist;
this.quantTickets = quantTickets;
this.ticketCost = ticketCost;
this.month = month;
this.day = day;
this.year = year;
this.concertId = concertId;
}
public void setConcertId (int concertId){
concertId++;
this.concertId = concertId;
}
public String shortString(){
return " " + artist + " " + getConcertId();
}
There is no reason to keep the concert ID separate from the array count. In fact, the array count would be a very good concert ID. You would just have to modify this line to read:
concert[numConcert++] = new Concert(artist, quantTickets, ticketCost, month, day, year, numConcert);