For loop - like Python range function

后端 未结 9 1577
情歌与酒
情歌与酒 2020-12-30 21:45

I was wondering if in Java there is a function like the python range function.

range(4)

and it would return

[0,1,2,3]
         


        
9条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 22:27

    What you can do to substitute the range in python in java can be done with the following code. NOTE: I am not going off of your code, I am just writing a small piece of code and showing it to you.

    in python you would do.. . .

    if -2 <= x <= 10:
         print(x) 
    

    in java you would substitute this range and do. . ..

    if(x >= -2 && x <= 10){
    System.out.println("x")
    }
    

    By doing the above code in java, you don't need a range, but you have the -2 <= x <=10 range and split it into x >= -2 and x <= 10. It means the same thing, but the one I explained in java may take the compiler a longer time to read. So if you are using python go with the former's code format, and if you are using java, use the latter's code format.

提交回复
热议问题