【问题标题】:Why does it say that my return statement is "unreachable" [closed]为什么它说我的退货声明“无法访问”[关闭]
【发布时间】:2021-09-01 15:44:53
【问题描述】:

我正在为一个学校项目开发一个非常简单的 minecraft 插件,但我似乎无法让这个 return false; 被“访问”

我使用的是 Eclipse IDE,这是我的代码

package com.genuishour.me;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public class Events implements CommandExecutor{
    
    private Main plugin;
    
    public Events(Main plugin) {
        this.plugin = plugin;
        
    plugin.getCommand("hello").setExecutor(this);
        
    }
    
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage("Only players can execute this command!");
            return true;
            
            
        }
        
        Player p = (Player) sender;
        
        String name = sender.getName();
        
        if (p.hasPermission("hello.use")) {
            p.sendMessage("Hello " + name + "!");
            return true;
            } else {
                p.sendMessage("You do not have permission to execute this command");
                return true;
            }
        
        return false; //unreachable code
    }       
    

}

【问题讨论】:

  • 当 p 具有“hello.use”权限时,您希望何时返回,如果没有,则返回。哪种情况会同时跳过 if 和 else?由于您的return false 在那里不起作用,您需要为它找到一个更好的地方,并且有一个。当你想到它时,你就会发现它。
  • 因为它是。 if (p.hasPermission("hello.use")) 的两个分支都首先返回。如果你缩进你的代码,你可能会看得更清楚。

标签: java return unreachable-code


【解决方案1】:

你有一个“悬空的 else”——这两个是等价的:

if (p.hasPermission("hello.use")) {
    p.sendMessage("Hello " + name + "!");
    return true;
} else {
    p.sendMessage("You do not have permission to execute this command");
    return true;
}
   
return false; //unreachable code

if (p.hasPermission("hello.use")) {
    p.sendMessage("Hello " + name + "!");
    return true;
}
p.sendMessage("You do not have permission to execute this command");
return true;
   
return false; //unreachable code

这应该清楚为什么最后一个无法访问

【讨论】:

    【解决方案2】:

    根据您缩进代码的方式,我猜您希望最后一个 return false 成为函数中的最后一个语句。但现在它在 (p.hasPermission("hello.use")) {

    总结一下:将它向下移动一行,它位于函数的末尾。

    【讨论】:

    • 最后的return已经函数的最后一条语句了。
    【解决方案3】:

    因为这里:

    if (p.hasPermission("hello.use")) {
                p.sendMessage("Hello " + name + "!");
                return true;
                } else {
                    p.sendMessage("You do not have permission to execute this command");
                    return true;
                }
    

    不管p.hasPermission("hello.use")的结果是什么,你总是会通过返回true来退出代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 2015-04-28
      • 2017-04-06
      • 2020-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多