Ok, so I'm more of a dunce than a beginner so bear with me.
What I'm trying to accomplished is to try to set/add variable within an array.
The question I am doing is to create a package and call another method called addAccommodation(); and use that method to add the required info and adding it to TravelPackage travelpackage.
I'm posting section of the issue here. The arraylist is called travelPackages and the one I want to add variables into is TravelPackage travelpackage.
(addAccommodation(); is the method soppose to lead another section, and travelpackage.setAccID is the issue I'm trying to solve)
public void addPackages() {
Scanner input = new Scanner(System.in);
System.out.println("Input Customer ID: ");
int customerID = input.nextInt();
input.nextLine();
System.out.print("Input Duration in Days: ");
int duration = input.nextInt();
input.nextLine();
System.out.print("Date in format yyyy-mm-dd? ");
String date = input.nextLine();
LocalDate startDate = null;
try{
startDate = LocalDate.parse(date);
}
catch(Exception e){}
TravelPackage travelpackage = new TravelPackage(customerID, duration, startDate);
travelPackages.add(travelpackage);
addAccommodation();
}
public void addAccommodation(){
Scanner input = new Scanner(System.in);
boolean match = false;
while(true) {
System.out.print("Input Accommodation Type(Hotel, Lodge, Ski Club, Apartment, Village): ");
String type = input.nextLine();
for (Accommodation a: accommodations) {
if (a.getType().equalsIgnoreCase(type) && a.getAvailability()) {
// Update accommodation status in ArrayList
a.setAvailability(false);
travelpackage.setAccID(a.getAccID());
// Set match flag to break loop
match = true;
// Stop searching for matching bike
break;
}
}
if(match){
System.out.println("Did not find a match.");
break;
}
}
}
It keep saying cannot find symbol. Is there something I'm missing here? (Sorry if I can't provide proper info, I am quite dumb)
currently, I'm doing an assignment that deals with the ArrayList class.
at some point, I need to check of the id of the instructor and make sure that the instructor is not added twice to the ArrayList, so I made a for loop to go through all the id that has been registered and get the id and check if it exists already
the problem is when I use the method " .size()" in the loop, the JVM throws NullPointerException
and I don't know why.
==========================================================================
what I need to read is this:
\\name - id - dateOfBirth - gender - degree - speciality - city - availability
Amanda Smith, 102020, 320101200000, M, PhD, Software Engineering, NewYork, true
=======================================================================
this is the code:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) { //ERROR OCCURE
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
The problem is membersList doesn't exist when you call .size() on it
instead of
ArrayList<UniversityMember> membersList;
you need to initialize it
ArrayList<UniversityMember> membersList = new ArrayList<UniversityMember>();
You need to initialize the ArrayList.
Like that ArrayList membersList = new ArrayList();
After that, in the first size() returns 0 and not null. Remember all data structure must be initialize in java.
You haven't added anything to the membersList then asking for the size for something that has nothing in it.
Example of whats going on
String str;
for(int i = 0; i < str.length(); i++){
System.out.println("hey");
}
also you need to declare the array list like this
ArrayList<Method name> membersList = new ArrayList<Method name>();
also don't forget to import the ArrayList class
import java.util.ArrayList;
nvm I figured out that I haven't initialized my array ( ╥ω╥ )
I'll keep the question for others to be carefull
==================================================
The code after fixing it:
public static void main(String[] args) {
/* NOTE: I HAVE A CLASS CALLED "UniversityMember" THAT IS A SUPERCLASS FOR "Instructor" CLASS */
//declare what I need
ArrayList<UniversityMember> membersList;
Scanner read = new Scanner("inputFile.txt");//the file contains the text above
/* ===== FIXING THE ERROR ======*/
membersList = new ArrayList();
//First: Split the line everytime the sign ", " shows
String[] line = read.nextLine().split(", ");
//Second: Assign each valuse to its correspondeding variable
String name = line[0];
String id = line[1];
long date = Long.parseLong(line[2]);
Date birthDate = new Date(date);
char gender = line[3].charAt(0);
String degree = line[4];
String specialization = line[5];
String address = line[6];
boolean availability = Boolean.parseBoolean(line[7]);
//check if the Id is registered already
for (int i = 0; i < membersList.size(); i++) {
if (membersList.get(i) == null) {
break;
}
if (membersList.get(i).id.equals(id)) {
System.out.println("The instructor is registered already, the ID is found in the system.");
System.exit(0);
}
}
//add and make a new object for the constructor
membersList.add(new Instructor(name, id, birthDate, gender, degree, specialization, address, availability));
System.out.println("The instructor is successfully added.");
}//end main
I would like to calculate the number of the overlapping days between two date ranges. The 2 pairs of date ranges are read from the console in the format: yyyy-mm-dd;
For example, if the two dates are
2020-01-05
2020-03-31
and
2020-01-05
2020-03-20
the program should find the days between 2020-01-05 and 2020-03-20. However, it doesn't work. I would like to ask how can I fix this?
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;
public class Dates {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String b = sc.nextLine();
String c = sc.nextLine();
String d = sc.nextLine();
LocalDate ldt1 = LocalDate.parse(a);
LocalDate ldt2 = LocalDate.parse(b);
LocalDate ldt3 = LocalDate.parse(c);
LocalDate ldt4 = LocalDate.parse(d);
System.out.println(ChronoUnit.DAYS.between(ldt1,ldt2,ldt3,ldt4));
}
}
It’s a little more complicated than that (not badly).
String i1StartStr = "2020-01-05";
String i1EndStr = "2020-03-31";
String i2StartStr = "2020-01-05";
String i2EndStr = "2020-03-20";
LocalDate i1Start = LocalDate.parse(i1StartStr);
LocalDate i1End = LocalDate.parse(i1EndStr);
LocalDate i2Start = LocalDate.parse(i2StartStr);
LocalDate i2End = LocalDate.parse(i2EndStr);
if (i1End.isBefore(i1Start) || i2End.isBefore(i2Start)) {
System.out.println("Not proper intervals");
} else {
long numberOfOverlappingDates;
if (i1End.isBefore(i2Start) || i2End.isBefore(i1Start)) {
// no overlap
numberOfOverlappingDates = 0;
} else {
LocalDate laterStart = Collections.max(Arrays.asList(i1Start, i2Start));
LocalDate earlierEnd = Collections.min(Arrays.asList(i1End, i2End));
numberOfOverlappingDates = ChronoUnit.DAYS.between(laterStart, earlierEnd);
}
System.out.println("" + numberOfOverlappingDates + " days of overlap");
}
Output from the code as it stands here is:
75 days of overlap
I have also used better variable names and have introduced validation of the intervals that the user inputs.
I know I was supposed to add some explanation here, but frankly, I find the code using java.time so clear to read in itself, I don’t know what needs to be explained. If you want the number of days inclusive of both start and end dates, remember to add 1 to the return value from ChronoUnit.DAYS.between(). Please follow up in the comments and let me know what further explanation will be appropriate.
The overall project is creating a system manager for airports. It keeps track of airports, flights, seating sections, seats and other relevent info for each of those catagories. The initial system is set up by importing from a file that's formatted a certain way. I'm having problems parsing the file properly to set up the initial system. the data is parsed from the file and used as method parameters to create the objects: Airport, Airline, Flight, FlightSection, and Seat.
the formatting is:
[list-of-airport-codes] {list-of-airlines}
list-of-airport-codes ::= comma-separated strings
list-of-airlines ::= airline-name1[flightinfo-list1], airline-name2[flightinfo-list2], airlinename3[flightinfo-list3], …
flightinfo-list ::= flightID1|flightdate1|originAirportCode1|destinationAirportCode1[flightsectionlist1], flightID2|flightdate2|originAirportCode2|destinationAirportCode2[flightsection-list2], …
flightdate ::= year, month, day-of-month, hours, minutes
flightsection-list ::= sectionclass: seat-price: layout: number-of-rows, …
sectionclass ::= F, B, E (for first class, business class, economy class)
layout ::= S, M, W (different known seating layouts)
example:
[DEN,NYC,SEA,LAX]{AMER[AA1|2018,10,8,16,30|DEN|LAX[E:200:S:4,F:500:S:2],
AA2|2018,8,9,7,30|LAX|DEN[E:200:S:5,F:500:S:3], …], UNTD[UA21|2018,11,8,12,30|NYC|SEA[E:300:S:6,F:800:S:3], UA12|2018,8,9,7,30|SEA|DEN[B:700:S:5, F:1200:S:2], …], FRONT[…], USAIR[…]}
I tried brute forcing it using a combination of delimiters and while loops. The code successfully creates the Airports, first Airline and Flighsections, but when it gets to creating the second airline it crashes, because i'm not looping properly, and having a hard time getting it right. My code for it as of now, is a mess, and if you're willing to look at it, I would appreciate any constructive input. My question is what would be a better way to approach this? A different design approach? Maybe a smarter way to use the delimiters?
Thanks in advance for your help!!
here's what i've tried.
private void readFile(File file){
System.out.println("reading file");
Scanner tempScan;
String result;
String temp = "";
scan.useDelimiter("\\[|\\{");
try{
// AIRPORTS
result = scan.next();
tempScan = new Scanner(result);
tempScan.useDelimiter(",|\\]");
while(tempScan.hasNext()){
temp = tempScan.next();
sysMan.createAirport(temp);
}
tempScan.close();
/* AIRLINE
* FLIGHT
* FLIGHTSECTION
*/
do{
// AIRLINE (loop<flight & fsection>)
result = scan.next();
sysMan.createAirline(result);
// FLIGHT
result = scan.next();
tempScan = new Scanner(result);
do{
tempScan.useDelimiter(",|\\|");
ArrayList flightInfo = new ArrayList();
while(tempScan.hasNext()){
if(tempScan.hasNextInt()){
flightInfo.add(tempScan.nextInt());
} else {
flightInfo.add(tempScan.next());
}
}
tempScan.close();
sysMan.createFlight(sysMan.getLastAddedAirline(),(String)flightInfo.get(0), (int)flightInfo.get(1), (int)flightInfo.get(2), (int)flightInfo.get(3), (int)flightInfo.get(4), (int)flightInfo.get(5), (String)flightInfo.get(6), (String)flightInfo.get(7));
// FLIGHTSECTION (loop<itself>)
result = scan.next();
tempScan = new Scanner(result);
tempScan.useDelimiter(",|:|\\]");
ArrayList sectInfo = new ArrayList();
int i = 1;
while(!temp.contains("|")){
if(tempScan.hasNextInt()){
sectInfo.add(tempScan.nextInt());
} else {
temp = tempScan.next();
if(temp.equals(""))
break;
char c = temp.charAt(0);
sectInfo.add(c);
}
if(i == 4){
sysMan.createSection(sysMan.getLastAddedAirline(), sysMan.getLastAddedFlightID(), (char)sectInfo.get(0), (int)sectInfo.get(1), (char)sectInfo.get(2), (int)sectInfo.get(3));
i = 1;
sectInfo = null;
sectInfo = new ArrayList();
continue;
}
i++;
}
}while(!temp.equals("\\s+"));
}while(!temp.contains("\\s+"));
}catch(NullPointerException e){
System.err.println(e);
}
}
I'd rather chunk it down by regexp mathing the outer bounds, have a look, I took it a couple of levels broken.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tokeni {
static String yolo = "[DEN,NYC,SEA,LAX]{AMER["
+ "AA1|2018,10,8,16,30|DEN|LAX[E:200:S:4,F:500:S:2],"
+ "AA2|2018,8,9,7,30|LAX|DEN[E:200:S:5,F:500:S:3]],"
+ "UNTD[UA21|2018,11,8,12,30|NYC|SEA[E:300:S:6,F:800:S:3],"
+ "UA12|2018,8,9,7,30|SEA|DEN[B:700:S:5, F:1200:S:2]]}";
public static void main(String[] args) {
Matcher airportCodesMatcher = Pattern.compile("\\[(.*?)\\]").matcher(yolo);
airportCodesMatcher.find();
String[] airportCodes = airportCodesMatcher.group(1).split(",");
Matcher airLinesMatcher = Pattern.compile("\\{(.*?)\\}").matcher(yolo);
airLinesMatcher.find();
String airLinesStr = airLinesMatcher.group(1);
System.out.println(airLinesStr);
Pattern airLinePattern = Pattern.compile("\\D+\\[(.*?)\\]\\]");
Matcher airLineMatcher = airLinePattern.matcher(airLinesStr);
while( airLineMatcher.find() ) {
String airLineStr = airLineMatcher.group(0).trim();
if(airLineStr.startsWith(",")) {
airLineStr = airLineStr.substring(1, airLineStr.length()).trim();
}
System.out.println(airLineStr);
Matcher airLineNameMatcher = Pattern.compile("[A-Z]+").matcher(airLineStr);
airLineNameMatcher.find();
String airLineName = airLineNameMatcher.group(0).trim();
System.out.println(airLineName);
airLineStr = airLineStr.substring(airLineStr.indexOf("[")+1, airLineStr.length());
Matcher airLineInfoMatcher = Pattern.compile("\\D+(.*?)\\]").matcher(airLineStr);
while(airLineInfoMatcher.find()) {
String airLineInfoStr = airLineInfoMatcher.group(0).trim();
if(airLineInfoStr.startsWith(",")) {
airLineInfoStr = airLineInfoStr.substring(1, airLineInfoStr.length()).trim();
}
System.out.println(airLineInfoStr);
}
}
}
}
My code like belows, I am using android. I found different devices may have different result.
Using different phone: I can get : "EST" or "GMT-05:00".
However, I just want to get abbreviation(just like "EST").
How can I get the abbreviation (or change offset to abbreviation)?
String timezone =Calendar.getInstance().getTimeZone().getDisplayName(false, TimeZone.SHORT);
If anyone else need the solution : I just tweak the code and get desired short name, which i needed to display to user.
private static String getTimeZoneShortName() {
String tz = TimeZone.getDefault().getDisplayName();
String[] stz = tz.split(" ");
StringBuilder sName = new StringBuilder();
for (int i = 0; i < stz.length; i++) {
sName.append(stz[i].charAt(0));
}
return sName.toString();
}