如何限制用户可以输入的字符数量?

时间:2016-05-12 22:36:59

标签: java

对于我下面的程序,我想要它,以便用户必须输入2个或更多字符的单词,但我不知道如何进行限制。

这是一个回文程序,它用于测试这个词是否是回文。它允许我输入任何长度的单词,但我想限制为2或更多,如果他们只输入一个单词,则消息应显示“错误的单词”。

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);
    } 
}

2 个答案:

答案 0 :(得分:3)

你可以循环读取输入, 如果输入太短,则输出错误, 获得有效输入时会中断,例如:

    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");
    }

答案 1 :(得分:0)

 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");