60.0k views
5 votes
Write a Java program that Asks the user for the names of 3 cities, separated by spaces.It is assumed that a given city name won't have spaces in it.

User IanNorton
by
7.9k points

1 Answer

7 votes

Final answer:

To write a Java program that asks the user for the names of 3 cities, separated by spaces, you can use the Scanner class in Java to take input from the user.

Step-by-step explanation:

To write a Java program that asks the user for the names of 3 cities, separated by spaces, you can use the Scanner class in Java to take input from the user. Here is an example program:

import java.util.Scanner;

public class CityNames {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the names of 3 cities separated by spaces:");
String cities = input.nextLine();
String[] cityNames = cities.split(" ");

for (String city : cityNames) {
System.out.println(city);
}
}
}

In this program, the Scanner class is used to read a line of input from the user. The user is prompted to enter the names of 3 cities, which are then stored in a String variable. The split() method is then used to split the input into an array of city names, which are printed one by one using a for-each loop.

User Ahmad Habib
by
7.9k points