我正在尝试创建一个用户输入短语的游戏,但该短语只能是小写字母(如果您明白我的意思)。所以程序会用 do-while 循环提示用户。如果用户输入类似 (1234567890, or !@#$%^&* or 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)));
}
}
最佳答案
使用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 ]+"));
关于java - 为返回的字符串值设置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17582800/