【问题标题】:Code decipher using do-while loops [closed]使用do-while循环进行代码解密[关闭]
【发布时间】:2016-10-25 18:50:14
【问题描述】:

我必须解码程序要求输入 1-7 的消息。 1 代表“D”。 2代表“W”。 3代表“E”。 4代表“L”。 5代表“H”。 6代表“O”。 7代表“R”。所以我尝试使用 do-while 循环来扫描我放在一起的字符串,然后一次扫描每个字母,将所述字母添加到解密的字符串中。请帮忙。这是我的代码:

        System.out.println("Please enter 10 numbers, after each number you put in, press enter. The numbers can only be from 1 - 7.");

    int numInputs = 0;
    String code = "", deciphered = "";
    int input = 0, charNumber = 1;

    do{
        System.out.println("Please enter a number: ");
        input = in.nextInt();
        code+=input;
        numInputs++;
    }while(numInputs < 10);

    System.out.println("Your code is " + code);
    do{
        switch(code.charAt(charNumber)){
        case 1: deciphered+="D";
        break;
        case 2: deciphered+="W";
        break;
        case 3: deciphered+="E";
        break;
        case 4: deciphered+="L";
        break;
        case 5: deciphered+="H";
        break;
        case 6: deciphered+="O";
        break;
        case 7: deciphered+="R";
        break;
        default: System.out.println("Something went wrong! Try again with numbers only 1 - 7.");
        }
        charNumber++;
        numInputs++;
    }while(numInputs < 10);

    System.out.println("The output is: "+deciphered);
}

【问题讨论】:

  • 请帮忙,什么?您没有表达需要帮助的问题。
  • 问题是什么?

标签: java loops do-while


【解决方案1】:
  1. 您的第二个 do-while 循环(可能应该是一个 for 循环)使用 numInputs &lt; 10 作为其条件。由于numInputs 由于第一个 do-while-loop 已经是 10,因此您的第二个 do-while-loop 只会执行一次。您不会在其他任何地方使用charNumber,在此使用条件更有意义。此外,它必须设置为 0 开始,因为String 的索引从 0 开始。

  2. 当您将数字添加到 code 时,它们将被转换为与该数字对应的 chars,因此 1 -> '1', 2 -> '2', ...每次都会导致您的switch 失败。您有两个选择:使用ints 数组来保存代码,或者更改cases 以检查chars 而不是ints。

  3. 与您的任何问题无关,但您应该在函数结束时关闭inin.close();

【讨论】:

    猜你喜欢
    • 2015-04-24
    • 2016-08-13
    • 2020-02-29
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 2011-03-06
    • 1970-01-01
    相关资源
    最近更新 更多