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

無効な入力を避けるには、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 に答える