0

我一直在尝试正确执行此代码,但似乎缺少某些东西。程序需要接受一个字符串输入并检查它是否为空。如果不是,那么它应该检查是否有除字母之外的任何字符。如果是,它应该抛出错误并再次执行 while 循环以获取另一个输入。如果一切正常,它应该退出 while 循环并返回字符串。无法理解缺少什么。任何形式的帮助将不胜感激。

import java.util.Scanner;

public class Validator
{
    public static String getString(Scanner sc, String prompt)
{
    char temp;
    String s = "";
    boolean isValid = false;
      while (isValid == false)
    {
    System.out.print(prompt);
    s = "";
    s = sc.next();  // read user entry
    sc.nextLine();  // discard any other data entered on the line

    if (s == null || s.equals(""))
            System.out.println("Please enter a valid input");
    else
    {
        check:
    for (int i =0; i<s.length(); i++)
    {
         temp = s.charAt(i);
        if (!Character.isLetter(temp))
        {
            System.out.println("Invalid input. The name should consist of only alphabets");
            break check;
         }
        }
                }
                 isValid = true;
    }
      return s;
}

}

4

3 回答 3

0

你可以像这样简单地使用break

    if (!Character.isLetter(temp))
    {
        System.out.println("Invalid input. The name should consist of only alphabets");
        break;
     }

PS-什么是检查?

于 2013-11-08T07:26:59.260 回答
0

为避免无效输入,应使用gotoforcheck:continue语句。但continue更可取。

if (!Character.isLetter(temp)){
  System.out.println("Invalid input. The name should consist of only alphabets");
  continue;
}
于 2013-11-08T07:31:12.803 回答
0

修改您的代码,例如

包 com.practice.strings;

导入 java.util.Scanner;

公共类比较{

/**
 * @param args
 */
public static void main(String[] args) {
    getString();
    System.out.println("exit");
}

public static String getString() {
    Scanner sc = new Scanner(System.in);
    char temp;
    String s = "";
    boolean isValid = false;
    while (isValid == false)
    {
        s = "";
        s = sc.next();  // read user entry
        sc.nextLine();  // discard any other data entered on the line

        if (s == null || s.equals(""))
            System.out.println("Please enter a valid input");
        else
        {
            int i;
            for (i =0; i<s.length(); i++)
            {
                temp = s.charAt(i);
                if (!Character.isLetter(temp))
                {
                    System.out.println("Invalid input. The name should consist of only alphabets");
                    break ;
                }
            }
            if (i == s.length())
                isValid = true;
        }
    }
    return s;
}

}

于 2013-11-08T07:46:02.317 回答