我正在尝试创建一个用户输入短语的游戏,但这个短语只能是小写字母(如果你抓住了我的漂移)。因此程序将使用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)));
}
}
答案 0 :(得分: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 ]+"));
答案 1 :(得分: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;
}
}
}
}
}