I develop a Java program to format Java codes

Discussion in 'Java' started by gearss8888@gmail.com, Mar 2, 2012.

  1. Guest

    The program can format Java codes, the codes formatted will have correct indent spaces.

    //----------
    /*
    Modified: 2012-3-1
    it can format java codes so as to get the correct indent spaces.


    */
    import java.io.IOException;//ÒýÈëÀà
    import java.io.*;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.InputStreamReader;
    import java.io.StringReader;
    import java.io.StringWriter;
    import java.io.FileInputStream;
    import java.io.FileReader;
    import java.io.InputStream;
    import java.io.Reader;
    import java.util.ArrayList;
    import javax.swing.JOptionPane;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Graphics;
    import java.awt.Color;
    import javax.swing.JFileChooser;
    import javax.swing.SwingConstants;
    import javax.swing.UIManager;

    public class Tidy extends JFrame {
    JButton SelectFilebtn, OKbtn;
    JTextField FileNameField;
    String TabBlank = " "; // ÿһ´ÎtabµÄ¿Õ¸ñ´óС£¬ÕâÀïΪĬÈϵÄËĸö¿Õ¸ñ
    int HowManyTab = 0;
    boolean HaveUnCleanRow = false; // ¼Ç¼ÓÐûÓбàд²»¹æÕûµÄ³ÌÐò´úÂ룬Èç¹ûÓе¯³ö¶Ô»°¿òÇëÓû§¸ÄÕýÔٹرտØÖÆ̨£¬Èç¹ûûÓУ¬²»ÏÔʾ¶Ô»°¿ò¡£
    boolean ForWhileIfBlock = false; // ±êÖ¾ÕâÒ»ÐÐÊÇ·ñfor, while or if ¿ªÍ·µ«È´Ã»ÓÐ{}·ûºÅ£¬Õâ˵Ã÷Õâ¸ö¿éÖ»ÓÐÒ»ÐС£
    public Tidy () {
    this.setTitle( "ÎļþÕûÀíÆ÷");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.anchor = GridBagConstraints.WEST; //É趨LayoutµÄλÖÃ
    gbc.insets = new Insets(2,2,2,2); //É趨Óë±ß½çµÄ¾àÀë(ÉÏ,×ó,ÏÂ,ÓÒ)
    SelectFilebtn = new JButton("Ñ¡ÔñÎļþ");
    SelectFilebtn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    do_SelectFilebtn_actionPerformed(e);
    }
    });
    FileNameField = new JTextField("",40);
    gbc.gridy=1;
    gbc.gridx=0;
    this.add(SelectFilebtn, gbc);
    gbc.gridx=1;
    this.add(FileNameField, gbc);
    //--------------
    OKbtn = new JButton("OK");
    OKbtn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    String FileName = FileNameField.getText();
    do_OKbtn_actionPerformed(e, FileName);
    }
    });
    gbc.gridy=2;
    gbc.gridx=0;
    this.add(OKbtn, gbc);
    //---------------------
    this.pack();
    this.setVisible(true);
    }

    protected void do_SelectFilebtn_actionPerformed (ActionEvent e) {
    JFileChooser chooser = new JFileChooser();// ´´½¨ÎļþÑ¡ÔñÆ÷
    int option = chooser.showOpenDialog(this);// ÏÔʾÎļþ´ò¿ª¶Ô»°¿ò
    if (option == JFileChooser.APPROVE_OPTION) {// ÅжÏÓû§ÊÇ·ñÑ¡¶¨Îļþ
    File file = chooser.getSelectedFile();// »ñÈ¡Óû§Ñ¡ÔñÎļþ
    FileNameField.setText(file.getAbsolutePath());// °ÑÑ¡ÔñµÄÎļþ·¾¶ÏÔʾÔÚÎı¾¿òÖÐ
    }
    }

    protected void do_OKbtn_actionPerformed(ActionEvent e, String ThisFile){
    if (!ThisFile.equals("")) {
    HowManyTab = 0;
    ReadAndCombFile(ThisFile); // ÎļþÃû²»ÄÜΪ¿Õ
    }
    }
    // ¸ù¾Ý{ºÍ}µÄ¸öÊý¾ö¶¨Ã¿Ò»ÐÐÇ°ÃæÐèÒªÌí¼Ó¶àÉÙ¸ötab¿Õ¸ñ
    String FileInManyLines (String oneline, int CombRow, String Suffix) {
    String PreffixStr; // ÕâÊÇÿһÐпªÊ¼µÄ¿Õ¸ñ£¬ËüÊÇÓÃÀ´·½±ãÔĶÁµÄ
    String TrimIt = oneline.trim();
    String newoneline = "";
    int Diff = 0;
    // Java³ÌÐò
    if (Suffix.equals(".java")) {
    int Conutleft = strFind(TrimIt, "{", 0);
    int ConutRight = strFind(TrimIt, "}", 0);
    Diff = Conutleft - ConutRight;
    // Èç¹ûÇ°ÃæÒ»ÐÐÖ»ÓÐÒ»¸öfor, while or ifµ«Ã»ÓÐ{}£¬ËùÒÔÏÂÃæÒ»ÐоÍËõ½øÁË
    if ((Conutleft == 0) && (ConutRight == 0) && ForWhileIfBlock)
    Diff = 50;
    // for, while or if ¿ªÍ·£¬µ«ÊÇȴûÓÐʹÓÃ{}£¬ËµÃ÷Õâ¸ö¿éÖ»ÓÐÒ»ÐС£
    if ((Conutleft == 0) && (ConutRight == 0) && ((TrimIt.startsWith("for")) || (TrimIt.startsWith("while")) || (TrimIt.startsWith("if")) || (TrimIt.startsWith("else")) || (TrimIt.startsWith("else if")))) {
    ForWhileIfBlock = true;
    Diff= 100;
    }
    switch (Diff) {
    case 1 : {
    PreffixStr = ManyTabStr (HowManyTab, TabBlank);
    HowManyTab = HowManyTab + 1;
    newoneline = PreffixStr + TrimIt; // °Ñǰ׺¿Õ¸ñÌí¼Óµ½ÕâÒ»ÐÐÇ°Ãæ
    break;
    }
    case -1 : {
    HowManyTab = HowManyTab - 1;
    PreffixStr = ManyTabStr (HowManyTab, TabBlank);
    newoneline = PreffixStr + TrimIt; // °Ñǰ׺¿Õ¸ñÌí¼Óµ½ÕâÒ»ÐÐÇ°Ãæ
    break;
    }
    case 0 : {
    PreffixStr = ManyTabStr (HowManyTab, TabBlank);
    newoneline = PreffixStr + TrimIt; // °Ñǰ׺¿Õ¸ñÌí¼Óµ½ÕâÒ»ÐÐÇ°Ãæ
    break;
    }
    case 50 :{
    PreffixStr = ManyTabStr (HowManyTab, TabBlank);
    newoneline = PreffixStr + TrimIt; // °Ñǰ׺¿Õ¸ñÌí¼Óµ½ÕâÒ»ÐÐÇ°Ãæ
    HowManyTab = HowManyTab - 1;
    ForWhileIfBlock = false;
    break;
    }
    case 100 : {
    PreffixStr = ManyTabStr (HowManyTab, TabBlank);
    newoneline = PreffixStr + TrimIt; // °Ñǰ׺¿Õ¸ñÌí¼Óµ½ÕâÒ»ÐÐÇ°Ãæ
    HowManyTab = HowManyTab + 1;
    break;
    }
    default: {
    PreffixStr = ManyTabStr (HowManyTab, TabBlank);
    newoneline = PreffixStr + TrimIt; // °Ñǰ׺¿Õ¸ñÌí¼Óµ½ÕâÒ»ÐÐÇ°Ãæ
    System.out.println("µÚ"+CombRow+"ÐÐ"+"±àд²»¹æÕû£¬Çë¸ÄÕý!");
    HaveUnCleanRow = true; // ³ÌÐò×îºóµ¯³ö¶Ô»°¿òÌáÐÑÓû§Õâ¸ö³ÌÐòÓбàд²»¹æÕûµÄ´úÂë¡£
    }
    }
    } else if (Suffix.equals(".f90") || Suffix.equals(".f95")) { // Fortran³ÌÐò
    String LowCaseTrimIt = TrimIt.toLowerCase();
    if (LowCaseTrimIt.startsWith("program") || LowCaseTrimIt.startsWith("module") || LowCaseTrimIt.startsWith("subroutine") || ((strFind(LowCaseTrimIt, "function", 0) == 1)) || LowCaseTrimIt.startsWith("do ") || (LowCaseTrimIt.startsWith("if") && (LowCaseTrimIt.endsWith("then"))) || LowCaseTrimIt.startsWith("select") || LowCaseTrimIt.startsWith("case")) {
    Diff = 1;
    }
    else if (LowCaseTrimIt.startsWith("end ") || LowCaseTrimIt.startsWith("enddo") || LowCaseTrimIt.startsWith("endif")) {
    Diff = 2;
    }
    else if (LowCaseTrimIt.startsWith("else")) {
    Diff = 3;
    }
    else
    {Diff = 100;}
    switch (Diff) {
    case 1 : {
    PreffixStr = ManyTabStr (HowManyTab, TabBlank);
    HowManyTab = HowManyTab + 1;
    newoneline = PreffixStr + TrimIt; // °Ñǰ׺¿Õ¸ñÌí¼Óµ½ÕâÒ»ÐÐÇ°Ãæ
    break;
    }
    case 2 : {
    HowManyTab = HowManyTab - 1;
    PreffixStr = ManyTabStr (HowManyTab, TabBlank);
    newoneline = PreffixStr + TrimIt; // °Ñǰ׺¿Õ¸ñÌí¼Óµ½ÕâÒ»ÐÐÇ°Ãæ
    break;
    }
    case 3 : {
    HowManyTab = HowManyTab - 1;
    PreffixStr = ManyTabStr (HowManyTab, TabBlank);
    newoneline = PreffixStr + TrimIt; // °Ñǰ׺¿Õ¸ñÌí¼Óµ½ÕâÒ»ÐÐÇ°Ãæ
    HowManyTab = HowManyTab + 1;
    break;
    }
    case 100 : {
    PreffixStr = ManyTabStr (HowManyTab, TabBlank);
    newoneline = PreffixStr + TrimIt; // °Ñǰ׺¿Õ¸ñÌí¼Óµ½ÕâÒ»ÐÐÇ°Ãæ
    break;
    }
    }
    } else {// ÆäËû¸ñʽµÄÎļþ
    newoneline = oneline;
    }
    return newoneline;
    }
    // Éú³ÉÒ»¸ön¸ötab¿Õ¸ñµÄ¿Õ°××Ö·û´®
    String ManyTabStr (int howmany, String TabBlank) {
    String Str = "";
    for (int i = 0; i < howmany; i++)
    Str = Str + TabBlank;
    return Str;
    }
    // ·½·¨strFindÓÃÓÚʵÏÖ×Ö·û´®²éÕÒ£¬·µ»ØÆ¥ÅäµÄ´ÎÊý
    public int strFind(String s1, String s2, int pos) {
    // ±äÁ¿iºÍj·Ö±ð±íʾÖ÷´®ºÍģʽ´®Öе±Ç°×Ö·û´®µÄλÖã¬k±íʾƥÅä´ÎÊý
    int i, j, k = 0;
    // pos´ú±íÖ÷´®ÖпªÊ¼±È½ÏµÄλÖÃ
    // i=pos;
    i = 0;// Èç¹û°Ñi=pos¸Ä³É´Ë¾ä½«²»´ÓÊó±êλÖÿªÊ¼ÕÒ£¬¶øÊÇÖ±½Ó´Ó×Ö·û´®Í·¿ªÊ¼ÕÒ£¬i¾ö¶¨×Å¿ªÈç²éÕÒµÄλÖÃ
    j = 0;
    while (i < s1.length() && j < s2.length()) {
    if (s1.charAt(i) == s2.charAt(j)) {
    ++i;
    ++j;
    if (j == s2.length()) {
    // j=s2.length()±íʾ×Ö·û´®Æ¥Åä³É¹¦£¬Æ¥Åä³É¹¦´ÎÊý¼Ó1
    k = k + 1;
    // ½«Ö¸Ê¾Ö÷´®ºÍģʽÖе±Ç°×Ö·ûµÄ±äÁ¿iºÍj½øÐлØÍË
    i = i - j + 1;
    j = 0;
    }
    else {
    i = i - j + 1;
    j = 0;
    }
    }
    i++;
    }
    return k;// ΪʲôÕâ¸öwhileÑ­»·Ã»ÓÐÒ»¸öÑ­»·¿ØÖÆÆ÷ÄØ£¬ÎÒ»¹Ã»ÓÐÀí½âËüµÄ½á¹¹£¿
    }

    //ÒÔÐÐΪµ¥Î»¶ÁÈ¡Îļþ
    String[] readFileByLines (String fileName){
    File file = new File(fileName);
    ArrayList<String> alllinks = new ArrayList<String>();
    BufferedReader reader = null;//´´½¨»º´æ¶ÁÈ¡
    try {
    reader = new BufferedReader(new FileReader(file));//½«Îļþ·ÅÔÚ»º´æ¶ÁÈ¡ÖÐ
    String tempString = null;
    //Ò»´Î¶ÁÈëÒ»ÐУ¬Ö±µ½¶ÁÈënullΪÎļþ½áÊø
    while ((tempString = reader.readLine()) != null){
    alllinks.add(tempString);
    }
    reader.close();
    } catch (IOException e) {//²¶»ñÒì³£
    e.printStackTrace();
    } finally {//ÄÚÈÝ×ÜÖ´ÐÐ
    if (reader != null) {
    try {
    reader.close();//¹Ø±Õ»º´æ¶ÁÈ¡
    } catch (IOException e1) {
    }
    }
    }
    String[] links = new String[alllinks.size()];
    for (int count = 0; count < alllinks.size(); count++) {links[count] = alllinks.get(count);}
    return links;
    }

    // °Ñ×Ö·û´®Êý×éдÈëÎļþ, ¼´°´ÐÐдÈëÎļþ
    public boolean stringArrayToFile(String[] arrayres, String filePath) {
    boolean flag = true;
    BufferedReader bufferedReader = null;
    BufferedWriter bufferedWriter = null;
    StringBuffer temp = new StringBuffer();
    for (String one : arrayres) {
    temp.append(one);
    temp.append("\n");
    }
    int x = temp.lastIndexOf("\n");
    temp.replace(x, temp.length(), "");
    String res = temp.toString();
    try {
    File distFile = new File(filePath); //´´½¨Îļþ
    if (!distFile.getParentFile().exists()) //Åжϸ¸Â·¾¶ÊÇÎļþ¼ÐÊÇ·ñ´æÔÚ
    distFile.getParentFile().mkdirs(); //¿ÉÒÔÔÚ²»´æÔÚµÄĿ¼Öд´½¨Îļþ¼Ð
    bufferedReader = new BufferedReader(
    new StringReader(res)); //½«Ô­×Ö·û´®¶ÁÈ뻺³å
    bufferedWriter = new BufferedWriter(
    new FileWriter(distFile)); //½«ÎļþдÈ뻺³å
    char buf[] = new char[1024]; // ×Ö·û»º³åÇø
    int len;
    while ((len = bufferedReader.read(buf)) != -1) { //whileÑ­»·
    bufferedWriter.write(buf, 0, len); //½«×Ö·û´®Ð´ÈëÎļþ
    }
    bufferedWriter.flush(); //Ë¢ÐÂдÈëÁ÷µÄ»º³å
    bufferedReader.close(); //¹Ø±Õ¶Á³öÁ÷
    bufferedWriter.close(); //¹Ø±ÕдÈëÁ÷
    } catch (IOException e) { //²¶»ñÒì³£
    e.printStackTrace();
    flag = false;
    return flag;
    } finally { //finally·½·¨×ܱ»Ö´ÐÐ
    if (bufferedReader != null) { //Åж϶Á³öÁ÷ÊÇ·ñΪ¿Õ
    try {
    bufferedReader.close(); //È·±£¶Á³öÁ÷¹Ø±Õ
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    return flag; //·µ»Ø²¼¶ûÀàÐÍ
    }

    void ReadAndCombFile (String filename) {
    String[] FileDivideToManyLines = readFileByLines (filename);
    // »ñÈ¡ÎļþµÄºó׺Ãû
    int FileSuffixLoc = filename.lastIndexOf(".");
    String FileSuffix = filename.substring(FileSuffixLoc, filename.length());
    ArrayList<String> FileCombed = new ArrayList <String> (); // ´¢´æ¼ÓÈëºÏÊÊÇ°Ãæ¿ÕÐеÄеÄÒ»ÐÐ×Ö·û
    int RowNumber = 1; // ¼Ç¼ÏÖÔÚ´¦ÀíµÚ¼¸ÐеĴúÂ룬ʹÓÃÕâ¸öÐÐÊýÌáÐÑ¿ª·¢ÕßÄÄÀï³ö´íÁË
    for (String oneline : FileDivideToManyLines) {
    String newLine = FileInManyLines (oneline, RowNumber, FileSuffix);
    FileCombed.add(newLine);
    RowNumber = RowNumber + 1;
    }
    String[] FileCombInStr = new String[FileCombed.size()];
    for (int count = 0; count < FileCombed.size(); count ++) {FileCombInStr [count] = FileCombed.get(count);}
    stringArrayToFile (FileCombInStr, filename);
    if (HaveUnCleanRow) {JOptionPane.showMessageDialog(null, "Óв»¹æÕûµÄ´úÂ룬Çë¸ÄÕý¡£");}
    }

    public static void main(String[] args) {
    Tidy TideFiles = new Tidy();
    }
    }
     
    , Mar 2, 2012
    #1
    1. Advertising

  2. Novice Guest

    wrote in
    news:5690138.193.1330687781011.JavaMail.geo-discussion-forums@ynca15:

    > The program can format Java codes, the codes formatted will have
    > correct indent spaces.
    >


    > //----------
    > /*
    > Modified: 2012-3-1
    > it can format java codes so as to get the correct indent spaces.
    >
    >
    > */
    > import java.io.IOException;//ÒýÈëÀà
    > import java.io.*;
    > import java.io.BufferedReader;


    [snip]

    Are you simply trying to tell us that you have written a program that
    formats Java source code so that we know? Or do you have a question of
    some kind?

    Also, are you aware that at least some popular IDEs already have built-in
    source code editors with user-adjustable formatting? For example, Eclipse
    has configurable editors so that you can tell it how many spaces you want
    to indent, whether you want to use Tabs or Spaces, whether you want line
    breaks before open braces or after close braces, etc. etc.

    That means I'd have no real interest in using your program since my IDE
    already does these things in a satisfactory way. I just mention this in
    case you were hoping a lot of people would use or even buy this code.

    --
    Novice
     
    Novice, Mar 2, 2012
    #2
    1. Advertising

  3. Lew Guest

    On 03/02/2012 03:29 AM, wrote:
    > The program can format Java codes, the codes formatted will have correct indent spaces.
    >
    > //----------
    > /*
    > Modified: 2012-3-1
    > it can format java codes so as to get the correct indent spaces.
    >
    >
    > */
    > import java.io.IOException;//引入类
    > import java.io.*;


    It is better to use single-type imports than import-on-demand. Certainly don't
    do both on the same types.

    > import java.io.BufferedReader;
    > import java.io.BufferedWriter;
    > import java.io.File;
    > import java.io.FileWriter;
    > import java.io.InputStreamReader;
    > import java.io.StringReader;
    > import java.io.StringWriter;
    > import java.io.FileInputStream;
    > import java.io.FileReader;
    > import java.io.InputStream;
    > import java.io.Reader;
    > import java.util.ArrayList;
    > import javax.swing.JOptionPane;
    > import java.awt.event.*;
    > import java.awt.*;
    > import javax.swing.*;
    > import java.awt.Graphics;


    Don't mix single-type imports and import-on-demand for the same types.

    > import java.awt.Color;
    > import javax.swing.JFileChooser;
    > import javax.swing.SwingConstants;
    > import javax.swing.UIManager;
    >
    > public class Tidy extends JFrame {
    > JButton SelectFilebtn, OKbtn;


    The Java naming convention is to use lower-case first letter in variable and
    method identifiers, and camel case thereafter. Thus, 'selectFileBtn', not
    'SelectFilebtn'.

    > JTextField FileNameField;
    > String TabBlank = " "; // æ¯ä¸€æ¬¡tab的空格大å°ï¼Œè¿™é‡Œä¸ºé»˜è®¤çš„四个空格


    Is there a tab in there? If so, you should use '\t' rather than an embedded TAB.

    > int HowManyTab = 0;


    There is no need to set the default value twice like this, except there's
    really no harm, either. In this case you could argue that the redundant
    initialization helps document your intent.

    > boolean HaveUnCleanRow = false; // 记录有没有编写ä¸è§„整的程åºä»£ç ï¼Œå¦‚果有弹出对è¯æ¡†è¯·ç”¨æˆ·æ”¹æ­£å†å…³é—­æŽ§åˆ¶å°ï¼Œå¦‚果没有,ä¸æ˜¾ç¤ºå¯¹è¯æ¡†ã€‚
    > boolean ForWhileIfBlock = false; // 标志这一行是å¦for, while or if 开头但å´æ²¡æœ‰{}符å·ï¼Œè¿™è¯´æ˜Žè¿™ä¸ªå—åªæœ‰ä¸€è¡Œã€‚
    > public Tidy () {


    Your constructor is a bit unwieldy - too long and complicated. I suggest that
    you refactor the fancy logic into a separate private method.

    > this.setTitle( "文件整ç†å™¨");
    > setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    > this.setLayout(new GridBagLayout());
    > GridBagConstraints gbc = new GridBagConstraints();
    > gbc.anchor = GridBagConstraints.WEST; //设定Layoutçš„ä½ç½®
    > gbc.insets = new Insets(2,2,2,2); //设定与边界的è·ç¦»(上,å·¦,下,å³)
    > SelectFilebtn = new JButton("选择文件");
    > SelectFilebtn.addActionListener(new ActionListener() {
    > public void actionPerformed(ActionEvent e) {
    > do_SelectFilebtn_actionPerformed(e);
    > }
    > });
    > FileNameField = new JTextField("",40);
    > gbc.gridy=1;
    > gbc.gridx=0;
    > this.add(SelectFilebtn, gbc);
    > gbc.gridx=1;
    > this.add(FileNameField, gbc);
    > //--------------
    > OKbtn = new JButton("OK");
    > OKbtn.addActionListener(new ActionListener() {
    > public void actionPerformed(ActionEvent e) {
    > String FileName = FileNameField.getText();
    > do_OKbtn_actionPerformed(e, FileName);
    > }
    > });
    > gbc.gridy=2;
    > gbc.gridx=0;
    > this.add(OKbtn, gbc);
    > //---------------------
    > this.pack();
    > this.setVisible(true);
    > }


    I strongly recommend that the 'setVisible()' call happen after the constructor.

    >
    > protected void do_SelectFilebtn_actionPerformed (ActionEvent e) {


    Why is this method 'protected'?

    > JFileChooser chooser = new JFileChooser();// 创建文件选择器
    > int option = chooser.showOpenDialog(this);// 显示文件打开对è¯æ¡†
    > if (option == JFileChooser.APPROVE_OPTION) {// 判断用户是å¦é€‰å®šæ–‡ä»¶
    > File file = chooser.getSelectedFile();// 获å–用户选择文件
    > FileNameField.setText(file.getAbsolutePath());// 把选择的文件路径显示在文本框中
    > }
    > }
    >
    > protected void do_OKbtn_actionPerformed(ActionEvent e, String ThisFile) {


    Why is this method 'protected'?

    Naming convention: 'thisFile', not 'ThisFile'.

    > if (!ThisFile.equals("")) {


    You forgot to check for the parameter being 'null'. This could cause a
    'NullPointerException'. Tsk, tsk.

    > HowManyTab = 0;
    > ReadAndCombFile(ThisFile); // 文件åä¸èƒ½ä¸ºç©º
    > }
    > }
    > // æ ¹æ®{å’Œ}的个数决定æ¯ä¸€è¡Œå‰é¢éœ€è¦æ·»åŠ å¤šå°‘个tab空格
    > String FileInManyLines (String oneline, int CombRow, String Suffix) {


    Why is this method package-private?

    Naming convention. 'fileInManyLines()'. 'combRow'. 'suffix'.

    > String PreffixStr; // 这是æ¯ä¸€è¡Œå¼€å§‹çš„空格,它是用æ¥æ–¹ä¾¿é˜…读的


    There's only one "f" in "prefix". Don't put the type of the variable in the
    name ("Str")!

    > ... [snip] ...
    > public static void main(String[] args) {
    > Tidy TideFiles = new Tidy();
    > }
    > }


    Start GUIs on the Event Dispatch Thread (EDT)!

    Do file operations *off* the EDT!

    I suggest reading the Swing tutorial and other references about Swing
    programming. Also, study the Java coding conventions, around since 1999. Your
    code is not thread-safe. Heck, it's not any kind of safe - you leave room for
    runtime exceptions, you don't comment the strange parts of your logic (like
    your switch on 'Diff' [sic] and the magic values it assumes). Your
    pretty-print source is indented incorrectly - how good can your pretty-printer
    be if you don't indent correctly in the first place? You don't control the
    scope of your variables well ('i' and 'j' in 'strFind()', 'flag' and
    'bufferedWriter' in 'stringArrayToFile()'), you don't declare constant those
    that should be constants ('TabBlank' [sic]), and you redundantly initialize
    variables ('BufferedReader reader = null;', 'int HowManyTab = 0;', etc.). You
    declare methods as 'protected' or package-private willy-nilly without
    explanation for the choices.

    I will venture to guess that you wrote this as an exercise and though you
    didn't explicitly say so, posted it here for critique. There are so many Java
    pretty-printers out there already. Use one on your own code, why don't you?

    Your code needs good formatting, proper naming, corrected access control,
    controlled scope, controlled heritability, and the bugs eliminated.

    --
    Lew
    Honi soit qui mal y pense.
    http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg
     
    Lew, Mar 2, 2012
    #3
  4. Roedy Green Guest

    On Fri, 2 Mar 2012 03:29:41 -0800 (PST), wrote,
    quoted or indirectly quoted someone who said :

    > PreffixStr =3D ManyTabStr (HowManyTab, TabBlank);
    > HowManyTab =3D HowManyTab + 1;
    > newoneline =3D PreffixStr + TrimIt; // =B0=D1=C7=B0=D7=
    >=BA=BF=D5=B8=F1=CC=ED=BC=D3=B5=BD=D5=E2=D2=BB=D0=D0=C7=B0=C3=E6
    > break;
    > }
    > case -1 : {


    the process of posting on a newsreader is scrambling your code. Try
    posting it somewhere and giving the URL.

    see http://mindprod.com/jgloss/sscce.html
    --
    Roedy Green Canadian Mind Products
    http://mindprod.com
    One of the most useful comments you can put in a program is
    "If you change this, remember to change ?XXX? too".
     
    Roedy Green, Mar 2, 2012
    #4
  5. Lew Guest

    Roedy Green wrote:
    > wrote, quoted or indirectly quoted someone who said :
    >
    >> PreffixStr =3D ManyTabStr (HowManyTab, TabBlank);
    >> HowManyTab =3D HowManyTab + 1;
    >> newoneline =3D PreffixStr + TrimIt; // =B0=D1=C7=B0=D7=
    >> =BA=BF=D5=B8=F1=CC=ED=BC=D3=B5=BD=D5=E2=D2=BB=D0=D0=C7=B0=C3=E6
    >> break;
    >> }
    >> case -1 : {

    >
    > the process of posting on a newsreader is scrambling your code. Try
    > posting it somewhere and giving the URL.
    >
    > see http://mindprod.com/jgloss/sscce.html


    He *gave* us an SSCCE, already!

    It wasn't scrambled here. Perhaps it's something specific to your newsreader.
    It clearly wasn't scrambled by "the process of posting on a newsreader" or
    everyone would've seen the problem.

    His code even survived my newsreader placing it into the reply as "quoted
    text", without loss of formatting or other issues. Does the quoted code look
    scrambled in my reply? That would be a good data point.

    I do note however that your reply is scrambled, in the sense that it didn't
    transcribe the Chinese characters. I infer that your newsreader used the wrong
    text encoding. You should fix that.

    I recommend against the OP's posting the code on a separate URL. It's easier
    to get answers when the respondents have everything they need in one place. I
    was grateful that they included their SSCCE in their post.

    --
    Lew
    Honi soit qui mal y pense.
    http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg
     
    Lew, Mar 2, 2012
    #5
  6. Lars Enderin Guest

    2012-03-02 19:04, Roedy Green skrev:
    > On Fri, 2 Mar 2012 03:29:41 -0800 (PST), wrote,
    > quoted or indirectly quoted someone who said :
    >
    >> PreffixStr =3D ManyTabStr (HowManyTab, TabBlank);
    >> HowManyTab =3D HowManyTab + 1;
    >> newoneline =3D PreffixStr + TrimIt; // =B0=D1=C7=B0=D7=
    >> =BA=BF=D5=B8=F1=CC=ED=BC=D3=B5=BD=D5=E2=D2=BB=D0=D0=C7=B0=C3=E6
    >> break;
    >> }
    >> case -1 : {

    >
    > the process of posting on a newsreader is scrambling your code. Try


    Blame your own newsreader! I had no trouble reading the OP with
    Thunderbird, Chinese comments and all.
    The headers are a bit unusual, granted:
    Content-Type: text/plain; charset=GB2312
    Content-Transfer-Encoding: quoted-printable
    (which your newsreader ignores completely)

    > posting it somewhere and giving the URL.


    --
    Lars Enderin
     
    Lars Enderin, Mar 2, 2012
    #6
  7. Arne Vajhøj Guest

    On 3/2/2012 1:04 PM, Roedy Green wrote:
    > On Fri, 2 Mar 2012 03:29:41 -0800 (PST), wrote,
    > quoted or indirectly quoted someone who said :
    >> PreffixStr =3D ManyTabStr (HowManyTab, TabBlank);
    >> HowManyTab =3D HowManyTab + 1;
    >> newoneline =3D PreffixStr + TrimIt; // =B0=D1=C7=B0=D7=
    >> =BA=BF=D5=B8=F1=CC=ED=BC=D3=B5=BD=D5=E2=D2=BB=D0=D0=C7=B0=C3=E6
    >> break;
    >> }
    >> case -1 : {

    >
    > the process of posting on a newsreader is scrambling your code. Try
    > posting it somewhere and giving the URL.


    You need a newsreader that understands Quoted Printable.

    Something from late 90's or later should support that.

    Arne
     
    Arne Vajhøj, Mar 2, 2012
    #7
  8. Guest

    I am a Java beginner, perhaps it is my third Java program, sorry for my poor skill in Java. I donot use Eclipse to write Java codes, it is not good ateditting codes, I prefer notepad ++ (http://notepad-plus-plus.org/download/v5.9.8.html) and SciTE(http://www.scintilla.org), Eclipse is a good integrated tool for developing Java program, but it is not the suitable editor topurely edit codes. I learn a lot from people's comment, later I will continue to post my codes here for comments.
    I donot know how to post long codes, I donot have space to attach my program.
     
    , Mar 2, 2012
    #8
  9. Arne Vajhøj Guest

    On 3/2/2012 6:55 PM, wrote:
    > I am a Java beginner, perhaps it is my third Java program, sorry for my poor skill in Java. I donot use Eclipse to write Java codes, it is not good at editting codes, I prefer notepad ++ (http://notepad-plus-plus.org/download/v5.9.8.html) and SciTE(http://www.scintilla.org), Eclipse is a good integrated tool for developing Java program, but it is not the suitable editor to purely edit codes. I learn a lot from people's comment, later I will continue to post my codes here for comments.
    > I donot know how to post long codes, I donot have space to attach my program.


    I think you will find out that >95% of Java developers use Eclipse or
    similar Java IDE to edit Java code.

    Arne
     
    Arne Vajhøj, Mar 3, 2012
    #9
  10. Lew Guest

    On 03/02/2012 03:55 PM, wrote:
    > I am a Java beginner, perhaps it is my third Java program, sorry for my poor skill in Java. I donot use Eclipse to write Java codes, it is not good at editting codes, I prefer notepad ++ (http://notepad-plus-plus.org/download/v5.9.8.html) and SciTE(http://www.scintilla.org), Eclipse is a good integrated tool for developing Java program, but it is not the suitable editor to purely edit codes. I learn a lot from people's comment, later I will continue to post my codes here for comments.
    > I donot know how to post long codes, I donot have space to attach my program.


    I disagree. Eclipse is entirely suitable as a code editor, even if you ignore
    all its other features. Ditto NetBeans. Ditto many others.

    I am interested in the details of why you find Eclipse unsuitable. What are they?

    Don't post long programs. Post simple, short, complete, compilable examples
    (SSCCEs) that reveal your difficulty.
    http://sscce.org/

    What you posted in the beginning was an SSCCE. It was enough from my point of
    view, anyway.

    As for not having space to attach your programs, sure you do. You've already
    done it. Not that you should attach anything, you should do exactly as you did
    and include it in the body of your post.

    However, this is a discussion group, so when people ask you questions you
    should participate in the discussion.

    > Novice wrote:
    >> Are you simply trying to tell us that you have written a program that
    >> formats Java source code so that we know? Or do you have a question of
    >> some kind?


    He has a point. We don't know why you came to us. Why did you?

    --
    Lew
    Honi soit qui mal y pense.
    http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg
     
    Lew, Mar 3, 2012
    #10
  11. Guest

    >He has a point. We don't know why you came to us. Why did you?
    -------
    My work doesnot need Java, I learn Java just for fun. Find some people to talk about something is interesting.
     
    , Mar 3, 2012
    #11
  12. Guest

    > am interested in the details of why you find Eclipse unsuitable. What arethey?
    ------------
    before I used SciTe to edit rebol codes, so I get used to the operation of SciTE, it is one the reasons that I continue to use the old editor. I triedEcplise, I find it cannot hightlight the matched "{" or "}", I am afraid it is because I donot know how to properly configure Ecplise. Addtionall, I find it is inconvenient to use SEARCH function in Ecplise.
     
    , Mar 3, 2012
    #12
  13. Lew Guest

    On 03/02/2012 07:24 PM, wrote:
    >> am interested in the details of why you find Eclipse unsuitable. What are they?

    > ------------
    > before I used SciTe to edit rebol codes, so I get used to the operation of SciTE,
    > it is one the reasons that I continue to use the old editor. I tried Ecplise,
    > I find it cannot hightlight the matched "{" or "}", I am afraid it is because I
    > donot know how to properly configure Ecplise.


    You are right.

    There is a setting in Eclipse to highlight matching braces.

    With any highlighting editor one has to invest time to configure the various
    syntax-coloring, indentation, layout, whatever options to our taste. If you
    don't, it's not the editor's fault.

    > Addtionall, I find it is inconvenient to use SEARCH function in Ecplise.


    Again, what's inconvenient about it? You type Ctrl-F, type in the search term
    and hit ENTER. Most of the GUI apps that allow search from browsers to editors
    to word processors to spreadsheets and beyond use the exact same idiom.

    What does SciTE do that's better, read your mind?

    --
    Lew
    Honi soit qui mal y pense.
    http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg
     
    Lew, Mar 3, 2012
    #13
  14. Lew Guest

    On 03/02/2012 06:57 PM, wrote:
    >> He has a point. We don't know why you came to us. Why did you?

    > -------
    > My work doesnot need Java, I learn Java just for fun. Find some people to talk about something is interesting.


    OK, but why did you come to us with that first post?

    You were asked a specific question that you keep avoiding for some reason.
    I'll repeat it, since you edited it out:

    > Novice wrote:
    >> Are you simply trying to tell us that you have written a program that
    >> formats Java source code so that we know? Or do you have a question of
    >> some kind?


    In other words, what was the specific point you made with your original post?

    --
    Lew
    Honi soit qui mal y pense.
    http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg
     
    Lew, Mar 3, 2012
    #14
  15. Roedy Green Guest

    On Sat, 10 Mar 2012 13:01:20 +0100, Wanja Gayk <>
    wrote, quoted or indirectly quoted someone who said :

    >
    >As a beginner in programming, you should really better start with a
    >lower hanging fruit.


    For example, try reflowing some text to make sure no lines are longer
    than n.

    Then add blank line collapsing, preserve blank lines or multiple blank
    lines as one blank line.

    I have a project in limbo right now to reflow HTML. You might look at
    IntelliJ for a remarkably complete set of specifications on just how
    you want the final result so look.

    see http://mindprod.com/jgloss/intellij.html
    --
    Roedy Green Canadian Mind Products
    http://mindprod.com
    One of the most useful comments you can put in a program is
    "If you change this, remember to change ?XXX? too".
     
    Roedy Green, Mar 15, 2012
    #15
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Greg  --
    Replies:
    4
    Views:
    2,276
  2. Replies:
    2
    Views:
    2,987
    Malcolm
    Aug 20, 2005
  3. xz
    Replies:
    2
    Views:
    340
    Roedy Green
    Sep 6, 2007
  4. Allen
    Replies:
    1
    Views:
    684
    Mark Rae [MVP]
    Dec 3, 2007
  5. Jean Dubois
    Replies:
    6
    Views:
    117
    Jean Dubois
    Dec 19, 2013
Loading...

Share This Page