title: Scanner: How do I limit the Scanner input after n characters?
body: <p>How do I limit the user's input <code>str = key.next();</code> after n characters? I'd like that <code>str</code> should only hold a specific amount of characters. I am very new to programming, and any help would be appreciated. </p>
  
  <pre><code>        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&lt;str.length()-k+1; i++){
  
              if (str.substring(i, i+k).compareTo(max)&gt;0){
                  max = str.substring(i, i+k);
              }
  
              else if (str.substring(i, i+k).compareTo(min)&lt;0){
                  min = str.substring(i, i+k);
              }
          }
  
          System.out.println(min + "\n" + max);
  </code></pre>