How to serialize an object which it's method has multiple parameters - java

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.

Related

How can I subtract two dates - one already declared, one the current date

I am trying to create an array that displays employees and their hire date, data that's already declared. I need to have a set instance variable of today's date as the retiring date and use that to find the amount of years, months and days they have worked. I have the project broken up into two files that work together. I'm just having trouble trying to get the years, months, and days they've worked.
My code is for the first file:
import java.time.*;
import java.time.LocalDate.*;
import java.time.Month.*;
import java.time.Period.*;
class Employee
{
//Instance variables
private String name;
private double salary;
private LocalDate hireDay;
private LocalDate retDay = LocalDate.now();
private int years;
private int months;
private int days;
//Constructor - same name as class -- first thing that runs
public Employee(String n, double s, int year, int month, int day)//, int ys, int
ms, int ds)
{
name = n;
salary = s;
hireDay = LocalDate.of(year, month, day);
///years = ys;
// months = ms;
//days = ds;
}
//methods are public -- any class can have access to the method
//may or may not have a parameter
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public LocalDate getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent/100;
salary += raise;
}
public int getRetYears()
{
return years;
}
public int getRetMonths()
{
return months;
}
public int getRetDays()
{
return days;
}
public void calcRetDay(Period timeWorked, int y, int m, int d)
{
timeWorked = Period.between(hireDay, retDay);
y = timeWorked.getYears();
m = timeWorked.getMonths();
d = timeWorked.getDays();
years = y;
months = m;
days = d;
}
}
My code for my second file is:
import java.time.*;
import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
//*****Communicates with employee.java****************************
public class EmployeeDriver
{
public static void main(String[] args)
{
Employee[] staff = new Employee[3];
//populate the staff array with three employee objects
staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);
//raise everyone's salary by 5%
for (Employee e : staff)
//below is dot notation --- encapsulation
e.raiseSalary(5);
//print out information about all Employee objects
for (Employee e : staff)
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" + e.getHireDay() + ",years=" + e.getRetYears()+ ",months=" + e.getRetMonths()+ ",days=" + e.getRetDays());
}
}

Trying to retrieve index from Array using loop

I made a program which stores movie names, hour and time of showing.
I saved the details inputted to arrays and then saved the arrays by getter and setter methods as a record.
In my final method i attempt to use a for loop to print out the details stored in the records but constantly get errors.
Any help to where the issue is would be greatly appreciated.
//Demonstrates usage of loops/adt/gettersetters
import java.util.Scanner;
class movies {
public static void main(String[] p) {
Movie m = new Movie();
int[] screenn = new int[4];
int[] namee = new int[4];
int[] hourr = new int[4];
int[] minn = new int[4];
for (int i = 0; i < 4; i++) {
screenn[i] = i + 1;
String moviename = input("Film for screen " + (i + 1));
namee[i] = moviename;
int moviehour = inputint("what hour does it start?");
hourr[i] = moviehour;
int moviemin = inputint("what min does it start?");
minn[i] = moviemin;
}
sethour(m, namee);
setmin(m, minn);
setscreen(m, screen);
setname(m, namee);
showtime(m);
System.exit(0);
}
//Getter Method
public static String[] getname(Movie m) {
return m.name;
}
public static int[] getscreen(Movie m) {
return m.screen;
}
public static int[] gethour(Movie m) {
return m.hour;
}
public static int[] getmin(Movie m) {
return m.min;
}
//Setter Method
public static Movie sethour(Movie m, int[] hour) {
m.hour = hour;
return m;
}
public static Movie setmin(Movie m, int[] min) {
m.min = min;
return m;
}
public static Movie setname(Movie m, String[] name) {
m.name = name;
return m;
}
public static Movie setscreen(Movie m, int[] screen) {
m.screen = screen;
return m;
}
public static String input(String message) {
Scanner scanner = new Scanner(System.in);
print(message);
String answer = scanner.nextLine();
return answer;
}
public static String print(String message) {
System.out.println(message);
return message;
}
public static int inputint(String message) {
int number = Integer.parseInt(input(message));
return number;
}
public static void showtime(movie m) {
print("Cineworld Movies For Tonight");
for (int i = 0; i < 4; i++) {
print("");
print(m.screen[i]);
print(m.movie[i]);
print(m.hour[i]);
print(m.min[i]);
}
}
}
class Movie {
String[] name = new String[4];
int[] hour = new int[4];
int[] min = new int[4];
int[] screen = new int[4];
}
You are getting your assignment wrong. According to OOP The Movie class should store Movie's properties (name, hour, mins, etc) and then on your MainProgram you should store an array of movies. How you create and the usage of these objects is not concern of the class it self. Having said that i re-implemented your mainProgram to:
Ask for each (4) movie attributes.
Create the movie.
add it to a list of movies.
for each movie (4) print its properties.
MovieClass:
public class Movie
{
String name;
int hour , min , screen;
public Movie ( )
{
super ( );
}
public Movie ( String name , int hour , int min , int screen )
{
super ( );
this.name = name;
this.hour = hour;
this.min = min;
this.screen = screen;
}
public String getName ( )
{
return name;
}
public void setName ( String name )
{
this.name = name;
}
public int getHour ( )
{
return hour;
}
public void setHour ( int hour )
{
this.hour = hour;
}
public int getMin ( )
{
return min;
}
public void setMin ( int min )
{
this.min = min;
}
public int getScreen ( )
{
return screen;
}
public void setScreen ( int screen )
{
this.screen = screen;
}
#Override
public String toString ( )
{
return "Movie [name=" + name + ", hour=" + hour + ", min=" + min + ", screen=" + screen
+ "]";
}
}
MainProgram:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MainProgram
{
public static void main ( String [ ] args )
{
List < Movie > movieList = new ArrayList < Movie > ( );
for(int i = 1; i <= 4; i++ )
{
int screen = i;
String name = inputString ( "Film for screen "+(i));
int hour = inputInt ("what hour does it start?");
int min = inputInt ("what min does it start?");
Movie movie = new Movie ( name , hour , min , screen );
movieList.add ( movie );
}
print("Cineworld Movies For Tonight");
for( Movie movie : movieList)
{
print ( "" );
print ( Integer.toString ( movie.getScreen ( ) ));
print (movie.getName ( ));
print (Integer.toString ( movie.getHour ( ) ));
print ( Integer.toString ( movie.getMin ( ) ));
}
}
public static String inputString ( String message )
{
Scanner scanner = new Scanner ( System.in );
print ( message );
String answer = scanner.nextLine ( );
return answer;
}
public static String print ( String message )
{
System.out.println ( message );
return message;
}
public static int inputInt ( String message )
{
int number = Integer.parseInt ( inputString ( message ) );
return number;
}
}
Note: as you can see i re-used some of your static methods but if you need something else you have to implement it by yourself.
I/O Example:
Film for screen 1
The Shawshank Redemption
what hour does it start?
19
what min does it start?
30
Film for screen 2
The Godfather
what hour does it start?
20
what min does it start?
15
Film for screen 3
The Godfather: Part II
what hour does it start?
20
what min does it start?
30
Film for screen 4
The Dark Knight
what hour does it start?
21
what min does it start?
15
Cineworld Movies For Tonight
1
The Shawshank Redemption
19
30
2
The Godfather
20
15
3
The Godfather: Part II
20
30
4
The Dark Knight
21
15
Hope it helps.

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;
}
...
}

Unidentified runtime error--Could not launch/Console

I am experiencing a strange error after I compile and run my program. I believe that these are called run time errors? Is that correct? The program compiles perfectly, all of the classes included. When I open the compiled program, I am prompted (correctly) to enter all information and after that when the program is supposed to print out the final output I receive a pop up error message ( with a yellow exclamation point on the java coffee cup) that says " The Java Class file 'Employee10.java' could not be launched. Check console for possible error messages. " Does anyone know why I am getting this message if the rest of the program runs correctly? Is my print statement not correct? Below I have added all the classes just incase the error isn't necessarily in Employee10.java. If anyone can help at all with this I would be very grateful. I am new to Java programing and could really use the help and guidance. Thank you very much all.
Here is Employee10
public class Employee10
{
public static void main ( String[] args )
{
System.out.println("Begin Program");
Employee e1 = new Employee();
Employee[] arr = new Employee[2];
int j = 0;
for ( int i=0; i < 3; i++)
{
arr[0] = e1;
String nameF = Input.getString("Please enter a First Name");
String nameL = Input.getString("Please enter a Last Name");
int Number = Input.getInt("Please enter an Employee Number");
String Street = Input.getString("Please enter a Street address");
String City = Input.getString("Please enter a City");
String State = Input.getString("Please enter a State");
double Zip = Input.getDouble("Please enter a Zip Code");
int Month = Input.getInt("Please enter a Month in numbers");
int Day = Input.getInt("Please enter a Day");
int Year = Input.getInt("Please enter a Year");
e1.setNumber(Number);
e1.setName( new Name(nameF, nameL));
e1.setAddress(new Address(Street, City, State, Zip));
e1.setHireDate(new Date(Month, Day, Year));
System.out.println(e1.getEmployeeString());
arr[i] = e1;
}
for ( j=0; j < arr.length; j++ )
{
System.out.println( arr[j].getEmployeeString() );
}
}
}
Here is Employee
public class Employee
{
private int Number;
Name name;
Address address;
Date HireDate;
public void setNumber ( int N )
{
Number = N;
}
public void setName ( Name n )
{
name = n;
}
public void setAddress ( Address a )
{
address = a;
}
public void setHireDate ( Date h )
{
HireDate = h;
}
public String getEmployeeString()
{
return name.getNameString() + Number + address + HireDate;
}
}
Here is Date
public class Date
{
private int month;
private int day;
private int year;
public Date() { month = 0; day = 0; year = 0; }
public void setDate( int m, int d, int y )
{
month = m; day = d; year = y;
}
public String getDateString()
{
return month + "/" + day + "/" + year;
}
public Date( int m, int d, int y )
{
month = m;
day = d;
year = y;
}
}
Here is Name
public class Name
{
private String NameF;
private String NameL;
public void setNameF ( String F )
{
NameF = F;
}
public void setNameL ( String L )
{
NameL = L;
}
public String getNameString ()
{
return NameF + NameL;
}
public Name ( String F, String L )
{
NameF = F;
NameL = L;
}
public Name ()
{
NameF = "John";
NameL = "Doe";
}
}
Here is Address
public class Address
{
private String Street;
private String City;
private String State;
private double Zip;
public void setStreet ( String s )
{
Street = s;
}
public void setCity ( String c )
{
City = c;
}
public void setState ( String T )
{
State = T;
}
public void setZip ( double z )
{
Zip = z;
}
public String GetAddressString ()
{
return Street + City + State + Zip;
}
public Address ( String s, String c, String T, double z )
{
Street = s;
City = c;
State = T;
Zip = z;
}
public Address ()
{
Street = "No street";
City = " No City";
State = "No state";
Zip = 00000;
}
}
Here is Input
import javax.swing.*;
public class Input
{
public static byte getByte( String s )
{
String input = JOptionPane.showInputDialog( s );
return Byte.parseByte( input );
}
public static short getShort( String s )
{
String input = JOptionPane.showInputDialog( s );
return Short.parseShort( input );
}
public static int getInt( String s )
{
String input = JOptionPane.showInputDialog( s );
return Integer.parseInt( input );
}
public static long getLong( String s )
{
String input = JOptionPane.showInputDialog( s );
return Long.parseLong( input );
}
public static float getFloat( String s )
{
String input = JOptionPane.showInputDialog( s );
return Float.parseFloat( input );
}
public static double getDouble( String s )
{
String input = JOptionPane.showInputDialog( s );
return Double.parseDouble( input );
}
public static boolean getBoolean( String s )
{
String input = JOptionPane.showInputDialog( s );
return Boolean.parseBoolean( input );
}
public static char getChar( String s )
{
String input = JOptionPane.showInputDialog( s );
return input.charAt(0);
}
public static String getString( String s )
{
String input = JOptionPane.showInputDialog( s );
return input;
}
}
In Employee class file can you replace
public String getEmployeeString()
{
return name.getNameString() + Number + address + HireDate;
}
with
public String getEmployeeString()
{
return name.getNameString() + Number + address.GetAddressString() + HireDate.getDateString();
}

Method for finding desired conditions

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

Categories

Resources