问题
I am currently completing a project and am trying to create a menu. The menu itself works alright but when I try and link to the other java file that the method itself is in I get the error "the method method name is undefined for the type String". Below is the code that I am using to try and link to the method in the other java file.
{
if (menuChoice.equals("A"))
{
System.out.print("Enter the Movie ID: ");
movieID = sc.nextLine();
movieID.borrowMovie();
}
if (menuChoice.equals("a"))
{
System.out.print("Enter the Movie ID: ");
movieID = sc.nextLine();
movieID.borrowMovie();
}
if (menuChoice.equals("B"))
{
System.out.print("Enter the Movie ID: ");
movieID = sc.nextLine();
movieID.returnMovie();
}
if (menuChoice.equals("b"))
{
System.out.print("Enter the Movie ID: ");
movieID = sc.nextLine();
movieID.returnMovie();
}
Further to, below is the code of the 2 methods that I am trying to link to in the other java file. It is a requirement of the project to have 2 separate class files and to demonstrate how to use them both together but this part has got me stumped!
// Implement borrowMovie method
public double borrowMovie(String memberID)
{
if (this.isOnLoan = false)
{
this.isOnLoan = true;
}
else
{
return Double.NaN;
}
}
// Implement returnMovie method
public double returnMovie(int daysBorrowed)
{
if (this.isOnLoan = false)
{
return Double.NaN;
}
else
{
this.isOnLoan = false;
}
}
Any help at all will be appreciated :)
回答1:
Looking at your code, I guess that movieID is a String.
Class String does not have methods borrowMovie() and returnMovie(), so you'll get an error from the compiler that tells you so.
Instead of movieID.borrowMovie() you want: borrowMovie(movieID).
Here's another bug in your borrowMovie() and returnMovie() methods:
if (this.isOnLoan = false)
You are assigning the value false to this.isOnLoan here. That is most likely not what you want. Use == for comparison, = for assignment. Better yet, to check if a boolean is false, use !:
if (!this.isOnLoan)
Why are your methods returning double values?
回答2:
This line assigns the value false to isOnLoan and as such will always yield true.
if (this.isOnLoan = false)
Apart from this there's no return value on the else branch for example:
public double returnMovie(int daysBorrowed)
{
if (this.isOnLoan = false)
{
return Double.NaN;
}
else
{
this.isOnLoan = false;
return this.id;
}
}
来源:https://stackoverflow.com/questions/17810669/the-method-is-undefined-for-the-type-string-in-eclipse