我是 Java 编程的初学者,我正在编写一个按字母顺序对名称进行排序的程序。如何编写“ if
”语句,使其只接受字母字符?在我的代码中,我有“ if (in.hasNext() != String)
”,这显然是错误的,但我现在只是在尝试任何事情。这是我的代码。
import java.util.*;
public class AlphaOrder
{
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<String>();
System.out.println("Enter a name, enter \"Sort\" to sort the names alphabetically, enter \"Quit\" to end: ");
Scanner in = new Scanner(System.in);
while (in.hasNext())
{
names.add(in.next());
if (in.hasNext("Sort"))
{
System.out.println("The names in alphabetical order are: " + names);
}
if (in.hasNext("Quit"))
{
System.out.println("This Program has stopped.");
}
if (in.hasNext() != String)
{
System.out.println("Please enter only alphabetical characters.");
}
}
}
}