Help with clarify some code
hello,
I am currently studying in class of Object Oriented Program were we are doing a simple program, however, I have some doubts that I could not clarify in classes.
we have a menu for adding some information about cat. This menu leads to addcat method. the method addcat has only this part of the code, however, I can not understand where we are asking cat information to the user and exactly why we use the following code
Code:
private boolean addCat (Cat cat)
{
if (catExists (cat.getId ()))
return false;
catList.add (cat);
return true;
}
private boolean catExists (String id)
{
for (Cat d: catlist)
if (d.getId (). equalsIgnoreCase (id))
return true;
return false;
}
Re: Help with clarify some code
That part of the code shouldn't ask information from the user; all the code does is check if a Cat is already in a list and if not, add it to the list. The second method does the checking for a Cat being present in a list. Another part of the code (which you should design and implement) should ask the user for the necessary information. This 'split' is called 'separtion of concerns' and it's a good thing.
kind regards,
Jos
Re: Help with clarify some code
Thanks for you help. It was actually what I was thinking.
So, I it should have a main method that ask the information from the user. However there is some restrictions in another separate program of how the id should be:
Code:
//PROGRAM A CATS
private static String id;
public Cat(String id) throws Exception
{
setId(id);
}
public String getId()
{
return id;
}
public void setId(String id) throws Exception
{
if (id.length()==5 &&
Character.isDigit(id.charAt(0)) &&
Character.isLetter(id.charAt(1)) &&
Character.isDigit(id.charAt(2)) &&
Character.isDigit(id.charAt(3)) &&
Character.isDigit(id.charAt(4)))
{
this.id = id;
}
else
{
throw new Exception ();
}
}
And then we have the program that I show you. I create a new main method that ask for the information, but it does not do the validation. I cannot understand how it will go to the other program and do the validation of the restriction of the ID and then come back to this one and validate that this cat is not in the list. And if we have the variables in the Cats program (PROGRAM A) why eclipse tells me that I have to create again the variables.
Code:
//Program B
{
String id;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter ID:");
id = keyboard.nextLine();
}
private boolean addCat (Cat cat)
{
if (catExists (cat.getId ()))
return false;
catList.add (cat);
return true;
}
private boolean catExists (String id)
{
for (Cat d: catlist)
if (d.getId (). equalsIgnoreCase (id))
return true;
return false;
}