How to define multiple variables in single statement

前端 未结 6 682
青春惊慌失措
青春惊慌失措 2021-01-18 07:14

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

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

How do I do the

相关标签:
6条回答
  • 2021-01-18 07:46

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

    Write your code like this:

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

    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.

    0 讨论(0)
  • 2021-01-18 07:47

    Maybe

    public class PCT 
    {
        final Point pos;  // two ints!
    
        public PCT (File file) 
        {
            pos = parseFile(file);
        }
    
        public int[] parseFile(File f) 
        {
            Point aa = new Point();
            // ....
            // ....
            return aa;
        }
    }
    
    0 讨论(0)
  • 2021-01-18 07:49

    When declaring several variables of the same type, you can do the following:

    int a = 1, b = 2, c = 3; //etc.
    
    0 讨论(0)
  • 2021-01-18 07:51

    Maybe this is what you're looking for:

    int array[] = {1,2};
    

    Java array assignment (multiple values)

    If you're looking to explicitly assign to each element, I don't think you can do that within one assignment, as a similar concept with the 2-d example below. Which seems like what you want as Jeremy's answers specifies.

    Explicitly assigning values to a 2D Array?

    0 讨论(0)
  • 2021-01-18 08:00

    If you literaly mean line; as long as you place a semicolon in between two statements, they are executed as if there is a new line in between so you can call:

    a = 1; b = 2;
    

    You can even compress an entire file into a oneliner, by removing comment (that scope to the end of the line). Spacing (space, tab, new line,...) is in general removed from the Java files (in memory) as first step in the Java compiler.

    But you are probably more interested in a singe statement. Sytax like [start, stop] = parseFile(file); is not supported (at least not for now). You can make a onliner:

    int[] data = parseFile(file); start = data[0]; stop = data[1];
    
    0 讨论(0)
  • 2021-01-18 08:02

    You can define multiple variables like this :

    double a,b,c;
    

    Each variable in one line can also be assigned to specific value too:

    double a=3, b=5.2, c=3.5/3.5;
    

    One more aspect is, while you are preparing common type variable in same line then from right assigned variables you can assign variable on left, for instance :

    int a = 4, b = a+1, c=b*b;
    

    Noticed, you can also practice arithmetic operations on variable by remaining in the same line.

    0 讨论(0)
提交回复
热议问题