1

我正在尝试创建一个用户输入短语的游戏,但该短语只能是小写字母(如果你明白我的意思)。所以程序会用一个do-while循环提示用户。如果用户输入类似 (1234567890, 或 !@#$%^&* 或 ASDFGH, 循环应该重新提示用户只输入小写字母。我对 java 非常陌生, 所以我的代码将真的很糟糕。这里是:

import java.util.Scanner;
public class Program05 
{
    public static void main(String[] args) 
    {
    Scanner scanner01 = new Scanner(System.in);
    String inputPhrase; 
    char inputChar;
        do {
            System.out.print("Enter a common phrase to begin!: ");
            inputPhrase = scanner01.nextLine(); 

        } while (!inputPhrase.equals(Character.digit(0,9)));
    }
}
4

2 回答 2

6

使用String.matches()适当的正则表达式来测试它是否都是小写字母:

inputPhrase.matches("[a-z ]+") // consists only of characters a-z and spaces

所以你的循环看起来像:

do {
    System.out.print("Enter a common phrase to begin!: ");
    inputPhrase = scanner01.nextLine(); 
} while (!inputPhrase.matches("[a-z ]+"));
于 2013-07-10T23:55:59.207 回答
0

试试这个,我编译了这个,效果很好

public static void main(String[] args) 
{
 Scanner scanner01 = new Scanner(System.in);
 String inputPhrase = ""; 
 char inputChar;
    while(!inputPhrase.equals("exit")){
        System.out.print("Enter a common phrase to begin!: ");
        inputPhrase = scanner01.nextLine(); 
        for(int i = 0; i < inputPhrase.length(); i++){
            if(!Character.isLetter(inputPhrase.charAt(i))
            ||Character.isUpperCase(inputPhrase.charAt(i))){
                System.out.println("Input must be lowercase characters");
                break; 
            }
        }
    }
 }
}
于 2013-07-11T00:03:55.587 回答