0

我是 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.");
            }                       
        }       
    }
}   
4

1 回答 1

0

1)您可能想稍微改变一下逻辑:

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()) {
      String sLine = in.next ();
      if (sLine.equals ("Sort")) {
        System.out.println("The names in alphabetical order are: " + names);
        doSort ();
      }
      if (sLine.equals ("Sort")) {
        System.out.println("This Program has stopped.");
        doExit ();
      }
      if (!isAlpha (sLine)) {
         System.out.println("Please enter only alphabetical characters.");
         continue;
      }
      names.add(sLine);
    }
  }
}

2) 有很多方法可以检查“isAlpha()”。我会看“正则表达式”:

http://www.vogella.com/articles/JavaRegularExpressions/article.html

3)这是一个“天真的”实现:

boolean isAlpha (String s)
{
  String s2 = s.toUpperCase();

  for (int i = 0; i < s2.length(); i ++) {
    if (s2.charAt(i) < 'A' || s2.charAt(i) > 'Z')
      return false;
  }
  return true;
}
于 2013-03-27T18:30:33.790 回答