【问题标题】:Sorting Java case statements对 Java 案例语句进行排序
【发布时间】:2017-11-13 08:47:13
【问题描述】:

我不久前来到这里试图找出是否有一种方法可以自动对案例语句进行排序。Eclipse 没有自动执行此操作的答案。所以我想找到一种方法来做到这一点。可悲的是,这似乎没有在任何地方解决。这是每个人都需要做的事情吗?可能不会。

【问题讨论】:

  • 这不是一个常见的用例,但我想它可能对重构有所帮助。
  • 我同意这不是人们可能需要做的日常事情。但是,如果案例陈述实际上遵循某种逻辑(即最有可能首先发生的事情),那么我实际上也不需要它。但是现在处理一长串案例语句,我可以轻松地向下滚动到我需要的地方,而不必 ctrl+F 一切。

标签: java sorting arraylist switch-statement


【解决方案1】:

这是我的解决方案:

主要调用:

package com.debug;

import java.io.IOException;

public class DebugMain {

    public static void main(String[] args) {
        fixCases();
    }

    public static void fixCases() {
        String filePath = System.getProperty("user.home").replace("\\", "/") + "/Documents/";
        String fileName = "case.txt";
        System.out.println("Organizing cases: " + filePath + fileName);

        CaseHandler ch = new CaseHandler(filePath + fileName, CaseType.Integer);
        try {
            ch.readFile();
            ch.sortCases();
            ch.writeCases(filePath + "casetest.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Organizing complete.");
    }
}

案例处理程序:

package com.debug;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * This handler allows you to read from a text file a list of case statements, sort the case statements<br />
 * in natural order, and write to a file.
 * 
 * @author Vincent
 */
public class CaseHandler {

    /**
     * This denotes the use of numerical or text based case statements.
     */
    public enum CaseType {
        String, Integer;
    }

    private boolean autoSort = false;
    private ArrayList<Case> cases = new ArrayList<Case>();
    private CaseType caseType;
    private File file;

    /**
     * This construcs a basic <code>CaseHandler</code> in which a file must be provided
     * within the {@link #readFile(String)} method.
     * <b>Note:</b> The file expected should always be a text file with only the case statements.<br />
     * The formatting is not important.
     * 
     * @param caseType The type of case this instance should use.
     * @see {@link CaseType}, {@link CaseHandler}
     */
    public CaseHandler(CaseType caseType) {
        this.caseType = caseType;
    }

    /**
     * This construcs a <code>CaseHandler</code> with a file provided.<br />
     * <b>Note:</b> The file expected should always be a text file with only the case statements.<br />
     * The formatting is not important.
     * 
     * @param fileName The full file path and name to be read from and/or written to.
     * @param caseType The type of case this instance should use.
     * @see {@link CaseType}, {@link CaseHandler}
     */
    public CaseHandler(String fileName, CaseType caseType) {
        this.caseType = caseType;
        this.file = new File(fileName);
    }

    /**
     * This construcs a <code>CaseHandler</code> with a file provided.<br />
     * <b>Note:</b> The file expected should always be a text file with only the case statements.<br />
     * The formatting is not important.
     * 
     * @param fileName The full file path and name to be read from and/or written to.
     * @param caseType The type of case this instance should use.
     * @param autoSort Enables auto sorting in the {@link #readFile()}
     */
    public CaseHandler(String fileName, CaseType caseType, boolean autoSort) {
        this.caseType = caseType;
        this.file = new File(fileName);
        this.autoSort = autoSort;
    }

    /**
     * Reads the file where the case statements are stored line by line.<br />
     * When the word case is found it creates a new temp <code>ArrayList</code> of <code>String</code>. <br />
     * If a temp <code>ArrayList</code> already exists then it overwrites the <code>ArrayList</code>. <br />
     * When the word break is found it then creates a <code>Case<code> object and stores the lines.<br />
     * This then stores the <code>Case</code> objects into an <code>ArrayList</code> for later use.
     * If auto sort has been enabled in the constructor then this will also sort the <code>Case</code> objects.
     * 
     * @throws IOException
     * @see {@link ArrayList}, {@link FileReader}, {@link BufferedReader}, {@link Case}
     */
    public void readFile() throws IOException {
        if (this.file != null && this.file.exists()) {
            FileReader fr = null;
            BufferedReader br = null;
            try {
                fr = new FileReader(this.file);
                br = new BufferedReader(fr);
                String line = "";
                ArrayList<String> lines = null;
                while ((line = br.readLine()) != null) {
                    if (line.contains("case")) {
                        if (lines != null && lines.get(lines.size() - 1).contains("break")) {
                            lines = new ArrayList<String>();
                        } else {
                            lines = new ArrayList<String>();
                        }
                    }
                    lines.add(line);
                    if (line.contains("break")) {
                        String caseName = lines.get(0).replace("case", "").replace(":", "").trim();
                        Case aCase = null;
                        if (caseType == CaseType.Integer) {
                            aCase = new Case(Integer.parseInt(caseName), lines);
                        } else if (caseType == CaseType.String) {
                            aCase = new Case(caseName, lines);
                        }
                        cases.add(aCase);
                    }
                }
                if (this.autoSort) {
                    this.sortCases();
                }
            } finally {
                if (br != null) {
                    br.close();
                }
                if (fr != null) {
                    fr.close();
                }
            }
        } else {
            System.out.println("File " + this.file.getName() + " does not exist!");
        }
    }

    /**
     * Reads the file where the case statements are stored line by line.<br />
     * When the word case is found it creates a new temp <code>ArrayList</code> of <code>String</code>. <br />
     * If a temp <code>ArrayList</code> already exists then it overwrites the <code>ArrayList</code>. <br />
     * When the word break is found it then creates a <code>Case<code> object and stores the lines.<br />
     * This then stores the <code>Case</code> objects into an <code>ArrayList</code> for later use.
     * If auto sort has been enabled in the constructor then this will also sort the <code>Case</code> objects.
     * 
     * @param fileName The full file path and name to be read from and/or written to.
     * @throws IOException
     * @see {@link ArrayList}, {@link FileReader}, {@link BufferedReader}, {@link Case}
     */
    public void readFile(String fileName) throws IOException {
        this.file = new File(fileName);
        if (this.file != null && this.file.exists()) {
            FileReader fr = null;
            BufferedReader br = null;
            try {
                fr = new FileReader(this.file);
                br = new BufferedReader(fr);
                String line = "";
                ArrayList<String> lines = null;
                while ((line = br.readLine()) != null) {
                    if (line.contains("case")) {
                        if (lines != null && lines.get(lines.size() - 1).contains("break")) {
                            lines = new ArrayList<String>();
                        } else {
                            lines = new ArrayList<String>();
                        }
                    }
                    lines.add(line);
                    if (line.contains("break")) {
                        String caseName = lines.get(0).replace("case", "").replace(":", "").trim();
                        Case aCase = null;
                        if (caseType == CaseType.Integer) {
                            aCase = new Case(Integer.parseInt(caseName), lines);
                        } else if (caseType == CaseType.String) {
                            aCase = new Case(caseName, lines);
                        }
                        cases.add(aCase);
                    }
                }
                if (this.autoSort) {
                    this.sortCases();
                }
            } finally {
                if (br != null) {
                    br.close();
                }
                if (fr != null) {
                    fr.close();
                }
            }
        } else {
            System.out.println("File " + this.file.getName() + " does not exist!");
        }
    }

    /**
     * Sorts the {@link ArrayList} in alphabetical or numerical order.<br />
     * <b>Note:</b> This will <b>NOT</b> sort clusters of case statements.
     * @see {@link Collections#sort(java.util.List)}
     */
    public void sortCases() {
        if (cases.size() > 0) {
            Collections.sort(cases, Comparator.naturalOrder());
        }
    }

    /**
     * Overwrites the file provided to the <code>CaseHandler</code> with the cases list.
     * 
     * @throws IOException
     * @see {@link ArrayList}, {@link FileWriter}, {@link BufferedWriter}, {@link Case}
     */
    public void writeCases() throws IOException {
        if (this.file.exists()) {
            FileWriter fw = null;
            BufferedWriter bw = null;
            try {
                fw = new FileWriter(this.file);
                bw = new BufferedWriter(fw);
                for (Case aCase : cases) {
                    for (String line : aCase.getLines()) {
                        bw.write(line);
                        bw.newLine();
                    }
                }
            } finally {
                if (bw != null) {
                    bw.close();
                }
                if (fw != null) {
                    fw.close();
                }
            }
        }
    }

    /**
     * Overwrites the file provided to with the cases list.
     * 
     * @param fileName The full file path and name to be read from and/or written to.
     * @throws IOException
     * @see {@link ArrayList}, {@link FileWriter}, {@link BufferedWriter}, {@link Case}
     */
    public void writeCases(String fileName) throws IOException {
        File outFile = new File(fileName);
        if (!outFile.exists()) {
            outFile.createNewFile();
        }
        if (outFile.exists()) {
            FileWriter fw = null;
            BufferedWriter bw = null;
            try {
                fw = new FileWriter(outFile);
                bw = new BufferedWriter(fw);
                for (Case aCase : cases) {
                    for (String line : aCase.getLines()) {
                        bw.write(line);
                        bw.newLine();
                    }
                }
            } finally {
                if (bw != null) {
                    bw.close();
                }
                if (fw != null) {
                    fw.close();
                }
            }
        }
    }

    /**
     * Changes the case type.
     * 
     * @param caseType The new type of case this instance should use.
     * @see {@link CaseType}
     */
    public void setCaseType(CaseType caseType) {
        this.caseType = caseType;
    }
}

案例:

package com.debug;

import java.util.ArrayList;

/**
 * This is the individual case statement starting at <code>case (Integer or String):</code> <br />
 * The last line stored in the instance will be the <code>break;</code> statement.
 * 
 * @author Vincent
 *
 */
public class Case implements Comparable<Case> {

    private int nameInt;
    private String nameStr = null;
    private ArrayList<String> lines;

    /**
     * Constructs a new <code>Case</code> using integer values as the name.
     * 
     * @param nameInt The integer value name
     * @param lines The lines within this case statement
     * @see {@link ArrayList}
     */
    public Case(int nameInt, ArrayList<String> lines) {
        this.nameInt = nameInt;
        this.lines = lines;
    }

    /**
     * Constructs a new <code>Case</code> using string values as the name.
     * 
     * @param nameStr The string value name
     * @param lines The lines within this case statement
     * @see {@link ArrayList}
     */
    public Case(String nameStr, ArrayList<String> lines) {
        this.nameStr = nameStr;
        this.lines = lines;
    }

    @Override
    public int compareTo(Case aCase) {
        if (this.nameStr != null) {
            return this.nameStr.compareTo(aCase.getNameStr());
        } else {
            if (this.nameInt < aCase.getNameInt()) {
                return -1;
            } else if (this.nameInt > aCase.getNameInt()) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    /**
     * Returns the lines stored in this <code>Case</code> instance.
     * 
     * @return {@link ArrayList}
     */
    public ArrayList<String> getLines() {
        return this.lines;
    }

    /**
     * Returns the integer name of this <code>Case</code> instance.
     * 
     * @return {@link Integer}
     */
    public int getNameInt() {
        return this.nameInt;
    }

    /**
     * Returns the string name of this <code>Case</code> instance.
     * 
     * @return {@link String}
     */
    public String getNameStr() {
        return this.nameStr;
    }
}

示例输入:

case 338:
    // Code
    break;
case 852:
    // Code
    break;
case 2:
    // Code
    break;
case 696:
    // Code
    break;

示例输出:

case 2:
    // Code
    break;
case 338:
    // Code
    break;
case 696:
    // Code
    break;
case 852:
    // Code
    break;

希望这可能会帮助某人。我需要这个,因为我正在查看一长串案例(准确地说是 1000 个),这些案例没有按特定顺序排序或有任何理由按这种方式排序。所以我想以自然的顺序看到它们。

【讨论】:

  • 您应该包含代码作为答案,而不是问题本身。
  • 记下了,我把它移走了
  • 我喜欢这个想法,但是从可以将其编写为 IDE 插件的意义上说,这可以得到改进。具有更多功能,如 ASC 和 DESC 排序、字母排序等。
  • 我不想这么说,但我不熟悉制作这些插件,尽管在这种情况下这将是一个好主意。它不处理 ASC 和 DESC,尽管这可能很容易添加到它。这个只处理 ASC,它确实处理数字或字母排序。
猜你喜欢
  • 1970-01-01
  • 2020-10-17
  • 2013-05-11
  • 1970-01-01
  • 1970-01-01
  • 2016-11-24
  • 2023-03-29
  • 1970-01-01
  • 2016-12-14
相关资源
最近更新 更多