简体   繁体   中英

Scanner: How do I limit the Scanner input after n characters?

How do I limit the user's input str = key.next(); after n characters? I'd like that str should only hold a specific amount of characters. I am very new to programming, and any help would be appreciated.

        String str;
        int k;
        int n =1000;
        String min="";
        String max="";

        Scanner key = new Scanner(System.in);
        str = key.next();
        k = key.nextInt();

        max = str.substring(0,k);
        min = str.substring(0,k);

        for (int i=0; i<str.length()-k+1; i++){

            if (str.substring(i, i+k).compareTo(max)>0){
                max = str.substring(i, i+k);
            }

            else if (str.substring(i, i+k).compareTo(min)<0){
                min = str.substring(i, i+k);
            }
        }

        System.out.println(min + "\n" + max);

Do not pass System.in directly, but pass a wrapper to System.in implementing InputStream . In this wrapper, you can easily limit the number of characters you return.

A simple fix for you is to get a substring of the returned input string that is at most n characters long:

if (str.length() > n) {
  str.substring(0, n+1);
}

Where n is the max length you want str to be. This code snippet would go after str = key.next();

Note that String.substring is inclusive for the beginning index but exclusive for the ending index.

I hope this helps.

You can pass a regular expression to the method next(String pattern) (or perhaps findInLine(String) ). For example:

str = key.next(".{10}");

will put the next 10 characters into str .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM