Set / Get methods, tostring & ask method - Java - java

I am reletively new to java and have been set some tasks to complete, I (think) I have completed the first two tasks which request I:
Design a class Manual with the following properties:
serial number - string, - default:??????
title - string, - default: Untitled
author - string, - default: Unknown
Write a constructor and a method to print details of a Manual on the console.
.
Amend your Manual class by writing the following additional methods:
methods to set and get the properties of a Manual
a method to ask the user for details of a Manual
a toString() method.
Write a simple application to test your additional methods.
"
So far, I have this code:
public class Manual {
String serialNumber, title, author;
public static void main(String [] args){
Manual man= new Manual();
man.print();
}
public Manual(){
set("??????", "Untitled", "Unknown");
}
public Manual(String serialNumber, String title, String author)
{
set(serialNumber, title, author);
}
public void set(String serialNumber, String title, String author)
{
this. serialNumber = serialNumber;
this. title = title;
this.author = author;
}
public void print()
{
System.out.println("Serial Number : " +serialNumber);
System.out.println("Title : " +title);
System.out.println("Author : " +author);
}
public void print(String heading)
{
System.out.println(heading);
print();
}
public void ask()
{
serialNumber = Console.askString("Please enter the serial number: ");
title = Console.askString("Please enter the title: ");
author = Console.askString("Please enter the author: ");
set(serialNumber, title, author);
}
public String toString()
{
return serialNumber +" " +title +" " +author +" ";
}
}
Would anyone kindly be able to inform me if I have completed all areas of the first two questions correctly, and if there are any mistakes present in my code?
Thank you

The only major issue I see is that you have not implemented the Getters and Setters as was probably intended. In Java most classes have Getters/Setters for each variable that needs to be accessed, something like:
public String getTitle()
{
return title;
}
public void setTitle(String _title)
{
this.title = _title;
}
Also, there is nothing "wrong" with the way you have done the Print and toString functions, but I would have written up the toString to output more similar to how you have print doing it, and then calling toString from the print. Something like:
public String toString()
{
return "SerialNumber: " + serialNumber +"\n"
+"Title: " + title + "\n"
+"Author: " + author +"\n";
}
public void print()
{
System.out.println(this.toString());
}
As a final note, you did not include any code to use this class, as mentioned in the last line of question 2. Hope this helps

This is how I would implement the get() method for all three variables.
public String getSerialNumber(){
return serialNumber;
}
public String getTitle(){
return title;
}
public String getAuthor(){
return author;
}

Related

how can replace more then 16 if else-if statement Java

Im trying to make a program that allows the client to input a String. The string length should have 3 characters only and should contain the letters .
My program have to pass through this table and check what this string refers to..
Let's say the client passed this String "AUG", my program should show the name of this String which is "Met".
I made a code, and it worked but it has more then 15 if else-if condition.
My question is : Is there any other way to do it without using if else-if (or switch).
And does polymorphism work in this case ?
Have a look at HashMap
You can build your table with:
Map<String, String> table = new HashMap<>();
table.put("AUG", "Met");
table.put(...);
Then access your table using the user's input:
if(table.containsKey(input)){
return table.get(input);
}
I think I'd go about it with an enum personally (provided performance wasn't a significant concern):
public enum Abbreviations {
Ala("GCU", "GCC", "GCA", "GCG"),
Arg("CGU", "CGC", "CGA", "CGG", "AGA", "AGG")
// ...
;
private final List<String> codons;
private Abbreviations(final String... codons) {
this.codons = Arrays.asList(codons);
}
public boolean contains(final String codon) {
return this.codons.contains(codon);
}
}
And then you can find their matching from the String using something like:
public String find(final String codon) {
for (final Abbreviations abb : Abbreviations.values()) {
if (abb.contains(codon)) {
return abb.name();
}
}
throw new IllegalArgumentException("Unknown codon: '" + codon + "'");
}
You could try an Object Oriented Aproach:
//This is your representation of Codon
//Which has a name e.g. Alanine and an Abreviation object.
public class Codon {
private String name;
private Abreviation abreviation;
public Codon(String name, Abreviation abreviation) {
this.name = name;
this.abreviation = abreviation;
this.abreviation.addCodon(this);
}
#Override
public String toString() {
return "Codon [name=" + name + ", abreviation=" + abreviation + "]";
}
}
import java.util.ArrayList;
import java.util.List;
// This is a representation of an abreviation object
// Which has an abreviation: ALA;
// and the name of the abreviation "Alanine".
public class Abreviation {
private String abreviation;
private String name;
private List<Codon> codons = new ArrayList<>();
public Abreviation(String abreviation, String name) {
super();
this.abreviation = abreviation;
this.name = name;
}
public boolean addCodon(Codon codon) {
return this.codons.add(codon);
}
#Override
public String toString() {
return "Abreviation [abreviation=" + abreviation + ", name=" + name + "]";
}
}
// Here is your program, where it's being build all the Codons structure with your respective Abbreviation.
public class App {
public static void main(String[] args) {
// This is abreviation, it'll will associated with the codon
Abreviation alanine = new Abreviation("Ala", "Alanine");
// Here it's being build the codon CGU, which has abreviation alanine
Codon GCU = new Codon("GCU", alanine);
// Then using toString method it prints what have been done
System.out.println(GCU);
}
}
You can put all of your codons into a List, so you can search and retrieve then.

Why child class method is printing null ? What am i doing wrong?

Any tips why my code is taking null as output value instead of the parameter passed on. Kindly please guide me through the code.
Parent Class:
class Language{
protected String name;
protected int numSpeakers;
protected String regionsSpoken;
protected String wordOrder;
public Language(String getName, int getNumSpeakers, String getRegionsSpoken, String getWordOrder){
this.name = getName;
this.numSpeakers = getNumSpeakers;
this.regionsSpoken = getRegionsSpoken;
this.wordOrder = getWordOrder;
}
public void getInfo(){
System.out.println(name+ " is spoken by "+numSpeakers+" people mainly in "+regionsSpoken);
System.out.println("The language follows the word order: "+wordOrder);
}
public static void main(String[] args){
Mayan mayanLanguage = new Mayan("Ki'che'",30000);
mayanLanguage.getInfo();
}
}
Child Class:
class Mayan extends Language {
protected String name;
protected int numSpeakers;
Mayan(String languageName,int speakers ){
super(languageName,speakers,"Central America","verb-object-subject");
}
#Override
public void getInfo() {
System.out.println(name+" is spoken by "+numSpeakers+" people mainly in Central America.");
System.out.println("The language follows the word order: verb-object-subject");
System.out.println("Fun fact: "+name+" is an ergative language.");
}
}
I have looked into the code and tried to resolve it by making changes but nothing seems to work, i am getting stuck into what is the mistake that i am not seeing in the code.
Expected is:
Ki'che' is spoken by 2330000 people mainly in Central America.
The language follows the word order: verb-object-subject
Fun fact: Ki'che' is an ergative language.
Actual is:
null is spoken by 0 people mainly in Central America.
The language follows the word order: verb-object-subject
Fun fact: null is an ergative language.
In Mayan you have the fields
protected String name;
protected int numSpeakers;
Removing these will fix your issue. The reason this issue is happening is because when you define the two lines above, you are hiding the two fields from Language and you would have to access the fields from Language like super.name, super.numSpeakers, etc...
Something like the following is what you are probably after.
public class Mayan extends Language {
private static final String REGION = "Central America";
private static final String WORD_ORDER = "verb-object-subject";
public Mayan(String languageName, int speakers) {
super(languageName, speakers, REGION, WORD_ORDER);
}
#Override
public void getInfo() {
super.getInfo();
System.out.println("Fun fact: " + name + " is an ergative language.");
}
}
As Gavin pointed out, the access modifiers can be restricted. If you are working within a single package for your program, you might end up with something like
Language.java
class Language {
String name;
private int numSpeakers;
private String regionsSpoken;
private String wordOrder;
Language(String getName, int getNumSpeakers, String getRegionsSpoken, String getWordOrder) {
this.name = getName;
this.numSpeakers = getNumSpeakers;
this.regionsSpoken = getRegionsSpoken;
this.wordOrder = getWordOrder;
}
void getInfo() {
System.out.println(name + " is spoken by " + numSpeakers + " people mainly in " + regionsSpoken);
System.out.println("The language follows the word order: " + wordOrder);
}
public static void main(String[] args) {
Mayan mayanLanguage = new Mayan("Ki'che'",30000);
mayanLanguage.getInfo();
}
}
Mayan.java
class Mayan extends Language {
private static final String REGION = "Central America";
private static final String WORD_ORDER = "verb-object-subject";
Mayan(String languageName, int speakers) {
super(languageName, speakers, REGION, WORD_ORDER);
}
#Override
void getInfo() {
super.getInfo();
System.out.println("Fun fact: " + name + " is an ergative language.");
}
}

printing a specific variable of an object

This is probably a bad question, but i have constructed a DVD object in java:
DVD myDVD = new DVD (11.17 , 9 , 120 , " Howl ’s Moving Castle " , " Hayao Miyazaki " );
I have a toString to print the whole object, but I've been asked to print the director (Hayao Miyazaki) of the object without the rest, is there a way to do this?
If you need any more information in order to help, please comment. Thanks
create a get method for the director
public String getDirector(){
return director;
}
System.out.print(myDVD.getDirector());
Assuming your code is Java code, in your DVD class, you can override the toString method in order to print what you want:
public class DVD {
private String director;
//more fields and stuff
#Override
public String toString() {
return director;
}
}
If you already have a toString implementation and need another one, you can add another method to get the director:
public String getDirector(){
return director;
}
and print it:
System.out.print(myDVD.getDirector());
Or you may want a method to do the printing itself:
public void printDirector() {
System.out.println(director);
}
You could make it as simple as writing a new method printDirector() which would do just that, OR...
You could leave the responsibility of printing the information to some other class, and make the DVD object responsible only for providing its information:
public class Movies {
public class DVD {
private director;
public DVD(String director) {
this.director = director;
}
public String getDirector() {
return director;
}
}
public static void main(String... arg) {
DVD howl = new DVD("Miyazaki");
String director = howl.getDirector();
SomePrinterClass.print(director);
}
}
Ultimately that's a design decision, either will produce the same result.

ResultSet- What kind of object is it?

I'm iterating over a ResultSet and save it to a ArrayList.
weatherData = Arrays.asList (
new WeatherInfo(rs.getDate(1), rs.getInt(2)...
When I do a System.out.println(weatherData); I see this in the Eclipse Console:
[com.example.project.view.ChartsData$WeatherInfo#66ee6cea, com.example.project.view.ChartsData$WeatherInfo#757d0531.....
What does it mean? Is it a value I can handle in Java or not?
Is this the actual date and int that I can use in Java?
thanks
You need to override toString() method in WeatherInfo class. What you see is its default implementation that presents its memory location.
This is a typical model object in Java with a toString() method. I used Intellij Idea (recommended!) which has the ability to auto-generate toString() and other methods such as equals() and hashCode(). We find that having these methods on all model objects is very useful for debugging and testing.
Running main() will output:
weatherInfo = WeatherInfo{country='CA', probablyOfPrecipitation=20}
public class WeatherInfo {
public static void main(String [] args) {
WeatherInfo weatherInfo = new WeatherInfo();
weatherInfo.setCountry("CA");
weatherInfo.setProbablyOfPrecipitation(20);
System.out.println("weatherInfo = " + weatherInfo);
}
String country;
int probablyOfPrecipitation;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getProbablyOfPrecipitation() {
return probablyOfPrecipitation;
}
public void setProbablyOfPrecipitation(int probablyOfPrecipitation) {
this.probablyOfPrecipitation = probablyOfPrecipitation;
}
#Override
public String toString() {
return "WeatherInfo{" +
"country='" + country + '\'' +
", probablyOfPrecipitation=" + probablyOfPrecipitation +
'}';
}
}
Top Tip!
We use a library called EqualsVerifier to guarantee that all equals() and hashCode() implementations are correct.

Method to check a Object's variables within an ArrayList

I'm having issues creating the following two methods using an ArrayList object:
existTextbook(): checks whether a given textbook is in the catalogue. existTextbook() accepts the title and the author and returns true or false. True if the textbook is in the catalogue, false otherwise.
deleteTexbook(): deletes a textbook from the catalogue. deleteTextbook() accepts a textbook title as parameter and deletes the textbook if it exists.
Searching the Java API, the closest method I can find for the first method is the contains method but it takes an object as a parameter, not a String object within the Textbook object like the title or author. The same is true for the remove method for the second method taking an object of the ArrayList as a parameter.
Any hints on how to have a method look at each Textbook object String title or author, then return true if a match is found, or to delete the Textbook object containing the Textbook object String title or author?
Here's my code so far:
Textbook Class
package Ex1;
import java.text.NumberFormat;
public class Textbook
{
private String category, title, author;
private int year;
private double price;
public Textbook (String category, String title, String author, int year,
double price)
{
this.category = category;
this.title = title;
this.author = author;
this.year = year;
this.price = price;
}
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String description;
description = "Category: " + category + "\n";
description += "Title: " + title + "\n";
description += "Author: " + author + "\n";
description += "Year: " + year + "\n";
description += "Price: " + fmt.format(price) + "\n" + "\n";
return description;
}
}
Catalogue Class
package Ex1;
import java.util.ArrayList;
public class Catalogue
{
private ArrayList <Textbook> catalogue;
public Catalogue ()
{
catalogue = new ArrayList<Textbook>();
}
public void addTextbook (Textbook t)
{
catalogue.add(t);
}
public boolean existTextbook(String title, String author)
{
}
public void deleteTextbook(String title)
{
}
public String toString()
{
return catalogue.toString();
}
}
Driver Class
package Ex1;
public class Drivermain
{
public static void main(String[] args)
{
Textbook javaBook = new Textbook ("Computer Science",
"Java Software Solutions", "Lewis/Loftus", 2015, 163.45);
Textbook dataBook = new Textbook ("Computer Science",
"Data Structures and Algorithm Analysis in Java,",
"Mark A. Weiss", 2015, 181.90);
Textbook calcBook = new Textbook ("Mathematics",
"Calculus Plus NEW MyMathLab", "Briggs/Cochran/Gillett",
2015, 236.90);
Textbook osBook = new Textbook ("Computer Science",
"Operating Systems: Internals and Design Principles",
"William Stallings", 2015, 205.70);
Textbook historyBook = new Textbook ("History",
"History of the Canadian Peoples: Beginnings to 1867, Vol. 1",
"Conard/Finkel/Fyson", 2015, 96.90);
Catalogue bookCatalogue = new Catalogue();
bookCatalogue.addTextbook(javaBook);
bookCatalogue.addTextbook(dataBook);
bookCatalogue.addTextbook(calcBook);
bookCatalogue.addTextbook(osBook);
bookCatalogue.addTextbook(historyBook);
System.out.println(bookCatalogue);
bookCatalogue.existTextbook("Java Software Solutions", "Lewis/Loftus");
bookCatalogue.deleteTextbook("Java Software Solutions");
}
}
I think instead of using methods from collections, you may want to deal with looking in your Arraylist yourself.
I'm not using a for each loop (just a for loop) because for delete it will cause a concurrent modification exception.
package Ex1;
import java.util.ArrayList;
public class Catalogue
{
private ArrayList <Textbook> catalogue;
public Catalogue ()
{
catalogue = new ArrayList<Textbook>();
}
public void addTextbook (Textbook t)
{
catalogue.add(t);
}
public boolean existTextbook(String title, String author)
{
for(int i =0; i<catalogue.Size(); i++){
Textbook t = catalogue.get(i);
//you'll want getter and setter methods
if(t.author.equals(author)&&t.title.equals(title))
return truel
}
}
public void deleteTextbook(String title)
{
for(int i =0; i<catalogue.Size(); i++){
Textbook t = catalogue.get(i);
if(t.title.equals(title)){
catalogue.remove(i);
}
}
}
public String toString()
{
return catalogue.toString();
}
}
Happy Coding! Leave a comment if you have any questions.
Instead of directly using those methods you may consider just looping through the catalogue ArrayList yourself and testing if the current object matches the title (and author).
It might be overkill, but you could make Textbook implement Comparable or write a Comparator.

Categories