这就是我所做的。我需要在我的代码中进行更正。无法理解为什么这不起作用。
public class NewClass2 {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.println("Enter name of first city: ");
String s1 = obj.next();
char x = s1.charAt(0);
System.out.println("Enter name of second city: ");
String s2 = obj.next();
char y = s1.charAt(0);
System.out.println("Enter name of third city: ");
String s3 = obj.next();
char z = s1.charAt(0);
if (x<y && y<z)
System.out.println("The three cities in alphabetical order are " + s1 + " "+ s2 + " " + s3);
else if (y<x && x<z)
System.out.println("The three cities in alphabetical order are " + s2+ " " + s1 + " " + s3);
else if(z<x && x<y)
System.out.println("The three cities in alphabetical order are " + s3 + " " + s1 + " " + s2);
else if (y<z && z<x)
System.out.println("The three cities in alphabetical order are " + s2 + " " + s3 + " " + s1);
else if (x<z && z<y)
System.out.println("The three cities in alphabetical order are " + s1 + " " + s3 + " " + s2);
else
System.out.println("The three cities in alphabetical order are " + s3 + " " + s2 + " " + s1);
}
}
希望得到所需的解决方案。
答案 0 :(得分:0)
您始终将第一个输入与自身进行比较!
char y = s1.charAt(0);
应该是
char y = s2.charAt(0);
和
char z = s1.charAt(0);
应该是
char z = s3.charAt(0);
使用调试器可以帮助您理解这些问题。
答案 1 :(得分:0)
我建议使用Java的in-build方法为您完成排序工作。 您可以简单地将这些字符串添加到列表中并调用Collections.sort函数。
以下是它的工作代码:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class TestClass {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Scanner obj = new Scanner(System.in);
System.out.println("Enter name of first city: ");
String s1 = obj.next();
list.add(s1);
System.out.println("Enter name of second city: ");
String s2 = obj.next();
list.add(s2);
System.out.println("Enter name of third city: ");
String s3 = obj.next();
list.add(s3);
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
System.out.println("The three cities in alphabetical order are - " + list);
}
}