Issue with instance variables - java

My overall goal at the moment is to call a method that is in a different class, there is no inheritance between the classes.
After researching i found the best way to do this was to initialise an instance of the object in the method I am trying to call it in.
Is there a standard way to do this?
Any help will be greatly appreciated.

You have to pass the correct parameter values, not declare them again. Like this:
Book b = new Book(title, author, publisher, year);
Of course, you have to know the values for title, author, publisher, year before calling the constructor. Also, the method is expecting a boolean return value, so you must have a return true; or return false; at the end, depending on what the method is expected to do.

i get the error "Constructor Book in class Book cannot be applied to
given types
Because you did'nt specified a no-args constructor in your Book class
I assume that you want to check if the book already exists
won't compile since this method (i.e the method checkForDuplicate()) doesn't return a boolean in all the cases (when b.equals() is false).
So you should do
if(b.equals() == true){
return true;
}else {
return false;
}
which is equivalent to return b.equals();

Related

How to name two variables that have the same meaning but different types

I have a method that parses a String and converts it to a boolean.
The legal values are "true" and "false".
boolean convertStringToBoolean(String text) {
if (text.equals("true") {
return true;
} else if (text.equals("false")) {
return false;
} else {
throw new IllegalArgumentException(text);
}
}
When I use this variable, I get a naming problem.
void doSomething(String isSpecificReadString) {
boolean isSpecificRead = convertStringToBoolean(isSpecificReadString);
...
}
The problem is that the parameter carries a meaning that I want to keep in its name.
The meaning doesn't change just because the type is changed.
So far, my solution has been to just suffix the type to the parameter.
But I don't like this solution.
What should I call the variables to solve this problem?
So far, my solution has been to just suffix the type to the parameter.
But I don't like this solution.
Strongly typed language as Java works in this way.
Variables cannot change their type at runtime.
You have to accept the language constraints.
Converted a data from a type into another type within a method may create this issue.
But your actual solution is rather fine.
The intention is clear and you kept a natural name for the target variable.
You indeed added the type suffix only for the input that will be converted (temporary/intermediary variable), not for the output that will be used in the next statement(s).
As inspired by Andy Turner, I can make two doSomething methods.
A method that takes a String and another that takes a boolean.
The String method can then call the boolean method.
As follows:
void doSomething(String isSpecificRead) {
doSomething(convertStringToBoolean(isSpecificReadString));
}
void doSomething(boolean isSpecificRead) {
...
}

comparing object calling the method

i know this is very trivial, but for some reason i'm having a little trouble. i'm trying to write a method that has a book object from an array list calling the method that compares it to another book in the same list. I think i got the gist of it but i'm just not understanding how to compare them. i think it's supposed to look something like this.
public Boolean isShorter(Book otherBook)
{
if(otherBook.getLength() < ???????.getLength() )
return true;
else
return false;
}
use "this" keyword to refer to the current object (the caller of the method).
like this:
otherBook.getLength() < this.getLength()

What does "void" mean as the return type of a method? [duplicate]

This question already has answers here:
Can someone explain a void return type in Java?
(5 answers)
Closed 6 years ago.
I'm confused about "void",
as it pertains to methods.
I don't know what the distinction between two methods is when one has "void" and another doesn't.
For example, if I do:
Public meth (int amount)
{
amount = initial * interest;
return amount;
}
( not sure if it was right, or even valid, to take the name "amount" and name it the same thing as my formal parameter, but what makes sense here is that you're performing a calculation and returning the result)
Then, if I did something like:
Public void Testing (int array[])
{
//code that would modify the internals of an array
}
Would the second one have no "return" because it's more of a general method, that can be applied to any integer array, while the first one is about doing work on specific variables?
Would also appreciate one or two more examples of when I would or wouldn't be using "void" and "return".
One other thing that seems to confuse me is calling methods.
I know sometimes I'll do something like, for example, using the Testing method above,
Testing(ArrayName);
Other times, it will be like:
NameOfWhateverImApplyingMethodTo.MethodName();
And then there are times when things will be done properly by:
Thing1.MethodName(Thing2);
Which circumstances would I switch the syntax for method calls like this?
Java is case sensitive, so the modifier Public is invalid, use public
You can't define a method as public methodName(int a), only a constructor has this signature, a method must be public void methodName(<signature>) for methods that don't return anything or public <return type> methodName(<signature>) for methods that do.
Void basically means that the method will not return anything.
If you did
String name= "tim";
public void getName(){
return name;
}
This would result in an error, because the getName method is returning a string object called name, but the method declaration is saying I am returning nothing - because it is void.
Instead the method should be :
String name = "tim";
public String getName(){
return name;
}
Now when the method getName() is called it will return a string object "name" with "tim" inside of it :)
You might have void for a set method. So for example
String name = "tim";
public void setName(String newName){
this.name = newName;
}
When this method is called you would use setName("Andy"); and it would set the value of the name variable to be "Andy". Nothing is returned in this method, because it is setting something, but there is no need to send anything back, so we use void on the method declaration.
Hope this helps.
The method that has void as return type does not return anything. For example you want to set a field firstName in your class. You will write a setting method like
public void setFirstName(String n) {
this.firstName = n;
}
As you can see you are just setting a class variable and does not require to return anything.
If you dont use void then you have to provide a return type for method. Like if you wish to write a getter for above variable as:
public String getFirstName() {
return this.firstName;
}
Once you provide a return type, you will have to return a value of that type otherwise your code will not compile.
Calling a method can be done based on where you are calling it from and what modifier is used:
If you are calling the method from the same class then you can simply write firstName = getFirstName()
If you are calling the method from another class then you require object of method's class as qualifier like personObject.getFirstName()
If you are calling a static method then you require class name as qualifier like Person.getFirstName();
Return type is what you get out of it. When you call it, what are you hoping to get back? For instance, if the method gets the average of two numbers, then you're expecting a number back, so the return type will be a number type, like "int" (integer).
You can see what it should be using that logic or by looking in the method for the word return - what comes after return is what is returned, and its type should be declared in the method (e.g. if it says "return 4;" it's returning an int, and should be e.g. public int getFour()
You also asked about e.g. testing() vs testing(word)
I remember having the same difficulty. The distinction between the two also relates to the method declaration line. I'll illustrate.
public String testing(){
return "a word";
}
Calling this method by doing "System.out.println(testing());" should print "a word". Calling this method by doing "System.out.println(testing("a word"));" will give you an issue - this is because when you call testing, it looks at the appropriate method: one in the right class, with the right return type and with the right arguments/parameters. If you're calling testing("a word"), that means you're using a String as an argument (because "a word" is a string), and so it tries to use the testing(String aString) method - which doesn't exist.
So you use empty brackets when the method takes no input, and you put stuff in brackets when the method expects stuff. This should be less confusing than it sounds, because it's usually logical - if you want to call a method that returns an average, you need to ask yourself "Average of what?" You'd probably need to supply it with the values you want the average of.
Moving on: (a) testing() versus(b) AClass.testing() versus(c) aclass.testing() -
In (a), there's no class specified. Therefore, if you call it from that class, Java can guess which class: this one, and it'll work. From any other class, it won't know what you're talking about, and might even insult you.
In (b), you're specifying a class in general - therefore it'll know what class to find it in - and it'll work if it's a "static method". *[see bottom]
In (c), you're specifying an instance of AClass you want to run "testing()" on*.
For instance, imagine you've created a class called Business. You make a hundred Business objects by specifying for each a name, number, address.
e.g.
Business b = new Business(name, number, address);
Then in the Business class you have a method "getName()". This method takes no argument - you could see that the brackets are empty - so if, from another class, you call "Business.getName()", how could it know which name you want? You've just made a hundred businesses!
It simply can't. Therefore, for such a method, you'd call "b.getName()" (b being the Business we created above) and it would get the name for this instance of a Business - namely, b.
I'm happy to help, so if you're confused about any particular parts of what I just wrote please let me know and I'll try to elaborate!
edit: A bit on static methods:
Static methods don't belong to an instance of the class. getName(), for example, would get the name of this Business - ie, this instance of the Business class. But let's say that in the Business class you made a method that took the first letter of each word in a String and transformed it to uppercase - like if you wanted to make the business names look more professional when you printed them out.
public static String stringToUpperCase(String aString){
aString = aString.substring(0, 1).toUpperCase() + aString.substring(1);
return aString;
}
And to use that, you change the getName() method from:
public String getName(){
return name;
}
to
public String getName(){
return stringToUpperCase(name);
}
The new method is used here to make the name have an uppercase first letter - but that is the extent of its involvement with the Business class. You notice it doesn't ask for information about the name, address, or number for a particular business. It just takes a string you give it, does something to it, and gives it back. It doesn't matter whether you have no Businesses or a hundred.
To call this method, you'd use:
System.out.println(Business.stringToUpperCase("hello"));
This would print Hello.
If it were not a static method, you'd have to make a new Business first:
Business b = new Business("aName", "aNumber", "anAddress");
System.out.println(b.stringToUpperCase("hello"));
And if the method did need access to more Business-instance information (like a business's name number or address) it wouldn't be able to be an instance variable.
The first example, a method without a return type at all, is a constructor; used when an instance is created with new. However, you can't return a value from a constructor. Something like,
this.amount = initial * interest; // return amount;
Sets the field amount to initial * interest.

Cant get public boolean removeBorrower(String libraryNumber) to work

The code needs to be able to reference two library numbers together, and if they are equal, remove the borrower from the array.
It won't let me run a method from another class because it's a static context. I don't know how else to solve this.
Here is what I have so far:
public boolean removeBorrower(String libraryNumber)
{
if(libraryNumber == null)
return false;
else if(Borrower.getLibraryNumber().equals(libraryNumber)))
borrowers.remove(Borrower);
return true;
}
You need to pass a reference to the other Borrower you want to compare against:
public boolean removeBorrower(String libraryNumber, Borrower otherBorrower)
{
if(libraryNumber == null)
return false;
else if(otherBorrower.getLibraryNumber().equals(libraryNumber)))
borrowers.remove(otherBorrower);
return true;
}
Before, you were trying the get the library number for the generic Borrower class, which doesn't make conceptual sense. With this code, you have a specific person to check the library number of.
You need to get an instance of the class containing removeBorrower method.
I don't think that you can't run the method from another class (unless the method is contained in a package-private class and the client class is not part of the same package).
Maybe you wanted to say that you're not allowed to run this method without having a reference to an existing instance of the class containing removeBorrwer method.

How I return array of my class type object?

Reedited...
public EventData getEventDetails(String evtId, String Status) {
//do some data selection here.
return evData1;
}
public EventData[] getAdminAuthEvtDetails(String evtId, String Status) {
String eId=evtId;
String status=Status;
EventData[] evData=new EventData[2];
EventData[0] evData=getEventDetails(eId,"V");
EventData[1] evData=getEventDetails(eId,"M");
return evData;
}
EventData is my java data class. In there I set getters and setters. I want to call getEventDetails method two time one status as verified and other as modified for requested ID and set both evData into one array. In here there give a error couldn't get data into EventData[0] and EventData[1].Is there any error of calling my getEventDetails method?
Finally I got correct code.
EventData[] evData=new EventData[2];
evData[0]=getEventDetails(eId,"V");
evData[1]=getEventDetails(eId,"M");
return evData;
in both methods you must return an object rather than Type
in 1st method:
public EventData getEventDetails(String evtId, String Status) {
return new EventData(evtId, status);//don't know how is you constructor of EventData, but its just a smart guess. the idea is to create an object
}
and in 2nd method return eData;
I believe you need to update your getEventDetails method as well. EventData is a class however you need to return an instance of the class generally created by calling the constructor new EventData().
Otherwise, ay89 is correct that getAdmin... should return eData.
Conceptually, it's correct. You just have some syntax issues that others have mentioned (like returning a variable instead of a class).
Otherwise, some other things to note:
You'll want to probably use a lowercase "s" for "Status" since conventionally, variables shouldn't start with upper cases.
You probably dont need to redeclare the evtId to eid. You can just use the evtId (and the incorrectly cased Status) variable directly.
Personally, I like to perhaps call the getEventDetails(...) method something more like createEventDetails(...) since it's more indicative of the function of that method. "Get" always implies fetching instead of creating to me.
Just my 2c

Categories