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);
Related
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;
}
...
}
public class hw16 {
public static void main(String[] args) {
MonthlyRecord MonthRecord = new MonthlyRecord("January", 31);
MonthRecord.Transaction(5, 600);
}
}
public class MonthlyRecord {
private String month;
private int day;
private double[] moneyDaily = new double[day];
public MonthlyRecord() {
this.month = "January";
this.day = 0;
this.moneyDaily[1] = 0;
}
public MonthlyRecord(String name, int day) {
System.out.println("Hello");
this.setMonthlyRecord(name);
this.setDays(day);
}
public void setDays(int temp) {
this.day = temp;
}
public void setMonthlyRecord(String temp) {
this.month = temp;
}
public int setDays() {
return this.day;
}
public String getMonthlyRecord() {
return this.month;
}
public void Transaction(int daynum, int amount) {
System.out.println("You've made $" + amount + " on the " + daynum + "th day");
System.out.println(moneyDaily[daynum]);
}
}
I'm getting an error:
Hello You've made $600 on the 5th day Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 5 at
hwk16jzuramski1.MonthlyRecord.Transaction(MonthlyRecord.java:40) at
hwk16jzuramski1.Hwk16jzuramski1.main(Hwk16jzuramski1.java:11) Java
Result: 1
SO it say's my array is out of bounds which I don't understand? If I'm setting day to the length of my array why is it saying its out of bounds at int 5 when the array length should be 31?
What I think is happening is that at the top of your class your are instantiating the array monthDaily[] outside of the constructor. Since the int variable day only gets initialized in the constructors you should also instantiate the monthDaily[] variable in the constructor. Hence the beginning part of your code would look like:
public class MonthlyRecord {
private String month;
private int day;
private double[] moneyDaily;
public MonthlyRecord() {
this.month = "January";
this.day = 0;
this.moneyDaily = new double[1]; //variable is instantiated to have one slot as default
}
public MonthlyRecord(String name, int day) {
System.out.println("Hello");
this.setMonthlyRecord(name);
this.setDays(day);
moneyDaily = new double[days]; //array gets instantiated with number of slots equal to the value of the day variable
}
You need to set the size of the array upon calling the constructor:
public MonthlyRecord(String name, int day) {
moneyDaily = new double[day];
System.out.println("Hello");
this.setMonthlyRecord(name);
this.setDays(day);
}
Otherwise, your array moneyDaily will have the size of what day was originally, which is 0.
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.
I have the next code, and this code has to validate a date, but there are some requirements that i have to follow:
First of all i have to create a class named MyDate, this class contains three attributes: day, month and year. I have to initialize these attributes with a constructor without parameters.
Then I have to define three methods: setDay(),setMonth() and setYear(), inside this methods i have to validate if a date is correct. In the main method() i have to invoke the set methods, but the problem is that i don´t know how to initialize the attributes with the constructor, while at the same time i am already initializing them in the main when i call the set methods
class MyDate{
final int JANUARY = 1;
final int FEBRUARY = 2;
final int MARCH = 3;
final int APRIL = 4;
final int MAY = 5;
final int JUNE = 6;
final int JULY = 7;
final int AUGUST = 8;
final int SEPTEMBER = 9;
final int OCTOBER = 10;
final int NOVEMBER = 11;
final int DECEMBER = 12;
private int day;
private int month;
private int year;
public MyDate(){
//here is the problem;
}
public int getDay()
{
return day;
}
public int getMonth()
{
return month;
}
public int getYear()
{
return year;
}
public boolean setDay(int day)
{
//is not finished
}
public boolean setMonth(int month)
{
//is not finished
}
public boolean setYear(int year)
{
//is not finished
}
}
public class E{
public static void main(String[] args){
MyDate date = new MyDate();
date.setDay(31);
date.setMonth(11);
date.setYear(2014);
System.out.println("DAY: "+date.getDay());
System.out.println("MONTH: "+date.getMonth());
System.out.println("YEAR: "+date.getYear());
}
}
I'm not sure if I totally understood what you want, particularity the part where you want to set the variables in a constructor without parameters. How about the following solution? You can create a default Constructor as well and call this(1, 1, 2015).
class MyDate {
public MyDate() {
this(1, 1, 2015);
}
public MyDate(int day, int month, int year){
setDay(day);
setMonth(month);
setYear(year);
}
public void setDay(int day) {
if (isValid(day, month, year))
this.day = day;
else
throw new RuntimeException("Day is not valid.");
}
private boolean isValid(int day, int month, int year) {
// Your validation logic should go here.
}
Similar to setDay you can define setMonth and setYear for setting day and month. Your validation logic should go into isValid.
Your design is poor from 2 points:
First problem:
Having separate setters allows the state (fields) to be invalid until all setters are called. This is bad. Also bad is if you change from 31 Mar to 28 Feb (both valid), but happen to change the month first, the date is temporarily invalid (31 Feb). Also bad.
The 3 fields should be set atomically (in one action) using one method that sets all 3.
Second problem:
You have setters! Make your class immutable (no setters, final fields). If you need to "change" a date, make a new one. String works like this - it will work for you too.
class MyDate{
final int JANUARY = 1;
final int FEBRUARY = 2;
final int MARCH = 3;
final int APRIL = 4;
final int MAY = 5;
final int JUNE = 6;
final int JULY = 7;
final int AUGUST = 8;
final int SEPTEMBER = 9;
final int OCTOBER = 10;
final int NOVEMBER = 11;
final int DECEMBER = 12;
private final int day;
private final int month;
private final int year;
public MyDate(int d, int m, int y) {
day = d;
month = m;
year = y;
}
public int getDay() {
return day;
}
public int getMonth() {
return month;
}
public int getYear() {
return year;
}
public boolean isValid() {
// put your impl here
}
}
public class E {
public static void main(String[] args){
MyDate date = new MyDate(31, 11, 2014);
System.out.println("DAY: " + date.getDay());
System.out.println("MONTH: " + date.getMonth());
System.out.println("YEAR: " + date.getYear());
}
}
If you want, you could add a line to the constructor to allow only valid dates:
if (!isValid())
throw new IllegalArgumentException();
I have to initialize these attributes with a constructor without parameters.
Unless you are required to provide an explicit starting value for these parameters, you're pretty much done with that step already. Java will set an initial value for your fields, so each of those ints are set to 0 by the time you type new MyDate().
If you are required to start at specific values, then put them directly into the body of the no-arg constructor.
public MyDate() {
this.year = 2015;
this.month = 1;
this.day = 7;
}
I don't know how to initialize the attributes with the constructor, while at the same time I am already initializing them in main when I call the set methods
This is how POJOs work, in a sense. You create some class that does have a decent number of fields, but you only set the ones you care about.
Because you can rely on the initial value guarantee provided by the Java Language Specification, you don't have to worry about initializing those values unless you require them to be an explicit initial value besides zero.
Here is an Example on initializing Variable using Constructor:
Checked if it is FEBRUARY and Change Day Limit to 28, If False define max day to 30~31
class MyDate{
private int day;
private int month;
private int year;
public MyDate(){
this(1,1,2014);
}
public MyDate(int day, int month, int year){
this.day = day;
this.month = month;
this.year = year;
}
public int getDay()
{
return day;
}
public int getMonth()
{
return month;
}
public int getYear()
{
return year;
}
public boolean setDay(int day)
{
if(month == 2){
if(day>0 && day <=28){
this.day = day;
return true;
}else{
return false;
}
}else{
if( month % 2 != 0){
if(day>0 && day <=31){
this.day = day;
return true;
}else{
return false;
}
}else{
if(day>0 && day <=30){
this.day = day;
return true;
}else{
return false;
}
}
}
}
public boolean setMonth(int month)
{
if(month>0 && month <=12){
this.month = month;
return true;
}else{
return false;
}
}
public boolean setYear(int year)
{
// Not Required
if(year>1993 && year <=2018){
this.year = year;
return true;
}else{
return false;
}
}
}
public class E{
public static void main(String[] args){
MyDate date = new MyDate();
date.setDay(31);
date.setMonth(11);
date.setYear(2014);
System.out.println("DAY: "+date.getDay());
System.out.println("MONTH: "+date.getMonth());
System.out.println("YEAR: "+date.getYear());
}
}
If you can't pass any parameters to the constructor then all you can really do is initialize the object's variables to zero. The object won't contain a valid date, however, until you call your set methods which contains the validation code. The main reason for doing this is to avoid "variable might not have initialized" errors.
public MyDate(){
year = 0;
month = 0;
day = 0;
}
Just make sure that the validation code for setDay checks that the month and year don't equal zero still, otherwise it will be impossible to determine if the day value is valid.
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