Question:

How do you limit limit the size of a string that someone can input in java?

by  |  earlier

0 LIKES UnLike

i have to validate a title but i have to limit the user entry to 6-100 characters. how would limit the string to these parameters

 Tags:

   Report

1 ANSWERS


  1. Check out this sample code to see how you can do this:

    import java.io.*;

    public class ReadCharacters

    {

    public static void main (String[] args)

    {

    // Get user input

    System.out.print("Enter your string (must be between 6-100 characters inclusive): ");

    //  Get the input stream reader

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    String inputString = "";

    int len = 0;

    // read in the lines

    do

    {

    inputString = getLine();

    len = inputString.length();

    if(len < 6 || len > 100)

    {

    System.out.print("\nSorry, you must input between 6-100 characters. Try again: ");

    }

    }

    while(len < 6 || len > 100);

    // Print the output line

    System.out.println("\nYour input was: " + inputString);

    }



    private static String getLine()

    {

    String input = "";

    try

    {

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    input = br.readLine();

    }

    //  Handle any exceptions

    catch (IOException ioe)

    {

    System.out.println("There was an I/O error.");

    System.exit(1);

    }

    return input;

    }

    }  // end of ReadCharacters class

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.