Java提示缺少返回语句的解决办法
作者:李琳琅 时间:2021-08-04 19:42:03
Java提示缺少返回值语句怎么办?这里我们给大家提供具体的解决方法。
首先,以下面的程序为例,会看到在控制台有:错误:缺少返回语句的提示。
找到类中定义的方法test中发现,明明已经定义了return,软件依然会提示错误。
将return定义到for循环之外,就会发现,程序不再报错。
原因是因为数组不仅仅可以存放具体的变量值,而且可以不赋给数组任何值。
在数组内容为空的情况,程序是没有报错的,所以需要将return返回值定义到 for 循环之外即可。
关于Java中return缺少返回语句的解决方法总结如下:
Java 编译错误:缺少返回语句
import java.util.*;
import java.io.*;
public class tt {
public static void main(String[] args) {
foo();
}
public static String foo() {
int i=0;
while(i<10) {
return "ggg";
}
}
}
该函数编译便会报错:缺少返回语句。尽管看起来(i<10)是肯定为真的,但是编译器不会把i=0带进去算,所以它觉得foo函数有可能无返回值(即while后条件为假的时候)。
同理,把while改成if,编译报同样的错误。
把while(i<10)改为while(true)后,不再报错。
但是C就随意得多,跟Java比起来以下如此不确定的代码也能正常编译运行:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int a=foo();
printf("%d\n",a);
return 0;
}
int foo()
{
int i=0;
while(i++<10)
{
if(i>5) return 5;
else return 4;
}
}
再举个java例子:
这么写会提示缺少返回语句,
public static boolean has3(int[] a) {
for(int i=0; i<a.length; ++i) {
if (a[i]==3)
return true;
else
return false;
}
}
稍稍改动一下即可:
import java.util.*;
import java.io.*;
public class has {
public static void main(String[] args) {
int[] b = {1,2,3,4,5};
int[] c = {1,2,4,5};
System.out.println(has3(b));
System.out.println(has3(c));
}
public static boolean has3(int[] a) {
for(int i=0; i<a.length; ++i) {
if (a[i]==3)
return true;
}
return false;
}
}
标签:Java,返回语句
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
JAVA使用JDBC连接oracle数据库的详细过程
2021-11-20 19:20:19
![](https://img.aspxhome.com/file/2023/4/63414_0s.png)
Mybatis步骤分解实现一个增删改查程序
2021-09-16 01:12:43
![](https://img.aspxhome.com/file/2023/0/65730_0s.png)
详解Java类型擦除机制
2023-10-29 06:41:21
Java请求转发和请求重定向区别详解
2023-05-19 07:30:17
![](https://img.aspxhome.com/file/2023/6/63786_0s.webp)
SpringBoot如何获取Kafka的Topic列表
2023-11-26 16:01:52
![](https://img.aspxhome.com/file/2023/2/60242_0s.png)
Mybatis-Plus之ID自动增长的设置实现
2022-10-27 00:09:47
![](https://img.aspxhome.com/file/2023/7/65767_0s.png)
一文总结Java获取文件后缀名的所有方法
2022-10-18 16:06:40
浅谈Java内存区域划分和内存分配策略
2023-08-11 18:52:49
![](https://img.aspxhome.com/file/2023/6/58146_0s.png)
Spark JDBC操作MySQL方式详细讲解
2021-05-24 12:41:51
SpringCloudConfig之client端报错Could not resolve placeholder问题
2023-11-23 11:19:17
![](https://img.aspxhome.com/file/2023/5/59255_0s.png)
Java最简洁数据结构之冒泡排序快速理解
2023-12-01 06:31:52
![](https://img.aspxhome.com/file/2023/8/60278_0s.png)
Java实现指定线程执行顺序的三种方式示例
2021-08-16 15:11:34
![](https://img.aspxhome.com/file/2023/6/65626_0s.png)
Java Swing组件布局管理器之FlowLayout(流式布局)入门教程
2021-11-08 05:33:06
![](https://img.aspxhome.com/file/2023/1/61581_0s.gif)
Java如何实现字符串每隔4位加空格
2023-11-27 06:00:09
Spring Boot实现分布式系统中的服务发现和注册(最新推荐)
2022-07-10 03:50:23
Java并发之嵌套管程锁死详解
2023-01-13 10:55:01
Java BufferWriter写文件写不进去或缺失数据的解决
2023-07-20 14:57:02
maven的pom.xml中profiles的作用详解
2022-07-03 20:40:54
![](https://img.aspxhome.com/file/2023/9/64509_0s.png)
对Jpa中Entity关系映射中mappedBy的全面理解
2023-07-25 03:48:39
详解Spring ApplicationContext加载过程
2023-07-17 01:07:43