小编rhe*_*ser的帖子

捕获throwable并处理特定异常

好的,我知道抓住throwable不是一个好主意:

    try {
         // Some code
    } catch(Throwable e) { // Not cool!
        // handle the exception
    }
Run Code Online (Sandbox Code Playgroud)

但最近我正在阅读一个开源代码,我看到了这段有趣的代码(至少对我而言):

    try {
        // Some Code
    } catch (Throwable ex){
        response = handleException(ex, resource);
    }

    private handleException(Throwable t, String resource) {
        if (t instanceof SQLEXception) {
               // Some code
        } else if (t instanceof IllegalArgumentException) {
               //some code
        } //so on and so forth
    }
Run Code Online (Sandbox Code Playgroud)

这似乎不是那么糟糕?这种方法有什么问题?

java exception-handling exception

23
推荐指数
3
解决办法
8412
查看次数

算法将数字转换为String

我需要设计一种算法,其中每个数字都被编码为字母表,例如:

1 = A,2 = B,3 = C ... 26 = Z

给定一组数字,我必须将它们转换为字符串组合.例如:

123可以被翻译为 - ABC(123),AW(1 23)和LC(12 3)

编写算法以查找数字组合 - 123123123.

现在这就是我写的内容,因为有多个"for"循环,我发现它效率低下.有没有更好的方法可以重写这个算法?

public class ValidCombinations {
    Map<Integer, String> mapping = new HashMap<Integer, String>();

    public void run() {
            String s = "123123123";

            /*Convert String to int[]*/
            char[] cArray = s.toCharArray();
            int[] input = new int[cArray.length];

            for (int i=0; i<cArray.length; i++) {
                    input[i] = Character.getNumericValue(cArray[i]);
            }

            Set<String> output = new HashSet<String>();

            for (int i='A'; i<='Z'; i++) {
                    mapping.put(i - 'A' + 1, …
Run Code Online (Sandbox Code Playgroud)

java algorithm

7
推荐指数
1
解决办法
718
查看次数

Java - 解决多个条件逻辑的设计模式

假设我有一个实用程序类。在本课程中,我仅公开 2 个公共函数:

\n\n
public static boolean checkCustomerEligiblity(HttpServletRequest request)\npublic static boolean checkCartEligiblity(HttpServletRequest request)\n
Run Code Online (Sandbox Code Playgroud)\n\n

这些方法\xe2\x80\x99s的实现真的很乱(我没有实现这个方法)。为了供将来参考,我想了解在这种情况下我们可以实施的最佳方法。

\n\n

还要记住的是,如果条件为 FALSE,我们不应该退出或返回。我们必须记录 FALSE 条件并给出原因,然后继续进行其余的检查。

\n\n
public static Boolean checkCustomerEligiblity(HttpServletRequest request) {\n      if (Flags) { //Check if Flags are ON, only then proceed with rest         \n        if (Type of customer) { //Restrict only to certain type of customers\n          if (Customer within limit) { //Check customer\xe2\x80\x99s available cash limit in account\n\n          } else reasons.add(\xe2\x80\x9cCustomer not within limit\xe2\x80\x9d);\n        } else reasons.add(\xe2\x80\x9cCustomer type not supported\xe2\x80\x9d);\n\n        if (Customer account …
Run Code Online (Sandbox Code Playgroud)

java design-patterns strategy-pattern

4
推荐指数
1
解决办法
7900
查看次数