如何在单个语句中定义多个变量 [英] How to define multiple variables in single statement

查看:84
本文介绍了如何在单个语句中定义多个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我可以在一行中用数组定义两个变量。

In Python, I can define two variables with an array in one line.

>>>[a,b] = [1,2]
>>>a
1
>>>b
2

我如何在Java中做同样的事情?

How do I do the same thing in Java?

我有几个PCT类中的变量是最终类型。有没有一种方法可以像Python一样在一行中定义它们?以下格式显然不适用于Java。我可以分别定义它们,但是它将两次调用parseFile方法,这是我要避免的方法。

I have a couple of variables in class PCT which type is final. Is there a way to define them in one line in a Python like fashion? The following format clearly does not work in Java. I could define them separately, but it will call the parseFile method twice which I want to avoid.

public class PCT {
    final int start;
    final int stop;
    public PCT (File file) {
        //......
        //......
        // the following statement does not compile
        [start, stop] = parseFile(file);
    }
    public int[] parseFile(File f) {
        int[] aa = new int[2];
        // ....
        // ....
        return aa;
    }
}


推荐答案

此不可能,但您也不需要两次调用 parseFile

This is not possible, but you also don't need to call parseFile twice.

编写如下代码:

int [] temp = parseFile(file);
start = temp[0];
stop = temp[1];

Python(我相信)支持多个返回值。 Java遵守C约定,因此不允许这样做。由于这不是语言的一部分,因此语法也不是,这意味着如果您要进行多次返回,则需要使用诸如 temp 数组之类的粗暴骇客。

Python (I believe) supports multiple return values. Java obeys C conventions, and so doesn't permit it. Since that isn't part of the language, the syntax for it isn't either, meaning slightly gross hacks like the temp array are needed if you're doing multiple returns.

这篇关于如何在单个语句中定义多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆