gpt4 book ai didi

java - 如何使用 String.equals 和 String.compareTo 按字母顺序对用户输入的字符串名称进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 10:43:34 25 4
gpt4 key购买 nike

该程序的输出应该是:

Enter first : Alexis
Enter Second : Zach
Enter Third : Cassie

Here are sorted the sorted name:

Alexis

Cassie

Zach

但如果名称相同,则必须输出一条错误消息,说明名称相同。

示例输入姓名 1 亚历克西斯输入姓名 2 亚历克西斯输入姓名 3 凯蒂

名称一和名称二相同。

import java.util.Scanner;
import java.util.Arrays;


public class AlexisPriceAssignment6
{
public static String input = " ";
public static String input2 = " ";
public static String input3 = "";


public static void Greet()
{
System.out.println("Welcome to Alexis Price's Name Sorter.");
System.out.println("All names must be unique.");

}
public static void Uinput()
{
Scanner keyboard = new Scanner(System.in);

System.out.print("Enter the first name: ");
input = keyboard.nextLine();
char one = input.charAt(0);

System.out.print("Enter the second name: ");
input2 = keyboard.nextLine();
char two = input2.charAt(0);

System.out.print("Enter the third name: " );
input3 = keyboard.nextLine();
char three = input3.charAt(0);

System.out.println();
if (input.equals(input2) )
{
System.out.println(input + " is the same as "+ input2);
}
if ( input.equals(input3))
{
System.out.println(input + " is the same as "+ input3);
}
if (input2.equals(input3))
{
System.out.println(input2 + " is the same as "+ input3);
}
if (input!=(input2))
{
sort();
}


}

public static void sort()
{
System.out.println("Here are the sorted names.");

char charArray [] = input.toCharArray();
Arrays.sort(charArray);
String sortedString = new String(charArray);
System.out.println(sortedString);


}


public static void main(String[] args)
{
Greet();
Uinput();


}

}

最佳答案

检查:

    if (input!=(input2))
{
sort();
}

都是错误的,因为 String 使用 .equals() 方法进行比较,并且没有用,因为您已经通过直接比较每对来检查所有三个组合。只需在 3 个 if 语句之后调用 sort() 方法即可。

关于java - 如何使用 String.equals 和 String.compareTo 按字母顺序对用户输入的字符串名称进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48672134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com