我最近开始尝试 return 语句,并且对此有一个小疑问 - 当我有一个方法调用另一个方法时,我正在调用的该方法的 return 语句会显示吗?
让我们举个例子来让它更清楚-
/** Program to test return statment */
public class Test
{
public static void main(int a)
{
EvenOrOdd(a);
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display(As in that window does not pop up with the result.)
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
如果我只是删除主方法(或者甚至公开第二个方法并直接运行它),则会显示我的返回语句,但是如果我尝试调用该方法并运行程序,则不会显示我的返回语句.
这只是我面临的一个问题还是Java中的一般规则是当你调用另一个方法(有一个return语句)时return语句不起作用?
如果是后者,那么我很抱歉,我不知道这一点。
谢谢...
***UPDATE***
看来没有人明白我的意思。我再举一个例子-
请运行此程序-:
/** Program to test Return statment;simple program to return sum of two digits */
public class Return_Test
{
public static int main(int a,int b)
{
return a+b;//What I am lloking for is that box in which this is displayed.
}
}
最佳答案
return语句只返回值,不显示 如果不捕获返回值,怎么显示呢?添加这样的东西并尝试 ,
public class Test
{
public static void main(int a)
{
boolean temp=EvenOrOdd(a);
if(temp)
System.out.println("Output is True");
else
System.out.println("Output False(not even )");
//Or you can directly call the method as' System.out.println(EvenOrOdd));'
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
请尝试学习一些好的命名约定,类是这样命名的, FirstSecond,TestException(每个单词以大写字母开头)等,方法以小写字母开头,isPrime(),isEven(),
关于java - 调用另一个方法时返回语句不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26501328/