+ 1

How to convert this code from python3 to java

This code was a piece of cake for me with python. In java I was dasseled trying trying without any result. The code in PYthon3 is the following: ------------------------------------------------------------- fibonacci = [0, 1] n = input("Please type a number ") n = int(n) for x in range(n + 1): fibonacci.append(fibonacci[-2] + fibonacci[-1]) for x2 in range(len(fibonacci)): print(fibonacci[x2]) ------------------------------------------------------------- This programs create a fibonacci array and print each content of this array in a single line The code I was trying in java is the following: ------------------------------------------------------------- import java.util.Scanner; import jdk.nashorn.internal.objects.annotations.Where; public class Main { public static void main(String args[]) { System.out.print("java FibIter\n"); Scanner eingabe = new Scanner(System.in); System.out.println("Bitte geben Sie eine Nummer (n) ein"); int x = eingabe.nextInt(); int n0 = 0; int n1 = 1; int n2, i, j, n = x; System.out.print(n0 + " " + n1); for (i = 2; i < n; ++i) { n2 = n0 + n1; int[] myArray = new int[ where.size() ]; where.toArray( myArray ); n0 = n1; n1 = n2; } System.out.println(myArray); for (j = 0; j < myArray.length; ++j) { System.out.print(myArray[j]); } } } ------------------------------------------------------------- Please Help!

3rd May 2020, 11:47 PM
Mohammad Ala Tahhan
Mohammad Ala Tahhan - avatar
2 ответов
+ 3
About your python code: # You never used "m". # x2+=1 is useless # Your last loop could be written as: for x2 in fibonacci: print(x2) # You could have used only one loop # If you don't need to store them all in a list you could use only a list of length 2 and replace the old 2 values with the new ones in each loop iteration to improve performance and saving memory.
4th May 2020, 1:04 AM
Kevin ★
+ 2
I don't know what that "Where" is used for. In Java you should use a class like ArrayList for dinamic length. https://www.sololearn.com/learn/Java/2179/?ref=app The logic would be almost the same.
4th May 2020, 12:40 AM
Kevin ★