Java 如何对必须包含3个或更多字符的字符串值进行编码?

Java 如何对必须包含3个或更多字符的字符串值进行编码?,java,Java,我试图找出如何限制字符串中使用的字符数量,但是,我似乎无法找到如何编码,例如,如果我说“He”而不是“Hello”,我希望我的代码显示错误,因为“He”包含的字符少于3个。有什么建议吗 package trial; import java.util.Scanner; public class Trial { public static void main(String[] args) { Scanner input = new Scanner(System.i

我试图找出如何限制字符串中使用的字符数量,但是,我似乎无法找到如何编码,例如,如果我说“He”而不是“Hello”,我希望我的代码显示错误,因为“He”包含的字符少于3个。有什么建议吗

package trial;


import java.util.Scanner;

public class Trial {


    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);


            System.out.println("Enter a word: ");
                String word = input.nextLine();

                System.out.println("The Word you have typed is: " + word);

如果只允许字母数字字符,则可以使用带有\w的正则表达式,如:

regex的另一个想法可能是:

[\w\s]{3,} --> alphanumeric and spaces with 3 or more
您可以检查字符串长度是否小于3

if(word.length() < 3)
{
    System.err.println("Error");
}

您的代码很好,只需让用户不断输入值,直到字符数超过3个,这样您就可以通过while循环来检查word的字符数

package trial;


import java.util.Scanner;

public class Trial {


public static void main(String[] args) {

      Scanner input = new Scanner(System.in);

            String word="";
            while(word.length()<3){     

                System.out.println("Enter a word with more or equals to 3 characters: ");

                 word = input.nextLine();
            }  
                    System.out.println("The Word you have typed is: " + word);

使用Stringsplit和Stringlength.String.length…谢谢你的帮助:String.length单词非常感谢,非常感谢。谢谢,我将其添加到我的代码中,效果非常好:谁否决了正确的答案?大声说反对票对任何人都没有任何好处,除非你说为什么……这是个意外,对不起!哦,我明白了。使用此选项,输入单词。。。。将一直重复,直到用户键入超过3个字符。谢谢你的额外投入。
package trial;


import java.util.Scanner;

public class Trial {


public static void main(String[] args) {

      Scanner input = new Scanner(System.in);

            String word="";
            while(word.length()<3){     

                System.out.println("Enter a word with more or equals to 3 characters: ");

                 word = input.nextLine();
            }  
                    System.out.println("The Word you have typed is: " + word);