[英]How to restrict amount of characters a user can enter?
For my program below, I want it so that the user must enter a word 2 or more characters long, but I do not know how to make that restriction. 对于下面的程序,我希望它使用户必须输入2个或更多字符的单词,但是我不知道如何进行限制。
This is a palindrome program, and it is used to test whether the word is a palindrome or not. 这是一个回文程序,用于测试单词是否为回文。 It lets me enter a word of any length but I want to restrict to 2 or more, and if they enter only a one character word, a message should display "Wrong word". 它可以让我输入任意长度的单词,但我想限制为2个或更多,如果他们只输入一个字符的单词,则消息应显示“ Wrong word”。
import java.util.*;
class PalindromeTesterSamJiang1 {
public static void main(String [] arg) {
int x=0;
Scanner in=new Scanner(System.in);
System.out.printf("Menu: Please select an option \n"
+ "1)Palindrome Tester\n"
+ "0)Exit program \n");
x=in.nextInt();
switch (x){
case 1:
lol test=new lol();
test.palindromeTester("");
test.displayInfo();
break;
default:
System.out.println("Goodbye");
break;
}
}
}
class lol {
String original, reverse = "";
public String palindromeTester(String reference) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a word to Test: ");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
return original;
}
public void displayInfo() {
if (original.equals(reverse))
System.out.println("RESULT: A PALINDROME");
else
System.out.println("RESULT: NOT A PALINDROME");
String[] arguments = new String[] {"123"};
PalindromeTesterSamJiang1.main(arguments);
}
}
You can read the input in a loop, print an error if the input is too short, break out when you get a valid input, for example: 您可以循环读取输入,如果输入太短则显示错误,并在获得有效输入时中断,例如:
while (true) {
System.out.println("Enter a word to Test: ");
original = in.nextLine();
if (original.length() > 2) {
break;
}
System.out.println("Too short. Word must be at least 2 characters");
}
System.out.println("Enter a word to Test: ");
original = in.nextLine();
String[] array = original.split(" ");
if(array.length < 2)
System.out.print("Enter atleast 2 sentence");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.