Java带返回值的方法的定义和调用详解
作者:hmm?. 时间:2022-10-05 21:01:09
带返回值的方法练习
需求: 设计一个方法可以获取两个数的较大值,数据来自于参数
思路:
1. 定义一个方法,用于获取两个数中的较大数
public static int getMax(int a,int b){
}
2.使用分支语句分两种情况对两个数的大小进行处理
if (a>b) {
}else{
}
3. 根据题设分别设置两种情况下对应返回值结果
if (a>b) {
return a;
}else{
return b;
}
4. 在main() 方法中调用定义好的方法并使用变量保存
public static void main (String[ ] args){
int result = getMax(10,20);
system.out.println(getMax(10,20));
}
示例代码:
public class methodtext {
public static void main(String args[]){
int result = getMax(10,20);
System.out.println(result);
}
public static int getMax(int a,int b){
if(a>b){
return a;
}else{
return b;
}
}
}
方法的注意事项
方法注意事项
* 方法不能嵌套定义
* void表示无返回值,可以省略return,也可以单独书写return,后面不加数据
方法通用格式
格式:
public static 返回值类型 方法名(参数){
方法体;
return数据;
}
*定义方法时,要做到两个明确:
明确返回值类型:主要是明确方法操作完毕之后是否有数据返回,如果没有,写void;如果有,写对应的数据类型
明确参数:主要是明确参数类型和数量
调用方法时:
void类型的方法,直接调用即可
非void类型方法,推荐用变量接收调用
来源:https://blog.csdn.net/m0_68089732/article/details/123977812
标签:Java,方法调用,方法定义
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java 实现判定顺序表中是否包含某个元素(思路详解)
2023-09-11 01:03:04
![](https://img.aspxhome.com/file/2023/4/58474_0s.png)
Java线程池大小的设置方法实例
2022-10-04 04:20:19
详解Spring 中 Bean 对象的存储和取出
2023-08-06 02:42:46
![](https://img.aspxhome.com/file/2023/2/57832_0s.png)
Spring Boot 定义系统启动任务的多种方式
2023-11-24 13:25:33
![](https://img.aspxhome.com/file/2023/7/61947_0s.png)
java操作Apache druid的实例代码
2023-12-24 02:10:58
spring mvc 组合mybatis框架实例详解
2023-11-28 04:56:04
![](https://img.aspxhome.com/file/2023/2/59752_0s.png)
java实现发送邮件的示例代码
2023-07-04 17:00:54
![](https://img.aspxhome.com/file/2023/6/68216_0s.png)
Java 按行读取文件按行写入文件并以空格分割字符串的方法
2023-08-31 12:32:21
Java常用的八种排序算法及代码实现+图解
2022-04-09 13:30:06
![](https://img.aspxhome.com/file/2023/2/68132_0s.png)
浅谈virtual、abstract方法和静态方法、静态变量理解
2022-08-29 02:29:14
JAVA WSIMPORT生成WEBSERVICE客户端401认证过程图解
2023-11-14 00:27:55
![](https://img.aspxhome.com/file/2023/5/58985_0s.png)
Android实现带动画效果的可点击展开TextView
2023-08-06 05:42:08
![](https://img.aspxhome.com/file/2023/9/85989_0s.png)
Java使用iTextPDF生成PDF文件的实现方法
2023-10-15 10:44:13
![](https://img.aspxhome.com/file/2023/7/58687_0s.png)
安卓GreenDao框架一些进阶用法整理
2023-06-17 03:27:21
浅谈java中String StringBuffer StringBuilder的区别
2023-11-29 13:34:40
Java 反射机制实例详解
2023-11-28 03:49:47
关于MyBatis中SqlSessionFactory和SqlSession简解
2022-02-18 13:57:37
SpringCloud eureka(server)微服务集群搭建过程
2023-05-22 15:08:55
![](https://img.aspxhome.com/file/2023/4/69104_0s.jpg)
C#实现对Json字符串处理实例
2023-06-21 08:26:24
SpringBoot配置shiro安全框架的实现
2023-09-07 19:55:38