Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

In Java, write a program that prompts the user to enter four cities and displays them in ascending order. Here is my code but it

In Java, write a program that prompts the user to enter four cities and
displays them in ascending order.
Here is my code but it keeps coming out wrong:
package chapter4ex3;
import java.util.Scanner;
public class Chapter4Ex3{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the first city: ");
String c1= input.nextLine();
System.out.print("Enter the second city: ");
String c2= input.nextLine();
System.out.print("Enter the third city: ");
String c3= input.nextLine();
System.out.print("Enter the fourth city: ");
String c4= input.nextLine();
String firstC = c1;
if (c2.compareTo(firstC)<0){
firstC = c2;
}
if (c3.compareTo(firstC)<0){
firstC = c3;
}
if (c4.compareTo(firstC)<0){
firstC = c4;
}
String thirdC = c1;
if (c2.compareTo(thirdC)>0){
thirdC = c2;
}
if (c3.compareTo(thirdC)>0){
thirdC = c3;
}
if (c4.compareTo(thirdC)>0){
}
String secondC ="";
if (!c1.equals(firstC) && !c1.equals(thirdC)){
secondC = c1;
}
if (!c2.equals(firstC) && !c2.equals(thirdC)){
secondC = c2;
}
if (!c3.equals(firstC) && !c3.equals(thirdC)){
secondC = c3;
}
if (!c4.equals(firstC) && !c4.equals(thirdC)){
secondC = c4;
}
String fourthC ="";
if (c2.compareTo(fourthC)<0){
firstC = c2;
}
if (c3.compareTo(fourthC)<0){
firstC = c3;
}
if (c4.compareTo(fourthC)<0){
firstC = c4;
}
System.out.println("The three cities in alphabetical order are "+ firstC +""+ secondC +""+ thirdC +""+ fourthC);
}
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Concepts

Authors: David M. Kroenke, David J. Auer

7th edition

133544621, 133544626, 0-13-354462-1, 978-0133544626

Students also viewed these Databases questions

Question

How could you estimate the cost of workplace bullying?

Answered: 1 week ago