Source code:
Computeclass.java:
/** * @author Caiyong * @version 1.0 * * * * * * * * * * * Package pack;
Import Java.text.NumberFormat;
Import Java.util.Locale; public class Computeclass {* * * COMPUTE similarity */public static double Similardegree (string stra, String St
RB) {String Newstra = removesign (stra);
String NEWSTRB = removesign (STRB);
With a larger string length as the denominator, a similar substring is used as a molecule to compute the string similarity int temp = Math.max (Newstra.length (), newstrb.length ());
int temp2 = longestcommonsubstring (Newstra, NEWSTRB). Length ();
return TEMP2 * 1.0/TEMP; * * * To write all data for a string in one row */public static string Removesign (String str) {Stringbuf
Fer sb = new StringBuffer ();
Traversal string str, if a kanji number or letter, append to AB for (Char item:str.toCharArray ()) if (Charreg (item)) {
Sb.append (item);
return sb.tostring (); * * * To determine whether characters are Chinese characters, numbers and letters, * because the similarity of the symbols is notPractical significance, so the symbol does not add to the scope of consideration. * */public static Boolean Charreg (char charvalue) {return (charvalue >= 0x4e00 && Charvalue & lt;= 0x9fa5) | | (Charvalue >= ' a ' && charvalue <= ' z ') | | (Charvalue >= ' A ' && charvalue <= ' Z ') | |
(Charvalue >= ' 0 ' && charvalue <= ' 9 ');
* * To find common substring, using dynamic programming algorithm.
* It does not require that the character being evaluated is contiguous in the given string. * */public static string Longestcommonsubstring (string stra, String strb) {char[] Chars_stra = St
Ra.tochararray ();
char[] Chars_strb = Strb.tochararray ();
int m = chars_stra.length;
int n = chars_strb.length; * * Initialization matrix data, Matrix[0][0] value is 0, * If the character array Chars_stra and CHARS_STRB corresponding bit is the same, then Matrix[i][j] is the value of the upper left corner plus 1, * No
Then, the value of matrix[i][j] equals the larger value of the last two positions in the upper left, and the value of the remaining points in the matrix is 0.
* * int[][] matrix = new Int[m + 1][n + 1];
for (int i = 1; I <= m; i++) { for (int j = 1; J <= N; j +) {if (chars_stra[i-1] = chars_strb[j-1])
MATRIX[I][J] = matrix[i-1][j-1] + 1;
else matrix[i][j] = Math.max (Matrix[i][j-1], matrix[i-1][j]); }/* * Matrix, if the value of matrix[m][n] is not equal to the value of matrix[m-1][n] is not equal to matrix[m][n-1], * then Matrix[m][n
The corresponding character is a similar character element and is stored in the result array.
* */char[] result = new Char[matrix[m][n]];
int currentindex = result.length-1;
while (Matrix[m][n]!= 0) {if (matrix[n] = = matrix[n-1]) n--;
else if (matrix[m][n] = = Matrix[m-1][n]) m--;
else {Result[currentindex] = chars_stra[m-1];
currentindex--;
n--;
m--;
Return the new String (result);
}
* * * Result converted to percent */public static String Similarityresult (double resule) {return N
Umberformat.getpercentinstance (New Locale ("en", "US")). Format (resule); }
}
Simicalcu.java:
/** * @author Caiyong * @version 1.0 * * * * * * * * * * * Package pack;
Import Java.awt.BorderLayout;
Import java.awt.event.ActionEvent;
Import Java.awt.event.ActionListener;
Import Java.awt.event.KeyAdapter;
Import java.awt.event.KeyEvent;
Import Java.io.FileReader;
Import java.io.IOException;
Import Javax.swing.BorderFactory;
Import Javax.swing.Box;
Import Javax.swing.JButton;
Import Javax.swing.JFileChooser;
Import Javax.swing.JFrame;
Import Javax.swing.JLabel;
Import Javax.swing.JOptionPane;
Import Javax.swing.JScrollPane;
Import Javax.swing.JTextArea;
Import Javax.swing.filechooser.FileNameExtensionFilter;
Import Javax.swing.text.DefaultEditorKit; public class Simicalcu {public static void main (final java.lang.string[] args) {Java.awt.EventQueue.invoke
Later (new Java.lang.Runnable () {//AWT is single-threaded mode, all AWT components can only be accessed in the recommended event-handling thread, guaranteeing the correctness of the component state public void run () { Final JFrame frame = new JFrame ("String similarity calculation");/Declaration JFrame Final JLabEl tag = new JLabel ("Hint: Click the Select File Button" To select the file to compare or enter the file directly in the text box.)
")/Prompt label//file one final JButton load = new JButton (" Select file One: ");//Select File button Final JLabel filename = new JLabel ("");//file path final JTextArea textarea = new JTextArea (6, 20)//text box Textarea.setlinewrap (TRUE);//set to wrap Textarea.setwrapstyleword (true); Long line wrap at margin final jscrollpane scroller = new JScrollPane (textarea);//scroll bar effect//load file one of the Event Listener Load.addactionlistener (new ActionListener () {Private JFileChooser fil
Echooser = null;
Private Defaulteditorkit Kit = new Defaulteditorkit ();
public void actionperformed (ActionEvent e) {if (Filechooser = null) { Set default file selection path to desktop path Filechooser = newJFileChooser (System.getproperty ("User.home")); //filter file type, allow TXT file and Doc document Filechooser.setfilefilter to open (new
Filenameextensionfilter ("Text file", "TXT", "text", "Doc", "Docs"));
if (Filechooser.showopendialog (frame) = = Jfilechooser.approve_option) {//Show file path
Filename.settext (Filechooser.getselectedfile (). GetAbsolutePath ());
FileReader reader = null; Read the contents of the file to textarea & exception handling try {reader = n
EW FileReader (Filechooser.getselectedfile ());
Textarea.settext ("");
Kit.read (reader,textarea.getdocument (), 0);
catch (Exception Xe) { System.err.println (Xe.getmessage ()); finally {if (reader!= null) {try
{Reader.close ();
catch (IOException IoE) {System.err.println (Ioe.getmessage ());
}
}
}
Textarea.setcaretposition (0);//Mouse Focus}
Return
}
});
Document Two final JButton load2 = new JButton ("Choose File Two:");
Final JLabel filename2 = new JLabel (""); Final JTextArea textarea2 = new JTextArea (6, 20);
Textarea2.setlinewrap (TRUE);
Textarea2.setwrapstyleword (TRUE);
Final JScrollPane scroller2 = new JScrollPane (TEXTAREA2); Event Listener loading file two Load2.addactionlistener (new ActionListener () {Private Jfilech
Ooser filechooser2 = null;
Private Defaulteditorkit kit2 = new Defaulteditorkit ();
public void actionperformed (ActionEvent e) {if (Filechooser2 = null) {
Filechooser2 = new JFileChooser (System.getproperty ("User.home")); } filechooser2.setfilefilter (New Filenameextensionfilter ("Text file", "TXT", "text", "Doc", "D
OCS ")); if (Filechooser2.showopendialog (frame) = = jfilechooser.approve_option) {filename2.SetText (Filechooser2.getselectedfile (). GetAbsolutePath ());
FileReader reader2 = null;
try {reader2 = new FileReader (Filechooser2.getselectedfile ());
Textarea2.settext ("");
Kit2.read (reader2,textarea2.getdocument (), 0);
catch (Exception Xe2) {System.err.println (Xe2.getmessage ());
finally {if (Reader2!= null) {
try {reader2.close (); The catch (IOException ioe2) {System.err.println ioe2.getmessage (
));
} }} textarea2.setcaretposit
Ion (0);
} return;
}
});
TEXTAREA final JTextArea textarea_res = new JTextArea (6, 20) showing similar content;
Textarea_res.setlinewrap (TRUE);
Textarea_res.setwrapstyleword (TRUE);
Final JScrollPane scroller_res = new JScrollPane (textarea_res);
Set Textarea_res transparent Textarea_res.setopaque (false);
Scroller_res.setopaque (FALSE);
Scroller_res.getviewport (). Setopaque (false);
TextArea and TEXTAREA2 content change events, delete file paths and similar content Textarea.addkeylistener (new Keyadapter () {
public void keypressed (KeyEvent e) { Filename.settext ("");
Textarea_res.settext ("");
}
});
Textarea2.addkeylistener (New Keyadapter () {public void keypressed (KeyEvent e) {
Filename2.settext ("");
Textarea_res.settext ("");
}
});
Calculation, Exit button final JButton start = new JButton ("Start calculation"); Start Computing Similarity event Start.addactionlistener (new ActionListener () {public void Actionperfo
Rmed (ActionEvent e) {String Temp_stra = Textarea.gettext ();
String TEMP_STRB = Textarea2.gettext ();
String STRA,STRB; If two textarea are not empty and are not all symbols, the similarity calculation, otherwise prompts the user to enter data or select the file if (!) ( Computeclass.removesign (Temp_stra). Length ()= = 0 && computeclass.removesign (TEMP_STRB). Length () = 0)) {if (Temp_stra.length () >=
Temp_strb.length ()) {stra = Temp_stra;
STRB = TEMP_STRB;
}else{stra = TEMP_STRB;
STRB = Temp_stra;
Double result = Computeclass.similardegree (Stra, STRB); Displays similar content in Textarea_res textarea_res.settext ("Similar content is:" +computeclass.longestcommonsubstring (Stra,
STRB)); Results joptionpane.showmessagedialog (NULL, "similarity is:" + computeclass.similarityresult (Result), "
Computational results ", joptionpane.plain_message); }else{Joptionpane.showmessagedialog (null, "Hello, please enter the correct content.") "," hint ", joptionpane.error_message);
}
}
});
Final JButton cancle = new JButton ("Exit"); Exit Event Cancle.addactionlistener (new ActionListener () {public void Actionperforme
D (ActionEvent e) {frame.dispose ()//release of the resource occupied by the form system.exit (0);/exit Program
}
});
General layout//Document One North final Box north = Box.createverticalbox ();//Vertical arrangement
North.setborder (Borderfactory.createemptyborder (5,5,5,5));//margin North.add (tag);
North.add (Box.createverticalstrut (10));
North.add (load);
North.add (Box.createverticalstrut (5));
North.add (filename);
North.add (scroller); FRame.add (North,borderlayout.north);
File Two Center final Box center = box.createverticalbox ();
Center.setborder (Borderfactory.createemptyborder (5,5,5,5));
Center.add (LOAD2);
Center.add (Box.createverticalstrut (5));
Center.add (filename2);
Center.add (SCROLLER2);
Center.add (Scroller_res);
Frame.add (Center,borderlayout.center);
South Final Box south = Box.createhorizontalbox ();
South.setborder (Borderfactory.createemptyborder (5,5,5,5));
South.add (Box.createhorizontalglue ());//button Center display south.add (start);
South.add (Box.createhorizontalstrut (20));//Horizontal Spacing South.add (cancle);
South.add (Box.createverticalstrut (5)); Frame.add (South,borderlayout.south);
Frame.pack ();
Frame.setdefaultcloseoperation (jframe.exit_on_close);//form default exit form Frame.setlocationrelativeto (NULL);
Frame.setvisible (TRUE);
}
}); }
}
Run result chart: