java 在一个方法中使用多个 return 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12500830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:09:40  来源:igfitidea点击:

Using multiple return statements in a method

javasetreturnpojo

提问by ArthurP

import javax.swing.JOptionPane;

public class Speler
{

    public String naam;
    public String aantalKeerGespeeld;
    public String behaaldePunten;
    public String spelersInfo;


    public String setNaam(){
        return naam = JOptionPane.showInputDialog("Hoe heet je?");
    }

    public String setAantalKeerGespeeld(){
        return aantalKeerGespeeld = JOptionPane.showInputDialog("Hoe vaak heb je gespeeld?");
    }

    public String setBehaaldePunten(){
        return behaaldePunten = JOptionPane.showInputDialog("Hoe veel punten heb je behaald?");
    }

    public String setSpelersInfo(){
        **return naam = JOptionPane.showInputDialog("Hoe heet je?");
        return aantalKeerGespeeld = JOptionPane.showInputDialog("Hoe vaak heb je gespeeld?");
        return behaaldePunten = JOptionPane.showInputDialog("Hoe veel punten heb je behaald?");**


    }
    public String getNaam(){
        return naam;
    }

    public String getAantalKeerGespeeld(){
        return aantalKeerGespeeld;
    }

    public String getBehaaldePunten(){
        return behaaldePunten;
    }

    public String getSpelersinfo(){
        return naam;
        return aantalKeerGespeeld;
        return behaaldePunten;
    }
}    

Looks like I can't return or set more than 1 value. Just began learning Java, and it's hard to find the answer anywhere.

看起来我不能返回或设置超过 1 个值。刚开始学习Java,很难在任何地方找到答案。

回答by Code-Apprentice

After looking more closely at your code, I would like to clear up what appear to be a few misunderstandings. First of all, from what I can see, you don't need to return multiple values from any of your methods. In fact, a method name that starts with the word "set" shouldn't return anything at all. On the other hand, it needs to take a parameter in order to "set" the value of a variable. For example

在更仔细地查看您的代码后,我想澄清一些似乎存在的误解。首先,据我所知,您不需要从任何方法返回多个值。事实上,以单词“set”开头的方法名称根本不应该返回任何内容。另一方面,它需要一个参数来“设置”一个变量的值。例如

public void setNaam(String newNaam){
    naam = newNaam;
}

Note that I don't use a JOptionPane dialog to get the name. At this point in the code, we don't care where the value came from. Some other method is responsible for actually getting the value from the user. This method simply stores the value for later use.

请注意,我不使用 JOptionPane 对话框来获取名称。在代码的这一点上,我们不关心值从哪里来。其他一些方法负责从用户那里实际获取价值。此方法只是存储值供以后使用。

Also, note that you have a field declared as

另外,请注意,您有一个字段声明为

String spelersInfo;

I believe the getSpelersInfo()and setSpelersInfo()should use this, which is why I claim that you don't need to return multiple values from either of these methods.

我相信getSpelersInfo()并且setSpelersInfo()应该使用它,这就是为什么我声称您不需要从这些方法中的任何一个返回多个值。

Finally, it appears that you are creating what we call a POJO. See this link for more details about what the acronym means.

最后,您似乎正在创建我们所说的POJO。有关首字母缩略词含义的更多详细信息,请参阅此链接。

回答by Yarneo

The basics of a returnstatement is that it causes the program to leave the current function(subroutine) and resume from where the function was called, which is the return address.
When you enter a function the return address is saved on the call stack so its easily reachable.

return语句的基本原理是它使程序离开当前函数(子程序)并从调用函数的地方恢复,也就是返回地址。
当您输入一个函数时,返回地址会保存在调用堆栈中,因此可以轻松访问。

So as for your code, when you issue a returnstatement and then another one, the latter will not be called.
If I'm not mistaken, it will not be even compiled on most compilers.
Hence what you need to do is issue a return statement that returns all the String's together.
That can be done with many basic Data Structuresthat are available in the Java standard library and if you don't want to get involved in that, you could even append the strings into one big string and then split it after.

所以对于你的代码,当你发出一个return语句然后另一个语句时,后者不会被调用。
如果我没记错的话,它甚至不会在大多数编译器上编译。
因此,您需要做的是发出一个 return 语句,将所有字符串一起返回。
这可以通过Java 标准库中提供的许多基本数据结构来完成,如果您不想参与其中,您甚至可以将字符串附加到一个大字符串中,然后将其拆分。

But for now what I would suggest is to read a basic Java book/tutorialor even a basic book about programming languages.
Goodluck!

但就目前而言,我建议阅读一本基本的 Java 书籍/教程,甚至是一本关于编程语言的基本书籍。
祝你好运!

Link to some basic Java Data structures

链接到一些基本的 Java 数据结构

Edit
As Code-Guru pointed out and is correct, the best way to approach this issue is with a POJO, you can see a nice explanation in his answer.

编辑
正如 Code-Guru 指出的并且是正确的,解决这个问题的最佳方法是使用POJO,您可以在他的回答中看到一个很好的解释。

Though reading a book and understanding the fundamentals in my opinion beats all of the technical solutions at this point

虽然在我看来阅读一本书并理解基础知识在这一点上胜过所有的技术解决方案

回答by Ben Richards

No, you can't return more than one value in that way.

不,您不能以这种方式返回多个值。

The way the returnkeyword works is that it will immediately return control back to the calling code, using the returned value as the value of the function. The first return call it sees will exit the function itself, so any subsequent code will never be executed.

的方式return关键字的工作原理是,它会立即返回控制权返回给调用代码,使用返回的值作为函数的值。它看到的第一个返回调用将退出函数本身,因此将永远不会执行任何后续代码。

Generally, you shouldn't have to ever need to return multiple values from a function in that manner. However, if you want to return a list of values, you can pack them into a Container object (such as an object of java.util.Vector) and return the vector object. However, it doesn't appear that is necessary in any of your code that you listed.

通常,您不必以这种方式从函数返回多个值。但是,如果要返回值列表,则可以将它们打包到一个 Container 对象(例如 的对象java.util.Vector)中,并返回向量对象。但是,在您列出的任何代码中似乎都不需要。

In the code you posted, however, it seems like instead of returning values from the function, you want to have your instance variables of your class be set by the JOptionPaneprompts. Then you just have a single returnstatement at the end of the function once all those assignments complete. Note that if your function is declared as void(that is, it doesn't return a value), you don't need to have a return;line at the end, as once it reaches the end of the method, it will exit. Sometimes having return;is useful (such as if you have multiple return points) but that is a topic for study at another time.

但是,在您发布的代码中,您似乎希望通过JOptionPane提示设置类的实例变量,而不是从函数中返回值。然后return,一旦所有这些赋值完成,您在函数末尾只有一个语句。请注意,如果您的函数被声明为void(即它不返回值),则您不需要return;在末尾有一行,因为一旦到达方法的末尾,它将退出。有时拥有return;是有用的(例如,如果您有多个返回点),但这是另一个时间的研究主题。

回答by ddyer

Many modern languages have the elegant capability to return multiple values, but java does not. As a practical matter, you have to choose something else. The 100% acceptable solution from the viewpoint of everything but efficiency is to return a new object of a new class designed to hold the set of return values. ie;

许多现代语言具有返回多个值的优雅能力,但 java 没有。实际上,您必须选择其他东西。从除效率之外的所有方面来看,100% 可接受的解决方案是返回一个新类的新对象,该对象旨在保存返回值集。IE;

class TwoStrings { String name; String addres; ... }

类 TwoStrings { 字符串名称;字符串地址;... }

and in your code return(new TwoStrings("foo","bar"));

并在您的代码中 return(new TwoStrings("foo","bar"));

Another fully acceptable choice is to refactor your interface so it is natural to return the values one at a time. If you wanted "getXandY(), refactor it as getX() and getY()

另一个完全可以接受的选择是重构您的界面,以便一次返回一个值是很自然的。如果您想要“getXandY(),请将其重构为 getX() 和 getY()

A frequent choice is to make the container for return values one of the parameters of the callee. Instead of returning "name" and "address", supply a "person" to the function which it will load with name and address (and presumably return an indicator of success).

一个常见的选择是将返回值的容器作为被调用者的参数之一。不是返回“姓名”和“地址”,而是向函数提供一个“人”,该函数将加载姓名和地址(并可能返回成功的指示符)。

Less acceptable ways are to use non-specfic arrays or vectors to return multiple values

不太可接受的方法是使用非特定数组或向量来返回多个值

Least acceptable is to return one value, and stash the other values for use by the caller "return by side effect"

最不可接受的是返回一个值,并隐藏其他值以供调用者“副作用返回”使用

回答by AAT

Yes you are correct, You cannot have more than one return statement in a method. How about returning an POJO back to the caller method and get the value there?

是的,你是对的,一个方法中不能有多个 return 语句。将 POJO 返回给调用者方法并在那里获取值如何?