Writing a java program containing two classes - java

I've attempted to write a Java program containing two classes: Dog and a driver class Kennel.
A dog consists of the following information:
An integer age.
A string name. If the given name contains non-alphabetic characters, initialize to Wolfy.
A string bark representing the vocalization the dog makes when they ‘speak’.
A boolean representing hair length; true indicates short hair.
A float weight representing the dog’s weight (in pounds).
An enumeration representing the type of tail (LONG, SHORT, NONE).
A dog has the following methods:
A default constructor.
A constructor that takes a name as argument.
A method private boolean validName(String) that returns true / false whether the given name contains non-alphabetic characters.
humanAge that computes and returns the age of the dog in “human years.”
speak that returns the dog’s bark...
I am having trouble trying to figure out how to do the method for validName. Can anyone point me in the right direction? Also do I do the method for speak the same way or no? The code is attached below.
package lab101;
public class Dog
{
public enum TailType
{
LONG, SHORT, NONE
}
private int age;
private float weight;
private String name;
private String bark;
private boolean hairLength;
private TailType tail;
//Default Constructor--> initializes an object (called once)every constructor
//must initialize all the classes attributes!!
public Dog()
{
age = 0;
weight = 0;
name = "";
bark = "";
hairLength = false;
tail = TailType.NONE;
}
//Overloaded constructor (must have an argument)
public Dog(String theName)
{
age = 0;
weight = 0;
name = theName;
bark = "";
hairLength = false;
tail = TailType.NONE;
}
//If the name contains non-alphabetic characters
private boolean validName(String str)
{
str = str.toLowerCase();
if (str.length() <= 0)
{
}
return false;
}
//Computes the dog's age in human years.
public int humanAge()
{
int theAge = 7 * age;
return theAge;
}
//Returns the value of bark if true
public String(speak)
{
return bark;
}
//Method: <privacy: (private, public)> <return-type (data type or void)> <methodName>(<argument>){
// <body>
// return
// }
public String toString()
{
String str = "";
str += "Name: " + name;
str += "Weight: " + weight;
str += "Bark: " + bark;
str += "Hair Length: " + hairLength;
str += "Tail: " + tail;
str += "Age: " + age;
return str;
}
}

I am having trouble trying to figure out how to do the method for validName.
Assuming your validName method checks whether a valid name was given by checking whether there exist only alphabets:
//Return true if name is valid
private boolean validName(String str)
{
if(str == null || str.length() == 0)
return false;
return str.toLowerCase().matches("[a-z]+"); //Name only has a-z(A-Z)
}
Also do I do the method for speak the same way or no?
Well, I do not know what do you mean by "the same way". But your speak method is incorrect.
According to your description, it should be:
public String speak(){
return bark;
}
Something you did not ask, but could be done better:
You are implementing your class constructor twice. You could have invoke the constructor like this:
public Dog(){
this(""); //invoke Dog(String)
}
public Dog(String theName){
age = 0;
weight = 0;
name = theName;
bark = "";
hairLength = false;
tail = TailType.NONE;
}
The effect of the above is the same as what you did, but this is preferred.

you can also do this if you don't know regular expression:
private boolean validName(String str)
{ char[] letters = str.toUpperCase().toCharArray();
for(int i = 0 ; i < letters.length; i++){
int oneLetter = (int) letters[i];
if( !(oneLetter > 64 && oneLetter < 91)) // letters as ASCII for A-Z
return false; // if anyone is not A-Z then return false
}
return true; // if every letter is valid then return true
}

Related

How to search specific word position in array of Strings

A few questions. I'm creating a method that searches through an array of element objects (where each element object has been initialized with [atomicNumber abbreviation name atomicWeight]). I also need to return 'a reference to the element'-- not exactly sure how to do this. The user inputs an abbreviation in main, then the findAbbreviation method is used on an array. The toString method formats and returns each datatype as a String. How might I search for the abbreviation position in any given object for the entire array. And how do I return a reference to that 'element' object.
public class PeriodicTable {
private final int MAX_ELEMENTS = 200;
private PeriodicElement[] table;
private int actualSize;
public PeriodicTable() throws IOException{
table = new PeriodicElement[MAX_ELEMENTS];
Scanner input = new Scanner(new File("file name here"));
int index = 0;
while(input.hasNext() && index < MAX_ELEMENTS) {
int aN = input.nextInt();
String abbr = input.next();
String name = input.next();
double aW = input.nextDouble();
table[index] = new PeriodicElement(aN, abbr, name, aW);
index++;
}
input.close();
actualSize = index;
}
public String findAbbreviation(String abbreviationP){
boolean found = false;
int index = 0;
while(found && index < MAX_ELEMENTS){
if (table[index] = table[abbreviationP]){
found = true;
return table[index].toString;
}
index++;
}
return null;
}
}
class PeriodicElement {
private int atomicNumber;
private String abbreviation, name;
private double atomicWeight;
public PeriodicElement(int atomicNumberP,
String abbreviationP, String nameP,
double atomicWeightP){
atomicNumber = atomicNumberP;
abbreviation = abbreviationP;
name = nameP;
atomicWeight = atomicWeightP;
}
First, you would need an array or collection of Elements. This could be an instance variable of the class you are currently writing which includes 'findAbbreviation'.
Second, an "Element" could simply have an attribute variable like "abbreviation" as an instance variable of the Element class, and you may just be able to call the findAbbreviation on the list and search for that abbreviation specifically in the abbreviation instance variable. It is unlikely that you could search on the actual name to find the abbreviation, because, for example: Gold's "abbreviation" is AU.
Could you show how your list of elements is defined as well as the class that defines the Elements?
If you are simply looking through a list of abbreviations of elements (as your current code suggests), you may just have to fix your current code to do an equals comparison correctly:
public String findAbbreviation(String abbreviationP){
boolean found = false;
int index = 0;
while(!found && index < MAX_ELEMENTS){ //this should be !found instead of found
if (table[index].equals(abbreviationP)) { // you previously had an assignment statement in this if
found = true;
return table[index].toString;
}
index++;
}
return null;
}
Updating answer to reflect update to the question:
First, you will need to provide a method in the PeriodicElement class to get the instance variable "abbreviation".
This is a standard "getter":
public String getAbbreviation() {
return abbreviation;
}
Second, you'll want to update your findAbbreviation method to utilize this new getter:
public PeriodicElement findAbbreviation(String abbreviationP){
boolean found = false;
int index = 0;
while(!found && index < MAX_ELEMENTS){ //this should be !found instead of found
if (table[index].getAbbreviation().equals(abbreviationP)) { // you previously had an assignment statement in this if
found = true;
return table[index]; //This will return the object at the index where it was found.
// Notice I also changed the return type on your function.
}
index++;
}
return null;
}

Development of monopoly game

I seem to have a problem with a subtask. It's in danish so I put in the translated version of it:
Create a class Field, that is representing the fields of a monopoly game. Initially, Field can contain these encapsulated variables:
String name - short name of the field
int number - a number in the range[1..40]
Both variables must be initialized in a constructor, and there must only be getters, as they never will be changed after creation.
Moreover, there should be a method with the signature public String toString(), so it's easy to print what Field a player has landed on.
At first it's allowed to just call the fields Field1, Field2...
My Field class look like this:
public class Field {
String name;
int number;
public Field(String name, int number) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
}
In my main method I wanted to test this. So I wrote the following:
Field[] board = new Field[40]; // a board containing 40 fields
for (int i = 0; i < board.length; i++) {
board[i] = new Field("Field" + (i + 1), i + 1);
}
System.out.println("Board: " + Arrays.toString(board));
In my console I get this:
Board: [test.Field#2a139a55, test.Field#15db9742, test.Field#6d06d69c,......]
And I want this:
Board: [Field1, Field2, Field3,......]
Override Field's toString() to return the name, i.e.
public String toString() {
return name;
}
What you get (e.g. test.Field#2a139a55) is the default implementation of toString() which can be found in Object:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
You missed the
Moreover, there should be a method with the signatur public String toString(),
part of your task.
Are you able to use java8? Then I would suggest this:
Field[] board = new Field[40]; // a board containing 40 fields
for(int i = 0; i < board.length; i++){
board[i] = new Field("Field" + (i + 1), i + 1);
}
String commaSeparatedName =
Arrays.stream(board) // all items as stream
.map(Field::getName) // for each take its name
.collect(Collectors.joining(", "); // join names with a comma
System.out.println("Board: [" + commaSeparatedNames +"]");

Need help searching a linked list [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Hello everyone i have trouble searching a linked list. Basically I'm reading from a csv file and storing it in the linked list. I was able to add the list at the end. But when i search the list it keep saying it wasn't found. The method function is called contains. A method "contains" that takes a Country object as parameter and checks if the name of the country can be found in the list . to check whether object foo of type Country equals objects bar of type Country, you must override the "equals method" in class Country. When I'm running the code it returns not found and i found out the method contains from class countryNode returns null thats why its returns not found. I will appreciate the help thanks. Everything works except from the contains method. Below is my code:
public Country contains(Country obj)
{
if(this.isEmpty())
{
System.out.println("Sorry this is an Empty list");
return null;
}
else{
CountryNode current = first;
while(current!=null)
{
if(current.getCountry().equals(obj))
{
return current.getCountry();
// break;
}
current = current.getNext();
}
return null;
}
}
The class Country and the overrides method equals:
public class Country {
private String countryNames;
private SubscriptionYear[] subscriptions;
private int size;
private int location;
public Country(String country)
{
this.countryNames = country;
}
public Country(String country, int arraylength)
{
this.countryNames = country;
this.size = arraylength;
subscriptions = new SubscriptionYear[size];
location = 0;
}
public void addSubscriptionYear(int year, double subscription)
{
subscriptions[location]= new SubscriptionYear(year, subscription);
++location;
}
public String toString()
{
System.out.print(countryNames+"\t");
for(SubscriptionYear s: subscriptions)
{
//System.out.print(countryNames+"\t");
System.out.print(s.getSubscription()+"\t");
}
System.out.println();
return "";
}
public String getName()
{
return this.countryNames;
}
public boolean equals(Country obj)
{
return (this.countryNames==obj.countryNames);
}
}
This my test main file:
import java.util.Random;
import java.util.Scanner;
public class TestCountryList
{
/**
* Builds a list of countries to debug.
*/
private void debugListOfCountries(Country [] allCountries)
{
// TO COMPLETE
}
/**
* Builds a random list of countries.
*/
private void testRandomListOfCountries(Country [] allCountries)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("How many countries do you want to add to the list?");
int requestedSize = keyboard.nextInt();
// Build the list out of a random selection of countries.
Random random = new Random();
CountryList selectedCountries = new CountryList();
for (int i = 0; i < requestedSize; i++)
{
int selectedIndex = random.nextInt(allCountries.length);
selectedCountries.add(allCountries[selectedIndex]);
}
// Note: To debug your list, comment this line in
System.out.println("List of countries: " + selectedCountries);
// Check if the name of a country is in the list.
// If the country is found, print the details.
// Otherwise output not found.
System.out.println("\nWhat country do you want to search for?");
String countryToFind = keyboard.next();
Country obj = new Country(countryToFind);
Country foundCountry = selectedCountries.contains(obj);
if (foundCountry != null)
{
System.out.println("Country " + countryToFind + " found with details:" + foundCountry);
}
else
System.out.println("Country " + countryToFind + " not found.");
}
/**
* Includes test examples for class GraphView.
*/
public static void main(String[] args)
{
// Create and set objects of type Country
//
final String FILENAME = "data/cellular.csv"; // Directory path for Mac OS X
//final String FILENAME = "data\cellular.csv"; // Directory path for Windows OS (i.e. Operating System)
final int NUM_COUNTRIES_TO_TEST = 3; // Note: Include test cases in addition to 3
// Parse the CSV data file
//
CSVReader parser = new CSVReader(FILENAME);
String [] countryNames = parser.getCountryNames();
int [] yearLabels = parser.getYearLabels();
double [][] parsedTable = parser.getParsedTable();
// Create and set objects of type Country
//
Country [] countries;
countries = new Country[NUM_COUNTRIES_TO_TEST];
Country current;
countries = new Country[countryNames.length];
for (int countryIndex = 0; countryIndex < countries.length; countryIndex++)
{
int numberOfYears = yearLabels.length; // OR numberOfYears = dataTable[countryIndex].length;
current = new Country(countryNames[countryIndex], numberOfYears);
for (int yearIndex = 0; yearIndex < numberOfYears; yearIndex++)
{
double [] allSubscriptions = parsedTable[countryIndex];
double countryData = allSubscriptions[yearIndex];
current.addSubscriptionYear(yearLabels[yearIndex], countryData);
}
countries[countryIndex] = current;
}
TestCountryList application = new TestCountryList();
// Note: Initially, to test your output you may hard code the number of
// countries added, and the array positions selected.
// However, make sure to comment this out before submitting your work.
//application.debugListOfCountries(countries);
application.testRandomListOfCountries(countries);
}
}
Try overriding equals method of Object as below:
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return (this.countryNames.equals(((Country)obj).countryNames));
}
internally contains call countryList.equals method and equals method's signature is
public boolean equals(Object obj) {}
As opposed to
public boolean equals(Country obj) {}
Also you are just comparing two reference of strings while you need to compare the contents of String. So instead of
this.countryNames==obj.countryNames
You should say:
this.countryNames.equals(obj.countryNames);
you need to use equals or equalsIgnoreCase to compare String
public boolean equals(Country obj)
{
return this.countryNames.equals(obj.countryNames);
}

Inner if statement is skipped for some reason during debug and run

The inner if statement is being skipped completely, when I step through the code It never enters updateGrade. It just skips the if entirely. why?
heres the method in question:
public void updateCourse(String courseID, String newLetterGrade){
for(int i=0; i<classesTaken.size(); i++){
if(classesTaken.contains(courseID)){
classesTaken.get(i).updateGrade(newLetterGrade);
}
}
}
according to my debugger when i = 5 and my arrayList = 6 once i hits 6 it passes breaks out of the loop right away for no reason. I'm not sure what is wrong as there are no errors shown at make or when running.
this is the method that is called when contents of courseID is found in classesTaken:
public void updateGrade(String newGrade){
letterGrade=newGrade;
compute(newGrade);
My test file looks like this:
public class TranscriptTester {
public static void main(String[] args){
Transcript test = new Transcript("11234", "Cody");
test.addCourse("COP2013","A+");
test.addCourse("COP2014","B+");
test.addCourse("COP2015","B+");
test.addCourse("COP2016","D+");
test.addCourse("COP2017","A");
test.addCourse();
test.updateCourse("COP2013", "B-");
test.updateCourse("COP2014", "A+");
test.getGPA();
test.printArray();
test.toString();
}
}
according to my code it should jump into the if statement at the first iteration of classesTaken because COP2013 is at 0 index.
If you need anymore information in order to help me just ask. Thanks!
here is all of the class files if you want to see what all of it is:
public class Course {
//global variables
private String courseID;
private String letterGrade;
private Double numberGrade;
//CONSTRUCTORS
//param
public Course(String id, String letter){
courseID = id;
letterGrade=letter;
compute(letter);
}
//default
public Course(){
courseID = "COP2053";
numberGrade = 4.0;
letterGrade = "A";
compute(getLetterGrade());
}
//COMPUTING GRADES AND UPDATING
private void compute(String letter){
if(letter == "A+"){numberGrade = 4.0;}
else if(letter == "A"){numberGrade = 3.67;}
else if(letter == "A-"){numberGrade = 3.33;}
else if(letter == "B+"){numberGrade = 3.00;}
else if(letter == "B"){numberGrade = 2.67;}
else if(letter == "B-"){numberGrade = 2.33;}
else if(letter == "C+"){numberGrade = 2.00;}
else if(letter == "C"){numberGrade = 1.67;}
else if(letter == "C-"){numberGrade = 1.33;}
else if(letter == "D+"){numberGrade = 1.0;}
else if(letter == "D"){numberGrade = .67;}
else if(letter == "D-"){numberGrade = .33;}
else if(letter == "F"){numberGrade = 0.0;}
}
public void updateGrade(String newGrade){
letterGrade=newGrade;
compute(newGrade);
}
#Override
public String toString(){
return "\nCourse: "+getCourseID()+"\nLetter Grade: "+getLetterGrade()
+"\nGPA in course: "+numberGrade;
}
//GETTERS
public String getCourseID(){
return courseID;
}
public String getLetterGrade(){
return letterGrade;
}
public Double getNumberGrade(){
return numberGrade;
}
}
Transcript file:
public class Transcript {
private ArrayList<Course> classesTaken = new ArrayList<Course>();
public Transcript(String studentID, String studentName){
System.out.println("\nStudent ID: "+studentID+"\nStudent Name: "+studentName);
}
public void addCourse(String courseID, String letterGrade){
Course myCourse = new Course(courseID,letterGrade);
classesTaken.add(myCourse);
}
public void addCourse(){
Course myCourse = new Course();
classesTaken.add(myCourse);
}
public void updateCourse(String courseID, String newLetterGrade){
for(int i= 0; i<classesTaken.size(); i++){
if(classesTaken.get(i).equals(courseID)){
classesTaken.get(i).updateGrade(newLetterGrade);
}
}
}
public void getGPA(){
System.out.println("\nOverall GPA: "+calculateGPA());
}
private Double calculateGPA(){
Double overallGPA = 0.0;
for(int i=0; i<classesTaken.size(); i++){
overallGPA = classesTaken.get(i).getNumberGrade()+overallGPA;
}
return overallGPA / classesTaken.size();
}
public void printArray(){
for(int i=0; i<classesTaken.size(); i++){
System.out.println("\n"+classesTaken.get(i));
}
}
}
Just looking at your code I see that you're misusing (unless you use equals with String) the contains method:
classesTaken.get(i).updateGrade
You're invoking updateGrade on object (of some type, not String), which is obviously not String type.
But you try to find the String in the list classesTaken list:
classesTaken.contains(courseID)
Obviously there are no String's in this list. Otherwise the code wouldn't even compile (because String hasn't updateGrade method)
You should override equals or provide other method for finding out if the string is in the collection of object of your custom class
You should do something like this (let assume your class is ClassTaken):
for(int i=0; i<classesTaken.size(); i++){
ClassTaken c = classesTaken.get(i);
if(c.getCourseId().equals(courseID)){
c.updateGrade(newLetterGrade);
}
}
In your updateCourse method, you are comparing a Course object (an item from classesTaken ArrayList) with a String object (courseID). So the if condition is never satisfied.
Like the following, override the equals method in the Course class so that you could use the "contains" method to compare courses.
#Override
public boolean equals(Object other){
if (other == null) return false;
if (other == this) return true;
if (!(other instanceof Course))return false;
Course otherCourse = (Course)other;
return this.courseID.equals(otherCourse.courseID);
}
And then you need to update the updateCourse method in your Transcript class as well to make sure objects of the same type are being compared:
public void updateCourse(String courseID, String newLetterGrade){
Course c = new Course(courseID, newLetterGrade);
for(int i= 0; i<classesTaken.size(); i++){
if(classesTaken.get(i).equals(c)){
classesTaken.get(i).updateGrade(newLetterGrade);
}
}
}
It seems that classesTaken stores Courses, not Strings. So it will never contain the ID itself.
It seems like what you might want is something along the lines of classesTaken.get(i).getID().equals(courseID), assuming a getID function.

getting incompatible types when using .length method

I am working on an exercises from Objects first with java for self review. The part of the exercises that I am having trouble with is where it asks me to find the length of the refNumber string..if the length of the string is zero, then print out a line saying "zzz". I have tried doing this by making a local variable, and making it equal to refNumber.length(). However in my conditional statement bluejay indicates that I have an incompatible type. Ugh, please help. Thanks in advance.
class Book
{
// The fields.
private String author;
private String title;
private int pages;
private String refNumber;
/**
* Set the author and title fields when this object
* is constructed.
*/
public Book(String bookAuthor, String bookTitle, int numberOfPages)
{
author = bookAuthor;
title = bookTitle;
numberOfPages = pages;
refNumber = "";
}
public String getAuthor()
{
return author;
}
public String getTitle()
{
return title;
}
public int getPages()
{
return pages;
}
public String getRefNumber()
{
return refNumber;
}
public void setRefNumber(String ref){
ref = refNumber;
}
public void printTitle() {
System.out.println("Book desciption: " + title);
}
public void printAuthor() {
System.out.print(" by " + author);
}
public void printPages(){
System.out.println("Pages: " + pages);
}
public void printRef(){
int count = refNumber.length();
if (count = 0){ //incompatible type wtf?
System.out.println("zzz");
}
else {
System.out.println("Reference Number: " + referenceNumber);
}
}
Most programming languages use the single equals sign = to be an assignment operator. What you are trying to do is compare the two numbers, which uses the double equal sign ==.
So, effectively, your code is trying to assign count with the value 0, then check if the value is true or false. And since the result of an assignment operation is neither true nor false, it throws the error.
As other people are saying, use count == 0.
try it ..get out put
if (refNumber.length() == 0){
System.out.println("zzz");
}
It should be
if(count == 0)
In your code it's like you are assigning 0 to count which cannot happen in the if clause, since it expects a boolean based on the condition. So here you should check if count is equals (using equality operator == ) and in return it returns true if they are equal or false otherwise.
Use this:
if (count == 0){
....
}
'=' is assignment operator and '==' is comparison operator
count=0 stands for assignment while count==0 stands for comparison.

Categories

Resources