Method for finding desired conditions - java

I am trying to make my method display people who are born during the month of July.
class Personne {
private String naissance;
private int nbCafe;
public Personne(String year, int number) {
naissance = year;
nbCafe = number;
}
public Personne(String year) {
naissance = year;
nbCafe = 1;
}
public String getNaissance() {
return naissance;
}
public int getNbcafe() {
return nbCafe;
}
public void afficher(String message) {
System.out.println(message + ": nee le 16 novembre 1994, consomme 2 tasse(s) de cafe");
}
static void afficherTable(Personne[] pers, int amount) {
System.out.printf("\nContenu du tableau de %d personne(s)\n", amount);
System.out.printf("nbPers Birth numCafe\n");
for (int i = 0; i < amount; i++)
System.out.printf(" %d) %s %d\n", i, pers[i].getNaissance(), pers[i].getNbcafe());
}
static void demo1(Personne[] pers, int amount) {
int count = 0;
String juillet = "07";
for (int i = 0; i < amount; i++)
if (pers[i].toString().substring(3, 5) == juillet) {
count++;
}
System.out.println(count);
}
}
public class popo {
public static void main(String args[]) {
Personne p1 = new Personne("16/11/1994", 2);
Personne p2 = new Personne("15/12/1990");
Personne[] pers = {new Personne("12/10/1991", 3),
new Personne("15/10/1990", 6),
new Personne("13/07/1993", 3),
new Personne("05/06/1991"),
new Personne("16/12/1992", 3)};
int nbpers = pers.length;
p1.afficher("Informations de p1");
Personne.afficherTable(pers, nbpers);
Personne.demo1(pers, nbpers);
}
}
The method demo1() in my class is supposed to pick out the people who are born in July but it doesn't seem to work. I've tried using charAt/indexOf/substring to get the month from "Naissance" to no avail. Is there another way of finding what you want from a table of strings?

I would add this to the Personne class:
public int getMonth(){
return Integer.parseInt(this.naissance.substring(3,5));
}
Then you can call
If (pers[i].getMonth == 7)

The problem is that you're using:
pers[i].toString().substring(3, 5) == juillet)
You need to use
pers[i].getNaissance().substring(3, 5).equals(juillet))
since you're looking for the month from the naissance field.
You should use the String.equals(String other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. More info: Java String.equals versus ==

static void demo1(Personne[] pers, int amount){
int count = 0;
final String juillet = "07";
for (int i=0; i<amount; i++)
if (pers[i].naissance.substring(3,5).equals(juillet)) {
count++;
}
System.out.println(count);
}
}
The toString method was not overriden, you intended to use getNaissance() or so.
Also comparing strings is done with equals, not ==.
Instead of amount you may use pers.length.

if(pers[i].toString().substring(3,5)== juillet) has to be
if(pers[i].toString().substring(3,5).equals(juillet))

Honestly I'ld do in this way:
static void demo1(Personne[] pers, int amount) throws ParseException{
int count=0;
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(true);
Calendar c = GregorianCalendar.getInstance();
int juillet=7;
for (int i=0; i<amount;i++)
{
Date d = sdf.parse(pers[i].getNaissance());
c.setTime(d);
int month = c.get(Calendar.MONTH)+1;
if( month == juillet )
{
count++;
}
}
System.out.println(count);
}
Angelo

Related

Algorithm to find maximum classes attended by student | activity selection problem

Algorithm asked in one of the top company's interview, but I am not able to find a feasible solution. Need expert advice.
Suppose a student wants to attend maximum number of classes in a collage in a day (without any class overlap).
Input Format
The first line contains an integer n which gives the number of subjects offered on that day.
The next n lines follow containing the subject name (which is a string) followed by the start and end time for that subject in 24-hour format: hh:mm
For eg: Maths 10:00 11:00
Note: The timings are given in a 24-hour format and the subject names do not have spaces between them.
Output Format
The output should contain a number representing the maximum number of classes the student can choose.
Constraints
2 <= n <= 100
start time of a class < end time of class
Sample Input
4
Maths 16:00 18:00
ComputerScience 12:00 13:00
Physics 12:30 14:00
Chemistry 14:00 16:30
Sample Output
2
Explanation
ComputerScience starts the earliest and ends the earliest, so we take it first. After that, we cannot take Physics because it starts before ComputerScience is over. So we will take the next class, that is, Chemistry. But after Chemistry we cannot take Maths as Maths class starts before Chemistry class ends. So we can schedule a maximum of 2 classes for the day.
Below is my solution but I am not getting correct answer:
private void getMaxClass(String input) {
Map<String, Long> classTime = new LinkedHashMap<>();
Map<String, List<String>> timeMap = new LinkedHashMap<>();
String[] split = input.split(" ");
String subject = split[0];
String StartTime = split[1];
String endTime = split[2];
List<String> lvalue = new ArrayList<>();
lvalue.add(StartTime);
lvalue.add(endTime);
timeMap.put(subject, lvalue);
long difference = FineDifferenceInTime(StartTime, endTime);
classTime.put(subject, difference);
int count = 0;
Date date1 = null;
Date date2 = null;
Map<String, Long> sortedByValueDesc = classTime.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
for (Map.Entry<String, Long> entry : sortedByValueDesc.entrySet()) {
String sub = entry.getKey();
List<String> startEnd = timeMap.get(sub);
Date dateBefore = null;
Date dateAfter = null;
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
try {
dateBefore = format.parse(startEnd.get(0));
dateAfter = format.parse(startEnd.get(1));
} catch (ParseException e) {
e.printStackTrace();
}
if (count == 0) {
count++;
try {
date1 = format.parse(startEnd.get(0));
date2 = format.parse(startEnd.get(1));
} catch (ParseException e) {
e.printStackTrace();
}
}
if (dateBefore.after(date1) && dateBefore.before(date2)) {
timeMap.remove(sub);
}
}
System.out.println(timeMap.size());
}
This is known in literature as the Interval Scheduling Problem. There are many ways to solve it, but since it is NP-complete (as there is a a polynomial reduction from VC) you'll necessarily need to explore all the combinations.
Greedy algorithms do exist (as is yours and the solution by #PriyankaDeshmukh), but they don't guarantee you the exact solution for all instances of the problem.
The solution below is a simple tree search: at each level we decide if we take a given course or not and move on to decide on the next course.
You could also implement a dynamic programming solution.
Here is a very good blog post covering solutions to the Interval Scheduling Problem.
I modelled a student class the following way:
class StudentClass {
public int _start;
public int _end;
public String _name;
public StudentClass(String name, int start, int end) {
_name = name;
_start = start;
_end = end;
}
public boolean overlapsWith(StudentClass other) {
return _start < other._end && _end > other._start;
}
public String toString() {
return "[" + _start + " - " + _end + "] " + _name;
}
}
There are classes to represent the time of the day, but their syntax/instantiation is a bit annoying/verbose -- feel free to improve this answer though! My Java is also very rusty, so feel free to correct me :-)
The Schedule class has a getMaxSchedule() which returns the solution to the problem -- what is the maximum number of classes a student can take, such that none of them overlap?
There are a few ways to optimize it, but I left it as-is as I believe it's easier to be understood.
public class Schedule {
List<StudentClass> _classes = new LinkedList<>();
public void addClass(String name, int startTime, int endTime) {
_classes.add(new StudentClass(name, startTime, endTime));
}
private int getMaxSchedule(int index, Collection<StudentClass> selected) {
// check if we reached the end of the array
if (index >= _classes.size()) {
return 0;
}
StudentClass current = _classes.get(index);
// check if taking this class doesn't conflict with the
// previously-selected set of classes
boolean canTakeThisClass = true;
for (StudentClass other : selected) {
if (current.overlapsWith(other)) {
canTakeThisClass = false;
break;
}
}
// check best schedule if we don't take this class
int best = getMaxSchedule(index + 1, selected);
// check best schedule if we take this class (if such is possible)
if (canTakeThisClass) {
selected.add(current);
best = Math.max(best, 1 + getMaxSchedule(index + 1, selected));
selected.remove(current);
}
return best;
}
public int getMaxSchedule() {
Collection<StudentClass> selected = new ArrayList<>();
return getMaxSchedule(0, selected);
}
}
You can see the result is 3 for your concrete problem through the following:
public static void main(String[] args) {
Schedule s = new Schedule();
s.addClass("Maths", 1600, 1800);
s.addClass("Computer Science", 1200, 1300);
s.addClass("Physics", 1230, 1400);
s.addClass("Chemistry", 1400, 1630);
System.out.println("maximum classes: " + s.getMaxSchedule());
}
I tried it with Python. It gives correct output.
I got it sorted by start time of class.
sorted_by_start = [{'sub': 'ComputerScience', 'start': '12:00', 'end': '13:00',
'duration': 60}, {'sub': 'Physics', 'start': '12:30', 'end': '14:00', 'duration':
90}, {'sub': 'Chemistry', 'start': '14:00', 'end': '16:30', 'duration': 150},
{'sub': 'Maths', 'start': '16:00', 'end': '18:00', 'duration': 120}]
possible_sub = set()
for a, b in itertools.combinations(sorted_by_start, 2):
strt_tme = datetime.datetime.strptime(a["end"], '%H:%M')
end_tme = datetime.datetime.strptime(b["start"], '%H:%M')
if(strt_tme <= end_tme) :
possible_sub.add((a["sub"],b["sub"]))
print("A student can attend these combinations of subject classes:",possible_sub)
print("Maximum classes student can attend in a day is: ",max(map(len,possible_sub)))
Here trick part is deciding how many combinations you can make. So, that you can do by adding additional for loop ranging from 2 to length of sorted_list and pass i to combinations(sorted_list, i) like this.
Ouput is :
A student can attend these combinations of subject classes: {('Physics', 'Maths'), ('Physics', 'Chemistry'), ('ComputerScience', 'Chemistry'), ('Compu
terScience', 'Maths')}
Maximum classes student can attend in a day is: 2
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class InputSubject implements Comparable<InputSubject>{
String subject;
String startTime;
String endTime;
InputSubject(){
}
InputSubject(String subject, String startTime, String endTime){
this.subject = subject;
this.startTime = startTime;
this.endTime = endTime;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
#Override
public int compareTo(InputSubject o) {
return this.endTime.compareTo(o.endTime);
}
}
public class SubjectSort {
static int getToatlSubject(List<InputSubject> list){
String sTime = null;
String eTime = null;
int count = 0;
int noOfSubject = 0;
for(InputSubject object : list){
if(count == 0){
count++;
eTime = object.getEndTime();
noOfSubject ++;
}
else {
if(object.getStartTime().compareTo(eTime) > 0){
eTime = object.getEndTime();
noOfSubject ++;
}
}
}
return noOfSubject;
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
int days = Integer.parseInt(reader.readLine());
for(int i = 0 ; i < days ;i++){
int sub = Integer.parseInt(reader.readLine());
List<InputSubject> list = new ArrayList<>();
for(int k = 0 ; k < sub ; k++){
InputSubject inputSubject = null;
String subDetails = reader.readLine();
String[] subAndTimes = subDetails.split(" ");
inputSubject = new InputSubject(subAndTimes[0],subAndTimes[1],subAndTimes[2]);
list.add(inputSubject);
}
Collections.sort(list);
System.out.println(getToatlSubject(list));
}
} catch (Exception e) {
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class InputSubject implements Comparable<InputSubject>{
String subject;
String startTime;
String endTime;
InputSubject(){
}
InputSubject(String subject, String startTime, String endTime){
this.subject = subject;
this.startTime = startTime;
this.endTime = endTime;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
#Override
public int compareTo(InputSubject o) {
return this.endTime.compareTo(o.endTime);
}
}
public class solution {
static int getToatlSubject(List<InputSubject> list){
String sTime = null;
String eTime = null;
int count = 0;
int noOfSubject = 0;
for(InputSubject object : list){
if(count == 0){
count++;
eTime = object.getEndTime();
noOfSubject ++;
}
else {
if(object.getStartTime().compareTo(eTime) >= 0){
eTime = object.getEndTime();
noOfSubject ++;
}
}
}
return noOfSubject;
}
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
int days = Integer.parseInt(reader.readLine());
for(int i = 0 ; i < days ;i++){
int sub = Integer.parseInt(reader.readLine());
List<InputSubject> list = new ArrayList<>();
for(int k = 0 ; k < sub ; k++){
InputSubject inputSubject = null;
String subDetails = reader.readLine();
String[] subAndTimes = subDetails.split(" ");
inputSubject = new InputSubject(subAndTimes[0],subAndTimes[1],subAndTimes[2]);
list.add(inputSubject);
}
Collections.sort(list);
System.out.println(getToatlSubject(list));
}
} catch (Exception e) {
}
}
}
i had same question in a coding round of a recruitment and I have solved it the following way and it gives correct answer. But unfortunately this code passed only 1 test case given in the challenge. I believe that the test cases were incorrect. Can anyone point out if I have missed something in code which might have led to this code failing other test cases?
import java.util.*;
import java.time.*;
import java.time.format.DateTimeFormatter;
import static java.time.temporal.ChronoUnit.*;
class solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
int n=sc.nextInt();
String trash=sc.nextLine();
HashMap subjects=new HashMap<String,String>();
HashMap starttime=new HashMap<String,LocalTime>();
HashMap endtime=new HashMap<String,LocalTime>();
HashMap length=new HashMap<String,Long>();
for (int j = 0; j < n; j++){
String classes = sc.nextLine();
String[] classesArray=classes.split(" ");
String subject=classesArray[0];
if(classesArray[1].split(":")[0].length()==1){
classesArray[1]="0"+classesArray[1];
}
if(classesArray[2].split(":")[0].length()==1){
classesArray[2]="0"+classesArray[2];
}
LocalTime startTime=LocalTime.parse(classesArray[1]);
LocalTime endTime=LocalTime.parse(classesArray[2]);
DateTimeFormatter formatter = DateTimeFormatter.ISO_TIME;
Long lengthLecture=MINUTES.between(startTime, endTime);
subjects.put(subject,subject);
starttime.put(subject,startTime);
endtime.put(subject,endTime);
length.put(subject,lengthLecture);
String value = startTime.format(formatter);
String value1 = endTime.format(formatter);
// System.out.printf("Sub:%s st:%s et:%s length:%d\n",subject,value,value1,lengthLecture);
}
findMax(subjects,starttime,endtime,length);
//System.out.println(num);
}
}
public static void findMax(HashMap<String,String> subs,HashMap<String,LocalTime> strt,HashMap<String,LocalTime> endt,HashMap<String,Long> length){
int number=0;
List<Integer> list = new ArrayList<Integer>();
String curr,next1;
for (Map.Entry<String,String> entry : subs.entrySet()){
//System.out.println("Checkign for number: "+entry.getKey());
number=findnext(entry.getKey(),strt,endt);
// System.out.println("Number is: "+number);
list.add(number);
}
System.out.println(Collections.max(list));
}
public static int findnext(String subjt,HashMap<String,LocalTime> strt,HashMap<String,LocalTime> endt){
String sub=subjt;
int number=1;
LocalTime substtime=strt.get(subjt);
LocalTime subedtime=endt.get(subjt);
Long timetillstart=922337203L;
for (Map.Entry<String,LocalTime> entry : strt.entrySet()){
if((entry.getValue().compareTo(subedtime)>=0) && (MINUTES.between(subedtime, entry.getValue())<=timetillstart)){
sub=entry.getKey();
substtime=strt.get(entry.getKey());
timetillstart=MINUTES.between(subedtime, entry.getValue());
}
}
if(sub!=subjt){
number=number+findnext(sub,strt,endt);
}
return number;
}
}

set method is not working

I was doing one of my projects and couldn't really work my set method. And my set constructor was not working. I am new in class and need help. it will be a great help if you guys help me thank you.
My Class is:
public class date {
private int day;
private int month;
private int year;
public date ()
{
day = 1;
month = 1;
year = 1900;
}
I set up the constructor hear this is how it goes:
// set constructor
public date (int a,int b,int c) //(day,month,year)
{
if (a <1)
{
day = 1;
a = day;
}
if (b<1)
{
month = 1;
b = month;
}
if (c<1900)
{
year = 1900;
c = year;
}
else
{
a = day;
b = month;
c = year;
}
}
this is where I started to set the veribals as an mutators
// set date
public void setDay (int a)
{
if (a <1)
{
day = 1;
a = day;
}
else
a = day;
}
// set month
public void setMonth (int a)
{
if (a <1)
{
month = 1;
a = month;
}
else
a = month;
}
// set year
public void setYear (int a)
{
if (a <1990)
{
year = 1990;
a = year;
}
else
a = year;
}
And this is where I started to write my accessories
//Accsessors
public int getDay ()
{
return day;
}
public int getMonth ()
{
return month;
}
public int getYear ()
{
return year;
}
}
my main class is:
public class checkDate {
public static void main (String [] args)
{
date year1 = new date();
date year2 = new date (21,3,1995);
year1.setDay(13);
year1.setMonth(12);
year1.setYear(2010);
System.out.println(year1.getDay());
System.out.println(year1.getYear());
System.out.println(year2.getYear());
}
}
Output is:
1
1900
0
I tried checking everything I even tried to change the value but nothing works only thing I get is 1 and 1900
Many of the assignment statements are backwards. The expression on the right of the equals is assigned to the variable on the left. Here is what they should look like instead:
public date(int a, int b, int c) {
if (a < 1)
a = 1;
if (b < 1)
b = 1;
if (c < 1900)
c = 1900;
day = a;
month = b;
year = c;
}
The setters have a similar problem. Don't assign to the parameter, assign to the instance variable.
public void setDay(int a) {
if (a < 1)
a = 1;
day = a;
}
public void setMonth(int a) {
if (a < 1)
a = 1;
month = a;
}
public void setYear(int a) {
if (a < 1990)
a = 1990;
year = a;
}
Note: For more readable code, use better parameter names. Instead of reusing a, perhaps you should use d, m or y depending on the setter. Also, typical Java naming conventions always capitalize the first letter of class names, so you should use Date instead of date.
You're only setting the day and month when they are less than 1, and the year when it's less than 1990. You should probably flip those "<" into ">".
The problem lies in your variable assignments.
You could condense your code like this, by using the ternary operator:
public class Date{
private int day;
private int month;
private int year;
public Date(int d, int m, int y){
day = d<1 ? 1 : d;
month = m<1||m>12 ? 1 : m;
year = y<1900 ? 1990 : y;
}
public int getDay(){
return day;
}
...
public void setDay(int d){
day = d<1 ? 1 : d;
}
...
}

Insert object element into array in ordered position, without using sort algorithm in Java

I have programming projectת I have it almost finished, but I am struggling on inserting a new object made from the console into the array at the correct position.
I can make the object, insert at either the beginning or end, delete object, etc. but the array needs to be in order (month, day, time) and I am stuck.
I have been searching for a good day and a half, through forums, info websites, books, etc. and cannot find an answer.
P.S. I am NOT allowed to use anything other than an array (ArrayList, LinkedList, etc), and i cannot use any sorting algorithms (bubblesort, insertionsort, etc.)
Directions call specifically for me to shift array elements as needed and put new object in between/at correct position. Also I am using NetBeans.
/*
*
*
*/
package project1;
import UserInput.UserInput;
public class Schedule {
Delivery[] deliObj = new Delivery[20];
int count = 0;
public Schedule(){//set default objects
deliObj[0] = new Delivery("MAR", 4, 17, 30, "Pizza");
count++;
deliObj[1] = new Delivery("APR", 1, 06, 30, "Special Deliery");
count++;
deliObj[2] = new Delivery("MAY", 6, 12, 00, "Amazon (Books)");
count++;
deliObj[3] = new Delivery("JUN", 3, 11, 15, "Car Parts");
count++;
}
public void setDelivery(Delivery[] deliObj){
this.deliObj = deliObj;
}
public Delivery[] getDelivery(){
return this.deliObj;
}
public static void main(String[] args){
Schedule scheduleObj = new Schedule();
scheduleObj.run();
}
public void run(){
System.out.println("\n***** MAIN DELIVERY CONSOLE *****\n");
System.out.println("A)dd delivery");
System.out.println("D)delete Delivery");
System.out.println("L)ist Delivery");
System.out.println("E)xit");
char selection = Character.toUpperCase(UserInput.getChar());
switch(selection){
case 'A': addDelivery();
break;
case 'D': deleteDelivery();
break;
case 'L': listDelivery();
break;
case 'E': System.exit(0);
}
}
public void addDelivery(){
Delivery getInputDelivery = new Delivery();
getInputDelivery.InputDelivery();
deliObj[count] = getInputDelivery;
count++;
insertDelivery(getInputDelivery);
run();
}
public void deleteDelivery(){
System.out.println("Please enter the number you wish to delete: ");
int num = UserInput.getInt(0,count);
//deliObj[num-1] = new Delivery();
deliObj[num-1] = null;
count--;
run();
}
public void listDelivery(){
for(int i=0;i<count;i++) {
System.out.println(i+1 + ". " + deliObj[i]);
}
run();
}
public boolean compareDelivery(Delivery A1, Delivery A2){
//Delivery delivery = deliObj[count-4];
int numMonth;
int numMonth1;
numMonth = Delivery.integerMonth(A1.getMonth());
numMonth1 = Delivery.integerMonth(A2.getMonth());
if(numMonth < numMonth1){
return true;
}
else if(numMonth == numMonth1){
if(A1.getDay() < A2.getDay()){
return true;
}
else if(A1.getDay() == A2.getDay()){
if(A1.getHour() < A2.getHour()){
return true;
}
else if(A1.getHour() == A2.getHour()){
if(A1.getMintute() < A2.getMintute()){
return true;
}
}
}
} //else return false;
return false;
}
public void insertDelivery(Delivery temp){
for(int i = 0; i < count; i++){
/*if(!compareDelivery(deliObj[i], temp)) {
for(int k = 1; k < count; k++) {
Delivery temp2 = deliObj[k];
deliObj[k] = deliObj[count-1];
deliObj[count-1] = temp2;
}*/
if(compareDelivery(deliObj[i], temp)) {
Delivery temp2 = deliObj[i];
deliObj[i] = deliObj[count-1];
deliObj[count-1] = temp2;
}
}
/*for (int k = 0; k < count-1; k++) {
if(compareDelivery(deliObj[k], temp)) {
Delivery temp2 = deliObj[k];
deliObj[k] = deliObj[count-1];
deliObj[count-1] = temp2;
//deliObj[count] = deliObj[k];
//deliObj[k] = deliObj[count-1];
}
} */
}
}
this is my main class where things are run, but here is the other subclass that has the constructors and getters/setters etc.
package project1;
import UserInput.UserInput;
public class Delivery {
private static final String FINAL_MONTH[] = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};
private String month;
private int day;
private int hour;
private int minute;
private int second;
private String userMessage;
public static int integerMonth(String compareMonth){
for(int i = 0; i < FINAL_MONTH.length; i++){
if(compareMonth.equals(FINAL_MONTH[i])){
return i;
}
}
return -1;
}
public Delivery(String month, int day, int hour, int minute, String userMessage) {
this.month = month;
this.day = day;
this.hour = hour;
this.minute = minute;
this.userMessage = userMessage;
}
public void setMonth(String month) {
for (String FINAL_MONTH1 : FINAL_MONTH) {
if (month.equalsIgnoreCase(FINAL_MONTH1)) {
this.month = month.toUpperCase();
}
}
}
public String getMonth() {
return this.month;
}
public void setDay(int day) {
this.day = day;
}
public int getDay() {
return this.day;
}
public void setHour(int hour) {
this.hour = hour;
}
public int getHour() {
return this.hour;
}
public void setMinute(int minute) {
this.minute = minute;
}
public int getMintute() {
return this.minute;
}
public void setSecond(int second) {
this.second = second;
}
public int getSecond() {
return this.second;
}
public void setUserMessage(String userMessage) {
this.userMessage = userMessage;
}
public String getUserMessage() {
return this.userMessage;
}
public Delivery() {
month = "JAN";
day = 1;
hour = 12;
minute = 00;
userMessage = "default";
}
#Override
public String toString() {
String data = String.format(month + " %02d, " + "%02d:" + "%02d " + userMessage, day, hour, minute);
return data;
}
public void InputDelivery() {
System.out.println("Enter month of delivery(3 letter abbreviation): ");
setMonth(UserInput.getString(3, 3));
System.out.println("Enter day of delivery: ");
setDay(UserInput.getInt(0, 31));
System.out.println("Enter hour of delivery (0-23): ");
setHour(UserInput.getInt(0, 24));
System.out.println("Enter minute of delivery (0-59): ");
setMinute(UserInput.getInt(0, 59));
System.out.println("Enter message for delivery (40 Character Max): ");
setUserMessage(UserInput.getString(0,40));
System.out.println(toString());
}
}
I really need help with just the insertDelivery() method, if you see other errors you can mention them but please try to just advise me on that portion!
I'll start by assuming that "anything other than an array" does not extend to utility classes such as java.util.Arrays. If it does, you will need to implement some the method I use below your self.
The first step is to either make your Delivery implement Comparable<Delivery> or make a new class that implements Comparator<Delivery>. This defines an ordering for your Delivery object. This change should be simple because you have already defined a compareDelivery method.
With this modification made, you can get the index of at which to insert the value by calling Arrays.binarySearch(deliObj,temp). If you aren't allowed to use the Arrays class, this link show a simple binary search implementation.
1 int[] data;
2 int size;
3
4 public boolean binarySearch(int key)
5 {
6 int low = 0;
7 int high = size - 1;
8
9 while(high >= low) {
10 int middle = (low + high) / 2;
11 if(data[middle] == key) {
12 return true;
13 }
14 if(data[middle] < key) {
15 low = middle + 1;
16 }
17 if(data[middle] > key) {
18 high = middle - 1;
19 }
20 }
21 return false;
22 }
Having this index, you now need to insert your object at this point. Using arrays however, this is slightly more difficult than it seems. The length of an Array is immutable, so you have to create a new Array that is one element longer than your current array before inserting the object. You'll be doing what happens behind the scenes in ArrayList, more or less.Inserting an element into an array has been covered on StackOverflow before, so I'll just refer you to a helpful answer.
public static int[] addPos(int[] a, int pos, int num) {
int[] result = new int[a.length];
for(int i = 0; i < pos; i++)
result[i] = a[i];
result[pos] = num;
for(int i = pos + 1; i < a.length; i++)
result[i] = a[i - 1];
return result;
}
In general you cannot insert an element into an array. Arrays are fixed length (they contain exactly n elements and you cannot alter an array to contain n+1 or n-1 elements). What you can do is create a new array that has space for n+1elements and copy the elements from the original array into the new array inserting the new element in the correct place as you create it. You can also create it to be too large in anticipation of getting more elements (looks like what you have done) and then start to shift the elements up.
This sounds like a homework question. Are you able to ask a someone (a lab helper, tutor, co-student) if you have the right idea? The requirements "I am NOT allowed to use anything other than an array" and the need to insert seem at odds.

How to use LinkedList class in java?

So I'm trying to design a program in java that provides average daily temperate (low and high) for a certain month of a year.I've created a class that include two methods one for the average low and one for the average high temperature.
Now I'm trying to add a method that consumes a date (day, month, year) and a List of readings (nominally for that date) and stores a daily report for the given date (computing the high and low temperature readings from the given list of readings for that date).
I am struggling with the last method, i don't fully understand how am i supposed to go on doing it (I am not supposed to enter examples for each day, rather just calculate the average of available readings of the days in a certain month).
So anyone could point me in the right direction, this is supposed to be a practice for using LinkedList class in java.
Public class DailyReadings{
int day;
int month;
int year;
int highTemperature;
int lowTemperature;
public DailyReading(int day, int month, int year, int highTemperature, int lowTemperature){
this.day = day;
this.month = month;
this.year = year;
this.highTemperature = highTemperature;
this.lowTemperature= lowTemperature;
}
}
public class WeatherMonitor extends DailyReadings {
int averageHighForMonth (this.month, this.year) {
int tempHighAvg = 0;
int tempSum = 0;
int x = 0;
for ( DailyReadings highTemperature : Report ) {
if (this.month=this.month){
tempSum = tempSum + highTemperature;
x = x++;
}
}
tempHighAverage = tempSum/x;
}
return tempHighAverage;
}
int averageLowForMonth (this.month, this.year){
int tempLowAvg = 0;
int tempSum = 0;
int x = 0;
for ( DailyReadings lowTemperature : Report ) {
if (this.month = this.month) {
tempSum = tempSum + lowTemperature;
x = x++;
}
}
tempLowAverage = tempSum/x;
}
return tempLowAverage;
}
int addDailyReport(int date, LinkedList<DailyReadings> ) {
}
}
class Examples {
LinkedList<DailyReadings> Report = new LinkedList<DailyReadings>;
}
Here's what I've go so far. I'm supposed to store some readings as described and use it in the "temperateHighAverage, and temperatureLowAverage). I'm not sure how to first create the list and also storing the data in it using the "addDailyReport" method.
Try this:
import java.util.Iterator;
import java.util.LinkedList;
public class TestClass {
public static void main(String[] args) {
WeatherMonitor wM = new WeatherMonitor();
DailyReadings dR = new DailyReadings(1,1,2020, 10, -20);
wM.addDailyReport(dR);
dR = new DailyReadings(1,2,2020, 10, -21);
wM.addDailyReport(dR);
dR = new DailyReadings(1,3,2020, 11, -20);
wM.addDailyReport(dR);
//...
System.out.println(wM.averageHighForMonth(1, 2020));
System.out.println(wM.averageLowForMonth(1, 2020));
}
}
class DailyReadings {
int day;
int month;
int year;
int highTemperature;
int lowTemperature;
public DailyReadings(int day, int month, int year, int highTemperature, int lowTemperature){
this.day = day;
this.month = month;
this.year = year;
this.highTemperature = highTemperature;
this.lowTemperature= lowTemperature;
}
}
class WeatherMonitor {
LinkedList<DailyReadings> Readings = new LinkedList<DailyReadings>();
int averageHighForMonth (int month, int year) {
int tempHighAvg = 0;
int count = 0;
Iterator<DailyReadings> it = Readings.iterator();
DailyReadings tmp;
while( (tmp = it.next()) != null) {
if (tmp.month == month && tmp.year == year) {
tempHighAvg += tmp.highTemperature;
count++;
}
}
return tempHighAvg / count;
}
int averageLowForMonth (int month, int year) {
int tempLowAvg = 0;
int count = 0;
Iterator<DailyReadings> it = Readings.iterator();
DailyReadings tmp;
while( (tmp = it.next()) != null) {
if (tmp.month == month && tmp.year == year) {
tempLowAvg += tmp.lowTemperature;
count++;
}
}
return tempLowAvg / count;
}
void addDailyReport(DailyReadings dR) {
Readings.add(dR);
}
}
//-----------------------
But some points that you should know :
int averageLowForMonth (this.month, this.year){// This is wrong!
You cannot define a method this way, parameters should be defined like this:
(type name, type name ,...)
BTW, you should use Composition in situations like this, not Inheritance.
First of all, your list parameter needs a name, something like
int addDailyReport(int date, LinkedList<DailyReadings> reportList )
Then you can use it inside the method and add the report with
reportList.add(this);

Sort dates in Java

I want to list dates from the most current date to the oldest date.
I don't want to use Collections.sort()so I made my own method.
When I do this :
List<Livre> maBibliotheque = new ArrayList<Livre>();
boolean tri = false;
int born = maBibliotheque.size();
while (tri == false)
{
tri = true ;
for (int i=0; i<born-1;i++)
{
if ( maBibliotheque.get(i).getNewPeriode().compareTo(maBibliotheque.get(i+1).getNewPeriode())>0){
Livre livre = maBibliotheque.get(i);
maBibliotheque.set(i, maBibliotheque.get(i+1));
maBibliotheque.set(i+1,livre);
tri = false ; }
}
born -= born;
}
It works perfectly, but from the oldest to the newest date, but I want the otherwise.
I change this line to
if ( maBibliotheque.get(i).getNewPeriode().compareTo(maBibliotheque.get(i+1).getNewPeriode())<0){
But it's doesn't make anything, no sort dates in this case. Please help
To reverse the order, replace > 0 with < 0
Doesn't
born -= born;
do the same as
born = 0;
I suspect this isn't needed.
This
public static void main(String[] args) throws IOException, IllegalAccessException, NoSuchFieldException {
List<Livre> maBibliotheque = new ArrayList<Livre>();
maBibliotheque.add(new Livre("aaa"));
maBibliotheque.add(new Livre("abb"));
maBibliotheque.add(new Livre("bbb"));
maBibliotheque.add(new Livre("000"));
boolean tri;
int born = maBibliotheque.size();
do {
tri = true;
for (int i = 0; i < born - 1; i++) {
if (maBibliotheque.get(i).getNewPeriode().compareTo(maBibliotheque.get(i + 1).getNewPeriode()) > 0) {
Livre livre = maBibliotheque.get(i);
maBibliotheque.set(i, maBibliotheque.get(i + 1));
maBibliotheque.set(i + 1, livre);
tri = false;
}
}
} while (!tri);
System.out.println("increasing: " + maBibliotheque);
do {
tri = true;
for (int i = 0; i < born - 1; i++) {
if (maBibliotheque.get(i).getNewPeriode().compareTo(maBibliotheque.get(i + 1).getNewPeriode()) < 0) {
Livre livre = maBibliotheque.get(i);
maBibliotheque.set(i, maBibliotheque.get(i + 1));
maBibliotheque.set(i + 1, livre);
tri = false;
}
}
} while (!tri);
System.out.println("decreasing: " + maBibliotheque);
}
static class Livre {
private final String newPeriode;
Livre(String newPeriode) {
this.newPeriode = newPeriode;
}
public String getNewPeriode() {
return newPeriode;
}
#Override
public String toString() {
return "Livre{" +
"newPeriode='" + newPeriode + '\'' +
'}';
}
}
prints
increasing: [Livre{newPeriode='000'}, Livre{newPeriode='aaa'}, Livre{newPeriode='abb'}, Livre{newPeriode='bbb'}]
decreasing: [Livre{newPeriode='bbb'}, Livre{newPeriode='abb'}, Livre{newPeriode='aaa'}, Livre{newPeriode='000'}]
Sort from oldest to newest, then reverse it with Collections.reverse(maBibliotheque);
I would recommend implementing a Comparator. You set a field in the Comparator object that can tell it whether to sort Ascending or Descending, then call Collections.sort(maBibliotheque, new MyComparator(MyComparator.DESC))
Demo (adjust generics as needed, and if, as in this case, you know that you're comparing with a specific field use o1.getField().compareTo(o2.getField()). Alternately, you could implement Comparable in your Object and just call Collections.sort(List), but that's not as flexible.
public class MyComparator implements Comparator<String>
{
public static final int ASC = 0;
public static final int DESC = 1;
private final int sortOrder;
public MyComparator(int sortOrder)
{
this.sortOrder = sortOrder;
}
/* (non-Javadoc)
* #see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
#Override
public int compare(String o1, String o2)
{
switch(this.sortOrder)
{
case ASC:
return o1.compareTo(o2);
case DESC:
return o2.compareTo(o1);
}
return 0;
}
}

Categories

Resources