异常处理切换方法

时间:2018-03-30 18:54:20

标签: java exception-handling nullpointerexception

我试图获得一个程序,我要求某人提供1到13之间的数字,以便让他们做出选择。我试图弄清楚如果他们想要逆势并输入无效数字或字符或字符串,如何处理。这就是我到目前为止所拥有的......

try {
        attackingUnit = selectUnit(input.nextInt());
        attackerUnitName = attackingUnit.getUnitName();
    } catch (NullPointerException e) {
        System.out.println("Invalid option, please pick a valid option\n");
        showUnitSelection();
        attackingUnit = selectUnit(input.nextInt());
        attackerUnitName = attackingUnit.getUnitName();
}

这是我用来进行选择的方法:

private static Unit selectUnit(int selection) {

    switch (selection) {
        case 1:
            return Unit.GreatSwords;
        case 2:
            return Unit.BlackOrcs;
        case 3:
            return Unit.Bestigor;
        case 4:
            return Unit.ChaosChosen;
        case 5:
            return Unit.MenAtArms;
        case 6:
            return Unit.Executioners;
        case 7:
            return Unit.GraveGuard;
        case 8:
            return Unit.Retributors;
        case 9:
            return Unit.StormVermin;
        case 10:
            return Unit.SwordMasters;
        case 11:
            return Unit.TombGuard;
        case 12:
            return Unit.WildWoodRangers;
        case 13:
            return Unit.Hammerers;
    }

    return null;
}

我很确定我没有做到这一点,如果你不介意我想听听一些建议要考虑。

4 个答案:

答案 0 :(得分:1)

如果你这样做,我觉得代码看起来会更漂亮:

public enum Unit{

        GreatSwords(1),
        BlackOrcs(2),
        Bestigor(3),
        ChaosChosen(4),
        MenAtArms(5),
        Executioners(6),
        GraveGuard(7),
        Retributors(8),
        StormVermin(9),
        SwordMasters(10),
        TombGuard(11),
        WildWoodRangers(12),
        Hammerers(13)

        private int index;

        public int getIndex() {
            return this.index;
        }

        public static getUnitByIndex(int index) throws IllegalArgumentException {
            return Stream.of(values())
            .filter(unit -> unit.getIndex() == index)
            .findFirst()
            .orElseThrow(() -> new IllegalArgumentException("Invalid value");
        }

}

答案 1 :(得分:0)

这里的想法是避免空值,因此最好的选择是如果switch语句与任何内容不匹配,则返回min-width: 0的默认情况。然后你可以检查输入是否等于Unit.Unknown,以及它是否告诉用户它是无效的。

要执行此操作,首先将“Unknown”成员添加到Unit枚举。

然后在您的switch语句中添加一个默认大小写,如下所示:

Unit.Unknown

然后在原始代码中将其更改为:

     default:
        return Unit.Unknown;

答案 2 :(得分:0)

您的切换代码与默认情况一样 -

TestDummyContract
    ✓ testRandomNumberNew (53ms)
    1) testRandomNumberDeployed
    > No events were emitted


  1 passing (894ms)
  1 failing

  1) TestDummyContract testRandomNumberDeployed:
     Error: VM Exception while processing transaction: revert
      at Object.InvalidResponse (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/errors.js:38:1)
      at /usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/requestmanager.js:86:1
      at /usr/local/lib/node_modules/truffle/build/webpack:/~/truffle-provider/wrapper.js:134:1
      at XMLHttpRequest.request.onreadystatechange (/usr/local/lib/node_modules/truffle/build/webpack:/~/web3/lib/web3/httpprovider.js:128:1)
      at XMLHttpRequestEventTarget.dispatchEvent (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:64:1)
      at XMLHttpRequest._setReadyState (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:354:1)
      at XMLHttpRequest._onHttpResponseEnd (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:509:1)
      at IncomingMessage.<anonymous> (/usr/local/lib/node_modules/truffle/build/webpack:/~/xhr2/lib/xhr2.js:469:1)
      at endReadableNT (_stream_readable.js:974:12)
      at _combinedTickCallback (internal/process/next_tick.js:80:11)
      at process._tickCallback (internal/process/next_tick.js:104:9)

您的处理代码就像 -

    private static Unit selectUnit(int selection) {

        switch (selection) {
            case 1:
                return Unit.GreatSwords;
            case 2:
                return Unit.BlackOrcs;
            case 3:
                return Unit.Bestigor;
            case 4:
                return Unit.ChaosChosen;
            case 5:
                return Unit.MenAtArms;
            case 6:
                return Unit.Executioners;
            case 7:
                return Unit.GraveGuard;
            case 8:
                return Unit.Retributors;
            case 9:
                return Unit.StormVermin;
            case 10:
                return Unit.SwordMasters;
            case 11:
                return Unit.TombGuard;
            case 12:
                return Unit.WildWoodRangers;
            case 13:
                return Unit.Hammerers;
 default:throw new IllegalArgumentException(""Invalid option, please pick a valid option\n");
        }

    }

答案 3 :(得分:0)

试试这个。使用异常处理进行简单验证是一项昂贵的操作,尽管它可以正常工作。

attackingUnit = null;
while(attackingUnit == null){
   System.out.println("Invalid option, please pick a valid option\n");
   showUnitSelection();
   attackingUnit = selectUnit(input.nextInt());   
}

attackerUnitName = attackingUnit.getUnitName();

更新: 修改方法以包含默认情况(根据@SteelToe建议)

private static Unit selectUnit(int selection) {

switch (selection) {
    case 1:
        return Unit.GreatSwords;
    case 2:
        return Unit.BlackOrcs;
    case 3:
        return Unit.Bestigor;
    case 4:
        return Unit.ChaosChosen;
    case 5:
        return Unit.MenAtArms;
    case 6:
        return Unit.Executioners;
    case 7:
        return Unit.GraveGuard;
    case 8:
        return Unit.Retributors;
    case 9:
        return Unit.StormVermin;
    case 10:
        return Unit.SwordMasters;
    case 11:
        return Unit.TombGuard;
    case 12:
        return Unit.WildWoodRangers;
    case 13:
        return Unit.Hammerers;
    default:
        return Unit.Unknown;

  }


}

这样做:

attackingUnit = Unit.Unknown;
while(attackingUnit == Unit.Unknown){
   System.out.println("Invalid option, please pick a valid option\n");
   showUnitSelection();
   attackingUnit = selectUnit(input.nextInt());   
}

attackerUnitName = attackingUnit.getUnitName();