如何使用If语句使Scanner仅接受按字母顺序排列的字符

时间:2013-03-27 18:22:46

标签: string java.util.scanner alphabetical

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

1 个答案:

答案 0 :(得分: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)有很多方法可以检查&#34; isAlpha()&#34;。我会看一下&#34;正则表达式&#34;:

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

3)这里有一个天真的&#34;实现:

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;
}