4

ユーザーが文字列のみを入力する必要があり、整数とシンボルが入力に含まれていない場合、整数をキャッチする方法は? 私の初歩的なレポートを手伝ってください。

import java.util.*;
public class NameOfStudent {


    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        String name = "";

        System.out.print("Please enter your name: ");
        name = input.nextLine(); // How to express error if the Strin contains
                                //integer or Symbol?...

        name = name.toLowerCase();

        switch(name)
        {
        case "cj": System.out.print("Hi CJ!");
        break;
        case "maria": System.out.print("Hi Maria!");
        break;
        }

    }

}
4

9 に答える 9

3

この正規表現を使用します。

文字列に数字/記号などが含まれているかどうかを確認します.

boolean result = false;  
Pattern pattern = Pattern.compile("^[a-zA-Z]+$");  
Matcher matcher = pattern.matcher("fgdfgfGHGHKJ68"); // Your String should come here
if(matcher.find())  
    result = true;// There is only Alphabets in your input string
else{  
    result = false;// your string Contains some number/special char etc..
}

カスタム例外のスロー

Javaでカスタム例外をスローする

トライキャッチの働き

try{
    if(!matcher.find()){ // If string contains any number/symbols etc...
        throw new Exception("Not a perfect String");
    }
        //This will not be executed if exception occurs
    System.out.println("This will not be executed if exception occurs");

}catch(Exception e){
    System.out.println(e.toString());
}

try-catch の仕組みの概要を説明しました。ただし、一般的な「例外」は使用しないでください。独自の例外には、常にカスタマイズした例外を使用してください。

于 2013-09-10T06:37:17.907 に答える
1

Regex検索パターンを形成する一連の文字である which を使用します。

Pattern pattern = Pattern.compile("^[a-zA-Z]*$");
Matcher matcher = pattern.matcher("ABCD");
System.out.println("Input String matches regex - "+matcher.find());

説明:

^         start of string
A-Z       Anything from 'A' to 'Z', meaning A, B, C, ... Z
a-z       Anything from 'a' to 'z', meaning a, b, c, ... z
*         matches zero or more occurrences of the character in a row
$         end of string

空の文字列も確認する場合は、* を + に置き換えます


それなしでやりたい場合regex

public boolean isAlpha(String name) 
{
    char[] chars = name.toCharArray();

    for (char c : chars) 
    {
         if(!Character.isLetter(c)) 
         {
                return false;
         }
    }

    return true;
}
于 2013-09-10T06:39:28.553 に答える
1

名前などの文字列を手にしたら、次のように正規表現を適用できます。

    String name = "your string";
    if(name .matches(".*\\d.*")){
        System.out.println("'"+name +"' contains digit");
    } else{
        System.out.println("'"+name +"' does not contain a digit");
    }

必要に応じてロジック チェックを調整します。

于 2013-09-10T06:44:52.050 に答える
1

文字列には数字を含めることができますが、それでも文字列であることに注意してください。

String str = "123";

あなたの質問であなたが意味したのは、「数字や記号を使わずにアルファベット順のユーザー入力を強制する方法」であると思います。これは、正規表現を使用して簡単に実行できます

Pattern pattern = Pattern.compile("^[a-zA-Z]+$"); // will not match empty string
Matcher matcher = pattern.matcher(str);
bool isAlphabetOnly = matcher.find();
于 2013-09-10T06:47:12.190 に答える
0

Java では、String に何を含めることができるかを正規表現で定式化します。次に、文字列に許可されたシーケンスが含まれているかどうか、および許可されたシーケンスのみが含まれているかどうかを確認します。

コードは次のようになります。do-while-loop を追加しました。

    Scanner input = new Scanner(System.in);
    String name = "";

    do { // get input and check for correctness. If not correct, retry
        System.out.print("Please enter your name: ");
        name = input.nextLine(); // How to express error if the String contains
                                //integer or Symbol?...

        name = name.toLowerCase();
    } while(!name.matches("^[a-z][a-z ]*[a-z]?$"));
    // The above regexp allows only non-empty a-z and space, e.g. "anna maria"
    // It does not allow extra chars at beginning or end and must begin and end with a-z

    switch(name)
    {
    case "cj": System.out.print("Hi CJ!");
    break;
    case "maria": System.out.print("Hi Maria!");
    break;
    }

正規表現を変更して、たとえばアジア文字セットを使用した名前を許可できるようになりました。定義済みの文字セットを処理する方法については、こちらをご覧ください。私はかつて、任意の言語 (および UTF-8 文字セットの任意の部分) の単語のテキストをチェックしていましたが、テキスト内の単語を見つけるために次のような正規表現になりました。"(\\p{L}|\\p{M})+"

于 2013-09-10T07:27:48.093 に答える
-1

うーん..値を配列に格納してみてください..単一の値ごとに、 isLetter() と isDigit() を使用します..次に、その配列で新しい文字列を作成します

ここで try catch を使用して確認してください。私はパターンクラスに慣れていません。それがより単純な場合はそれを使用してください

于 2013-09-10T07:14:46.593 に答える