Convert Python syntax to Java

I need to convert this pythin code to java. Is there any online tools? Or can you please do it for me to understand better?

cases = int(input())
answer = []
for x in range(cases):
    cities = int(input())
    listOfCities = []
    for i in range(cities):
        listOfCities.append(input())
    setOfCities = set(listOfCities)
    answer.append(len(setOfCities))
for e in answer:
    print(e)```

I went through this line … to try to rewrite this in Java.

I used a Scanner object to do input.
I used a Java ArrayList for the Python list stuff.
And a Java HashSet for the Python set
I also used i++ instead of i+=1 or i = i + 1

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;

class CitiesStuff {
	public static void main (String[] args) { 

		Scanner inputter = new Scanner(System.in);
		int cases = inputter.nextInt();	
		ArrayList<Integer> answer = new ArrayList<Integer>(cases);
		for (int x=0; x < cases; x++) {
			int cities = inputter.nextInt();
			ArrayList<String> listOfCities = new ArrayList<String>(cities);
			for (int i=0; i < cities; i++) {
				String input = inputter.nextLine();
				listOfCities.add(input);
			}
			Set<String> setOfCities = new HashSet<String>(listOfCities);
			answer.add(setOfCities.size());
		
		}
		for (int e : answer) {
			System.out.println(e);
		}
	}
}

Hopefully there’s no mistakes in there.

1 Like