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;
}
...
}
Related
I'm a beginner to java and I need help. I have two classes, one (Song) see code is a Child of the second one (Date). Song is serializeable while Date is not serializeable (and i intend to keep the Date class that way). I'm using method from Date called setDate, it take three parameters, month, day and year, all integers. I'm trying to use custom serialization (using readObject and writeObject methods and such).
package assignment7;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
*
* #author Owner
*/
public class Song extends Date implements Serializable{
private String title;
private String artist;
private String genre;
//private String dateOpened;
//private Date obj = new Date();
public Song(){
}
public void setTitle(String t) {
title = t;
}
public void setArtist(String a) {
artist = a;
}
public void setGenre(String g) {
genre = g;
}
public void setDateOpen(int m, int d, int y){
setDate(m, d, y);
}
public void setDayOpen(){
}
public void setDayOpen(){
Date
}
public void setDayOpen(){
}
public String getDateOpen(){
return getDate();
}
public String getTitle() {
return title;
}
public String getArtist() {
return artist;
}
public String getGenre() {
return genre;
}
private void writeObject( ObjectOutputStream out ) throws IOException, ClassNotFoundException, NotSerializableException {
out.defaultWriteObject();
out.writeObject(getTitle());
out.writeObject(getArtist());
out.writeObject(getGenre());
out.writeObject(getDateOpen());
}
private void readObject( ObjectInputStream in ) throws IOException, NotSerializableException, ClassNotFoundException {
in.defaultReadObject();
setTitle((String)in.readObject());
setArtist((String)in.readObject());
setGenre((String)in.readObject());
setDateOpen((int)in.readObject(), (int)in.readObject(), (int)in.readObject());
}
}
The problem is that the getDateOpen method returns a string, while setDateOpen requires 3 ints. is there a way to to have readObjects() read 3 ints and still output a serialized string? (iv'e also included the date class which my teach said not to change)
package assignment7;
import java.util.Scanner;
public class Date
{
private int month;
private int day;
private int year;
public Date() { month = 0; day = 0; year = 0; }
public Date( int m, int d, int y )
{
month = editMonth( m );
day = editDay( d );
year = editYear( y );
}
public void setDate( int m, int d, int y )
{
month = editMonth( m );
day = editDay( d );
year = editYear( y );
}
public String getDate( )
{
return month + "/" + day + "/" + year;
}
public int getMonth() { return month; }
public int getDay() { return day; }
public int getYear() { return year; }
protected int editMonth( int m )
{
if( m >= 1 && m <= 12 )
return m;
else
{
Scanner input = new Scanner( System.in );
while( !( m >= 1 && m <= 12 ) )
{
System.out.print( "Month must be 1-12 --- Please re-enter: " );
m = input.nextInt();
}
return m;
}
}
protected int editDay( int d )
{
int [] monthDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if( d >= 1 && d <= monthDays[month - 1] )
return d;
else
{
Scanner input = new Scanner( System.in );
while( !( d >= 1 && d <= monthDays[month - 1] ) )
{
System.out.print( "Day must be 1 - " + monthDays[month - 1] + " ---
please re-enter: " );
d = input.nextInt();
}
return d;
}
}
protected int editYear( int y )
{
if( y >= 1 )
return y;
else
{
Scanner input = new Scanner(System.in);
while( y < 1 )
{
System.out.print( "Year must be greater than 1 --- please re-enter: "
);
y = input.nextInt();
}
return y;
}
}
}
If the Date type only offers a String date, then you'll need to pass that at some point. Either parsing in the writeObject and storing ints, or keeping with the String is the serial form and parsing in readObject.
Date only offering a stringified date probably isn't a good design choice. Also there is no way a Song should be a subtype of Date (unless there's some critical performance issue, which seems unlikely).
Also avoid Java Serialization. JSON seems the usual alternative.
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 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
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);