OOP School work (beginner) - java

As is, it does compile.
Bug = printing breed and declawed statements on same line. Cannot get rid of this bug for some reason
Bug = unable to get the result logic to compile and print for
console (newb)
There are examples a little like mine posted but they really haven't done anything to help because they are not exactly what I think I'm supposed to be going for. One worked perfect but uses and array and we aren't even to that part yet in my course. Here are the teachers instructions and some tips he gave me and then my code so far. Some of it is commented out since I'm trying to get rid of bugs before printing the result. Also I did change some of the names for convenience until the assignment is complete. Sorry for any formatting issues. Any advice?
In this order:
assignment instruction for class file
tip from the teacher
class file code so far
assignment for the driver file
driver file code so far
ASSIGNMENT INSTRUCTIONS FOR THE CLASS FILE:
Create a new class called Cat that includes the functionality below
The new class has the attributes of:
name – type String
age – type integer
weight – type double
breed - type String
declawed - type boolean - true for has no claws, false for has claws
Be sure your classes have a reasonable complement of constructor, accessor and mutator methods. Every member variable must have at least one independent accessor and one independent mutator.
Example:
public void setName(String name) mutator used to set name
public void setBreed(String breed) mutator used to set the breed
public void set(Boolean declawed) used to set claws or not
****(You must overload the set method to set deClawed value)** what is this?**
public String getName() accessor used to get name
public String getBreed() accessor used to get breed
public boolean getBoolean() access used to get the value of declawed
Ensure you use the “this” reference from within this class when referring to every instance variable or instance method of the current object.
TIP FROM THE TEACHER:
for your IF statement you will only use Age and Claw methods but
then at the end when you print out everything you will need the rest of the
methods. You can create a display method to display all the print
statements for each category such as name, age, etc...then it becomes
easier to display this in the main method - here would be your code in the
main method:
System.out.println("The cat data entered is: \n");
myCat1.display();
myCat2.display();
myCat3.display();
code for class file so far
/*************************************************************************************************
*Cat.java
*Jonathan Nees
*
*Cha. 6 OOP
*************************************************************************************************/
import java.util.Scanner;
public class Cat
{
private String name;
private int age;
private double weight;
private String breed;
private boolean declawed;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return this.name;
}
public void setAge(int age)
{
this.age = age;
}
public int getAge()
{
return this.age;
}
public void setWeight(double weight)
{
this.weight = weight;
}
public double getWeight()
{
return this.weight;
}
public void setBreed(String breed)
{
this.breed = breed;
}
public String getBreed()
{
return this.breed;
}
public void setDeclawed(boolean declawed)
{
this.declawed = declawed;
}
public boolean isDeclawed()
{
if (!this.declawed == false)
{
return true;
}
else
{
return false;
}
}
Scanner input = new Scanner(System.in);
public void display()
{
System.out.print("Enter the name of Cat: ");
this.name = input.nextLine();
System.out.print("Enter the age of Cat: ");
this.age = input.nextInt();
System.out.print("Enter the weight of Cat: ");
this.weight = input.nextDouble();
System.out.print("Enter the breed of Cat: ");
this.breed = input.nextLine();
System.out.print("Does the cat have claws? True or False?: ");
this.declawed = input.nextBoolean();
}
}
Assignment instructions for the driver file
Write a driver program that reads in 3 pets of type Cat and prints out the name and age of all cats with claws and over 3 years old.
The following information should be read in:
Name (as String)
Age (as int)
Weight (as double)
Breed (as String)
DeClawed (as boolean)
Ensure you use the accessor methods to check the age and claws.
code for driver file so far
/*************************************************************************************************
*CatDriver.java
*Jonathan Nees
*
*Cha. 6 OOP Driver
*************************************************************************************************/
import java.util.Scanner;
public class CatDriver
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
Cat Cat1 = new Cat();
Cat Cat2 = new Cat();
Cat Cat3 = new Cat();
Cat1.display();
System.out.println();
Cat2.display();
System.out.println();
Cat3.display();
System.out.println();
//*for (int i=0; i<3; i++)
//{
// System.out.println("The cats over 3 with claws are:");
// if ((!this.age() <= 3) && (this.Declawed() == true))
// {
// System.out.println("Name: " + this.name);
// System.out.println("Age: " + this.age + "Years Old");
// }
//}
}
}
Like I said I've commented some out to work out the bugs before doing the result.
It almost works! Sorta...

I was able to get it to work. I rewrote your display method using setter methods and it did the trick. Also, your declawed setter method is written a little confusingly so you may want to tinker with it.
Try this:
public void display()
{
System.out.print("Enter the name of Cat: ");
this.setName(input.nextLine());
System.out.print("Enter the age of Cat: ");
this.setAge(Integer.valueOf(input.nextLine()));
System.out.print("Enter the weight of Cat: ");
this.setWeight(Double.valueOf(input.nextLine()));
System.out.print("Enter the breed of Cat: ");
this.setBreed(input.nextLine());
System.out.print("Does the cat have claws? True or False?: ");
this.setDeclawed(!Boolean.valueOf(input.nextLine()));
}

Related

Return statement continues to prompt user to input String

The aim of my program is to take input of an attribute of an animal and then print the animal that has a corresponding attribute. I've used setter and getter methods along with three other methods that create the correct characteristics of the animals and then check if the attribute inputted corresponds with the animal.
My issue is that my input() method that's supposed to return the inputted String will run once if you put in an attribute corresponding to the first animal, but if you input a attribute corresponding to the second or third animal it will re-prompt you two or three times respectively, and once the program does find the correct animal it will just continue to re-prompt the user until for input. Like this:
Enter one attribute you'd like in your pet: green
Enter one attribute you'd like in your pet: green
Enter one attribute you'd like in your pet: green
You can have a Parrot
Enter one attribute you'd like in your pet: green
Enter one attribute you'd like in your pet: green
You can have a Parrot
Enter one attribute you'd like in your pet: green
You can have a Parrot
Process finished with exit code 0
I'm not sure why this is happening or how to fix, all I need is the input prompt to happen once and then print the correct animal to the user. Any help would be greatly appreciated, thanks. My current code is this:
import java.util.*;
class Main {
private static String name;
private static String colour;
private static String personality;
private static String noise;
public String input(){
Scanner sc = new Scanner(System.in);
System.out.print("Enter one attribute you'd like in your pet: ");
String input = sc.next();
return input;
}
public void setName(String name) {
this.name=name;
}
public void setColour(String colour) {
this.colour = colour;
}
public void setPersonality(String personality) {
this.personality = personality;
}
public void setNoise(String noise) {
this.noise = noise;
}
public String getName(){
return this.name;
}
public String getColour(){
return this.colour;
}
public String getPersonality(){
return this.personality;
}
public String getNoise(){
return this.noise;
}
public void PetOne(){
Main petOne = new Main();
String input = input();
petOne.setName("pug");
petOne.setColour("tan");
petOne.setPersonality("playful");
petOne.setNoise("woof");
if(input.equals(petOne.getName()) || input.equals(petOne.getColour()) || input.equals(petOne.getPersonality()) || input.equals(petOne.getNoise())){
System.out.println("You can have a Pug");
} else PetTwo();
}
public void PetTwo() {
Main petTwo = new Main();
String input = input();
petTwo.setName("cat");
petTwo.setColour("brown");
petTwo.setPersonality("affectionate ");
petTwo.setNoise("meow");
if(input.equals(petTwo.getName()) || input.equals(petTwo.getColour()) || input.equals(petTwo.getPersonality()) || input.equals(petTwo.getNoise())){
System.out.println("You can have a Cat");
} else PetThree();
}
public void PetThree() {
Main petThree = new Main();
String input = input();
petThree.setName("parrot");
petThree.setColour("green");
petThree.setPersonality("intelligent");
petThree.setNoise("squawk");
if(input.equals(petThree.getName()) || input.equals(petThree.getColour()) || input.equals(petThree.getPersonality()) || input.equals(petThree.getNoise())){
System.out.println("You can have a Parrot");
} else throw new RuntimeException
("Attempt to use real attributes n/0");
}
public static void main(String[] args) {
Main m = new Main();
m.PetOne();
m.PetTwo();
m.PetThree();
}
}
Try calling the input() method from main() and saving the result as a String which you refer to in the Pet() methods. Your input could be saved as a global variable or passed around as a parameter. This will avoid asking for the same input many times over.
Also, run your program in debugging mode and go through it line by line to ensure you understand why it is currently asking the user for the input so often. Debugging can be good for learning as well as fixing :)

How do I find the smallest variable from a list of objects? (JAVA)

The code doesn't show any errors. However, I am getting an unexpected output. I am supposed to get the smallest number for age, but what I keep getting is the last value entered for age. Can you help me point out the mistakes in this code?
Maybe there is some logical error in the getYoungestPet() method?
package pet;
public class Pet
{
public static String petName;
public static int petAge, petWeight;
int youngestAge=9999;
static int test;
public static String setPetName()
{
return petName;
}
public int setPetAge()
{
return petAge;
}
public int setPetWeight()
{
return petWeight;
}
public int getYoungestPet() //probably an error here..?
{
if (petAge<youngestAge)
youngestAge=petAge;
return youngestAge;
}
}
package pet;
import java.util.Scanner;
public class PetMain extends Pet
{
public static void main(String[] args)
{
System.out.println("How many pets do you want to enter? " );
Scanner data= new Scanner(System.in);
int petNumber=data.nextInt();
for (int i = 1;i<=petNumber; i++)
{
Pet PetObject = new Pet();
System.out.println("Please enter name for Pet " + i );
Scanner input = new Scanner(System.in);
petName= input.next();
System.out.println("Your pet's name is : " + petName);
System.out.println(" ");
System.out.println("Please enter " + petName + "'s Age" );
petAge= input.nextInt();
System.out.println("Your pet's age is : " + petAge);
System.out.println(" ");
System.out.println("Please enter " + petName + "'s Weight" );
petWeight= input.nextInt();
System.out.println("Your pet's weight is : " + petWeight);
System.out.println(" ");
System.out.println(PetObject.getYoungestPet());
}
}
}
The code is supposed to show the smallest age but it shows the latest entered age.
you should declare youngestAge as static variable. so that all of the petObject could share the same value.
static int youngestAge=9999;
your setter and getter methods are also not proper.
public static String setPetName()
{
return petName;
}
should be:
public static void setPetName(String name)
{
petName=name;
}
Also don't forget to set values into PetObject from main method.
...
petName= input.next();
PetObject.setPetName(petName);
...
There are many things that are problematic with this code.
But just to answer your question directly, think about how many pet objects there could be in this program if every time the for loop runs it recreates the pet object because it is inside the for loop.
however, simply moving it outside the for loop will not help because then you will simply keep resetting the values of the same pet object every time you run the for loop.
Consider making an array of pet objects.
Also, your code never actually accesses the pet objects instance variables
In addition, there are other problems with your use of static as others have pointed out.
cheers.
Each time you are creating a Pet, you are getting a different youngestAge with value 9999 for that object. So each time it is comparing the latest petAge with 9999 and giving you the latest petAge as your enterd petAge is less than 9999.
If you need to store the smallest age, then keep it in a static field. Cause, keeping an extra field to store the smallest age for all object is redundant for memory.
If you want your desired output with the existing design, then do this:
Make youngestAge static:
static int youngestAge=9999;
And also don't forget to make the method static too. There is no need to make it object property anymore, both the field variables, it is using, are static.
public static int getYoungestPet()
{
if (petAge<youngestAge)
youngestAge=petAge;
return youngestAge;
}

Proper use of objects

I have this method addPerson (on the main) which is used to set the name of a person.
private static Person[] addPerson(Person _person[], int _minAge, int _id){
int personAge;
String personName;
Scanner scan = new Scanner(System.in);
System.out.println("What's his age?");
personAge = scan.nextInt();
if(personAge >= _minAge){
if(!_person[_id].getPerson().equals("")){
System.out.println("Person " + _person[_id].getPerson() + " already exists.");
}else{
System.out.println("Enter the name of the person");
Scanner addPerson = new Scanner(System.in);
personName = addPerson.next();
_person[_id].setPerson(personName);
}
}else{
System.out.println("Person is not old enough");
}
return _person;
}
And here is the method setPerson in my custom class which is used to set the name of the person.
public void setPerson(String name){
System.out.println("Person added");
personName = name;
}
I know I should be doing the checking on whether that person already exists inside my setPerson method, but I am sort of confused with this. As you see I am expecting the user to input an integer, so I guess that I should check that right away to not get an error in case he inputs a string.
So my question is which should be checked within the same method and which on the method on my custom class?
Your code (and your question) is a bit confusing, but from what I can understand you want to know if you should check whether a person exists in the array in setPerson() or not?
Well, from what I can gather from your code, you should not do it in setPerson(), because that's a method in the Person class. The Person class shouldn't need to know anything about your array of Person objects.
So the way you're doing it now is probably your best bet.
Some general hints about the code:
There's no need to create a new Scanner, you can just use the one you have. So this
Scanner addPerson = new Scanner(System.in);
personName = addPerson.next();
becomes this
personName = scan.next();
I would also suggest you use the name setName()instead of setPerson()for your method name, it doesn't make sense to have it named one way when what it's actually doing is something else.
I would do it this way. However I don't have java currently so I didn't test this snippet.
class Person {
private String name;
public void setName(String name) {
this.name = name;
}
}
class Main {
private static final int minAge = 22;
private static Map<Person> addPerson(Map<Person> people, int id) {
if(people.containsKey(id)) {
// print that person with this id exists
return people;
}
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
if(age < minAge) {
// print that given age is invalid
return people;
}
String name = scanner.next();
people.get(id).setName(name);
return people;
}
}

Creating Methods and Classes (Java)

I am trying to write a class called Student that is supposed to work with a StudentDriver. However, I am having a very hard time wrapping my head around the concept of methods and classes. I do not know how to receive and return data. Moreover, I don't even know if I am declaring my data correctly. Please help me. I would greatly appreciate it.
Also when I compiled the Student it says that it cannot find the symbol this.setGPA. How so? When in the driver it has .setGPA.
Thank you.
// This will be the "driver" class for the Student class created in
// MinilabWritingClasses (It looks very complicated because of all
// the comments, but it really just creates instances of Student and
// tells them to do things...)
public class StudentDriver
{
public static void main(String[ ] args)
{
//create an instance of Student
System.out.println("***** Creating a Student, calling the default constructor");
Student stud1 = new Student();
//print it so we can see what the default values were for the class data
//note that its toString() will be called automatically
System.out.println("\n***** printing it - notice the default values (set by Java)");
System.out.println(stud1);
//create another instance of a Student, passing in initial values to its constructor
System.out.println("\n***** Creating another Student, passing initial values to its constructor");
Student msBoss = new Student("Bill Gates", 56, 'm', 3.2, true);
//tell it to return its age
System.out.println("\n***** telling it to return its age.");
int theAge = msBoss.getAge();
System.out.println("Its age is: " + theAge);
//print it - note that its toString() will be called automatically;
System.out.println("\n***** printing it - see if values are correct");
System.out.println(msBoss);
//ask it if it is on probation
System.out.println("\n***** asking it if it is on probation (check answer)");
System.out.println("onProbation() returned: " + msBoss.onProbation());
//tell it to change its gpa to 1.3
System.out.println("\n***** telling it to change its gpa to 1.3");
msBoss.setGPA(1.3);
//print it now
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(msBoss);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolean boolAnswer = msBoss.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
//tell it to complain
System.out.println("\n***** telling it to complain");
System.out.println("complain() returned: " + msBoss.complain());
//tell it to change its onScholarship field to false
System.out.println("\n***** telling it to change its onScholarship field to false");
msBoss.setOnScholarship(false);
//print it now
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(msBoss);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolAnswer = msBoss.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
//create a different student, tell it to have some different values, and tell it to print itself
System.out.println("\n***** creating a different Student, passing initial values to its constructor");
Student stud2;
stud2 = new Student("Hillary Clinton", 64, 'f', 2.0, true); //notice-can define variable and create it in 2 steps
//print it
System.out.println("\n***** printing it - see if the values are correct");
System.out.println(stud2);
//ask it if it is on probation now
System.out.println("\n***** asking it if it is on probation (check answer)");
boolAnswer = stud2.onProbation();
System.out.println("onProbation() returned: " + boolAnswer);
}
}
Here is the class that I am writing.
public class Student
{
private String name;
private int age;
private char gender;
private double gpa;
private boolean onScholarship;
public Student()
{
}
public Student(String newName, int newAge, char newGender, double newGPA, boolean newScholarship)
{
this.name = newName;
this.age = newAge;
this.gender = newGender;
this.gpa = newGPA;
this.onScholarship = newScholarship;
}
public int getAge(int newAge)
{
return age;
}
public double setGPA (double newGPA)
{
this.setGPA = newGPA;
}
public boolean setOnScholarship (boolean newScholarship)
{
this.setOnScholarship = newScholarship;
}
public String toString()
{
return this.name + "\t" + this.age + "\t" + this.gender + "\t" + this.setGPA + "\t" + this.setOnScholarship;
}
public boolean onProbation()
{
if (onScholarship==true && gpa < 2.0)
return true;
else
return false;
}
}
Try to change this line:
this.setGPA = newGPA;
to this:
this.gpa = newGPA;
setGPA symbol not found is because there is no setGPA field (it is a method). You are trying to change the gpa field.
You also don't need the empty public Student() {} constructor -- this is automatically created by Java.
Also, as #Sam pointed out, since setOnScholarship() doesn't return anything, you can change the return type boolean to void. This is because there is no return statement, and this returning of nothing is a void type.
Overall, though, you have a good understanding on creating instances of another class (i.e., creating Students).
On request (although it doesn't have much to do with your code), here is a brief summary on static.
The static keyword is used with methods and fields that are not used with an instance of that class, but the class itself.
For example, in your case, pretty much all of the Student fields and methods are non-static, because they are properties of Student objects:
this.gpa;
this.setGpa();
On the other hand, if it were not changing a variable related to a single object, for example the total number of students, you could create a static field in Student:
public class Student {
// non-static fields for each instance
public double gpa;
// static field for the class
public static numStudents;
public Student() {
// create student by setting object (non-static) fields, for example...
this.gpa = 3.2;
// edit static variable
numStudents++; // notice how there is no `this` keyword - this changes a static variable
}
}
... and from StudentDriver, numStudents can be retreived with:
Student.numStudents; // notice how this is like `this.[property]`, but with the class name (Student) - it is an instance of the class
I hope this helps! OOP programming is a difficult topic that can't be explained so simply.

Trying To Output A String From An Object Passed Into A Set

I'm trying to output a string from an Object that has been passed into a set. The Following line is where my problem lies. It outputs [alex, jane] but with correct formatting I believe it should be outputted at alex jane. i.e. without the comma separated value and the brackets from the array.
System.out.print(module.getStudents() + " ");
I've tried various solutions including:
System.out.prinf(%s, module.getStudents() + " ");
and
System.out.prinln(module.getStudents().[whatever Netbeans makes available] + " ");
To help you better understand the problem. The idea of the application so far is to allow a user to search for a mosule ans return all students connected to it. The full source code bar the driver is:
import java.util.*;
public class Control {
public void run() {
Student jane = new Student("jane");
Student alex = new Student("alex");
Set<Student> students = new HashSet<Student>();
students.add(jane);
students.add(alex);
Module ufce1 = new Module("UFCE1");
Module ufce2 = new Module("UFCE2");
Set<Module> modules = new HashSet<Module>();
modules.add(ufce1);
modules.add(ufce2);
jane.addModule(ufce1);
jane.addModule(ufce2);
alex.addModule(ufce2);
ufce1.addStudent(jane);
ufce2.addStudent(jane);
ufce2.addStudent(alex);
System.out.println("Search module code: ");
Scanner scan = new Scanner(System.in);
scan = new Scanner(System.in);
String searchModule = scan.nextLine().trim();
for (Module module : modules) {
if (searchModule.equalsIgnoreCase(module.getName())) {
Iterator it = students.iterator();
Student student = (Student) it.next();
if (student.getModules().contains(module)) {
System.out.print(student + " ");
}
}
}
}
}
Module Class:
import java.util.HashSet;
import java.util.Set;
public class Module {
private String name;
private Set<Student> students = new HashSet<Student>();
public Module(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addStudent(Student student){
students.add(student);
}
public Set<Student> getStudents() {
return students;
}
#Override
public String toString() {
return name;
}
}
Student Class:
import java.util.HashSet;
import java.util.Set;
public class Student {
private String name;
private Set<Module> modules = new HashSet<Module>();
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addModule(Module module){
modules.add(module);
}
public Set<Module> getModules() {
return modules;
}
#Override
public String toString() {
return name;
}
}
When you do this System.out.print(module.getStudents() + " "); you're implicitly calling the toString method on the HashSet instance. So to get the formatting you want, you have 2 choices:
iterate over the set and print it the way you want
Subclass HashSet and override toString to display the way you want it.
The problem is that getStudents returns a Set object (a HashSet, to be specific). HashSet, in turn, inherits a toString() method from AbstractCollection which behaves as follows:
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).
You'll need to write your own method for converting a set of students into the format you want, or else you can doctor up the value returned by the default toString implementation.
The brackets and the commas are coming from the toString() call on the Set. If you look in the source code of this method, you will see that it adds those. You can override the toString() method of the Set in your Module class, or just not printing the Set directly but manually looping over all elements and printing them one by one
#Chris gave an excellent solution in resolving your issues. There is however another one that I see more easy to implement and it is the following:
public String formatOutputString(){
String setStrings = module.getStudents();
// Get rid of opening bracket
String formatedString = setStrings.replace("[", "");
// Get rid of closing bracket
formatedString = setStrings.replace("]", "");
// Replace commas by spaces
formatedString = setStrings.replace(",", " ");
return formatedString;
}

Categories