java - Switch case 算法 Java 问题(需要新的 while 循环?)

标签 java arrays while-loop switch-statement

我正在尝试根据我的数组值运行 switch 语句。

我需要创建一个 while 循环,遍历整个数组, 如果数组位 value = 0 我需要它来运行 case 0 如果位 value = 1 我需要它来运行 case 1

我需要运行 while 循环,直到它完成数组值和相应的大小写切换函数的运行

我正在处理的代码:

        Scanner scan = new Scanner(System.in);
        System.out.println("What position do you want the top card to be moved to?");
        System.out.println("Enter \"1\", \"2\", \"3\", \"4\" or \"5\"");
        int i = scan.nextInt();
        int in = i -1;
        //System.out.println(i);
        String binaryString = Integer.toBinaryString(in);
        System.out.println(binaryString);
        int foo = Integer.parseInt(binaryString, 2);
        System.out.println(foo);

        String[] array = binaryString.split("\\|", -1);
            System.out.println(Arrays.toString(array));


            switch (foo) {
            case 0:
            cardForceOutShuffle();
            index = 51;
            break;
            case 1:
            cardForceInShuffle();
            index = 51;
            break;
            }


请帮忙。

最佳答案

假设很多的事情,这就是我想出的。请更准确地回答您的问题..

我将我的观点作为注释添加到了一些代码中。

Scanner scan = new Scanner(System.in);
System.out.println("What position do you want the top card to be moved to?");
System.out.println("Enter \"1\", \"2\", \"3\", \"4\" or \"5\"");
int i = scan.nextInt(); // This can lead to an InputMismatchException. Try to check if your input is an integer before you proceed.
int in = i - 1; // Unnecessary

String binaryString = Integer.toBinaryString(in); // Use i-1 directly
char[] charArray = binaryString.toCharArray(); // Since you need each bit you dont need String.split. Just convert to char[]

for (int j = 0; j < charArray.length; j++) {
    switch (charArray[j]) { // This switch is actually useless, since both cases do the same thing.
    case '0':
        cardForceOutShuffle();
        index = 51; // What is index?
        break;
    case '1':
        cardForceOutShuffle();
        index = 51;
        break;
    }
}
scan.close(); // Close your resources if they are not needed anymore.

关于java - Switch case 算法 Java 问题(需要新的 while 循环?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59426482/

相关文章:

使用 .NET 6 或更高版本时需要 Java SDK 11.0 或更高版本

java - 参数是@Test 需要的,但没有被标记为@optional 或定义

php - 如何获取具有空值的数组键列表?

javascript - javascript中函数的替代方法

带有嵌套数组的 PHP foreach?

Java:输入10个多项选择A、B、C、D并输出数字正确、错误和等级

java - Html.fromHtml 在电子邮件中共享 Intent 时无法在正文中使用粗体文本

java - 对 onCreate 方法期间引用布局感到困惑

java - 逐行迭代文本文件的内容 - 是否有最佳实践? (与 PMD 的 AssignmentInOperand 相比)

C++ 无意义的表达式填充