File tree Expand file tree Collapse file tree 2 files changed +45
-0
lines changed
Expand file tree Collapse file tree 2 files changed +45
-0
lines changed Original file line number Diff line number Diff line change @@ -36,6 +36,14 @@ public static void main(String[] args) {
3636 }
3737 } else {
3838 System .out .println ("'" + cmd + "' is not recognized as an internal or external command." );
39+ // Suggest closest command
40+ List <String > validCommands = new ArrayList <>(commands .keySet ());
41+ String suggestion = StringUtils .findClosest (cmd , validCommands );
42+ if (suggestion != null && !suggestion .equals (cmd )) {
43+ System .out .println ("'" + cmd + "' is not recognized as an internal or external command. Did you mean '" + suggestion + "'?" );
44+ } else {
45+ System .out .println ("'" + cmd + "' is not recognized as an internal or external command." );
46+ }
3947 }
4048 }
4149 }
Original file line number Diff line number Diff line change 1+ package com .mycmd ;
2+
3+ import java .util .List ;
4+
5+ public class StringUtils {
6+ // Compute Levenshtein distance between two strings
7+ public static int levenshtein (String a , String b ) {
8+ int [] costs = new int [b .length () + 1 ];
9+ for (int j = 0 ; j < costs .length ; j ++) {
10+ costs [j ] = j ;
11+ }
12+ for (int i = 1 ; i <= a .length (); i ++) {
13+ costs [0 ] = i ;
14+ int nw = i - 1 ;
15+ for (int j = 1 ; j <= b .length (); j ++) {
16+ int cj = Math .min (1 + Math .min (costs [j ], costs [j - 1 ]), a .charAt (i - 1 ) == b .charAt (j - 1 ) ? nw : nw + 1 );
17+ nw = costs [j ];
18+ costs [j ] = cj ;
19+ }
20+ }
21+ return costs [b .length ()];
22+ }
23+
24+ // Find the closest string from a list
25+ public static String findClosest (String input , List <String > candidates ) {
26+ String closest = null ;
27+ int minDist = Integer .MAX_VALUE ;
28+ for (String candidate : candidates ) {
29+ int dist = levenshtein (input , candidate );
30+ if (dist < minDist ) {
31+ minDist = dist ;
32+ closest = candidate ;
33+ }
34+ }
35+ return closest ;
36+ }
37+ }
You can’t perform that action at this time.
0 commit comments