在数组中找到二进制表示

时间:2014-04-09 03:37:18

标签: java methods switch-statement

我需要创建一个可以使用适当转换方法的switch语句。这是我的代码

public class ExerciseTwo
{
public static void main (Strings[] args)
{

Scanner input = new scanner(system.in);
String[] binary = { "0","1","2","3","4","5","6","7","8"};

for (c = 0; c < array.length; counter++)
binary[] = input.nextInt();

System.out.println("Enter number between 0 and 8");
number = input.nextInt();

system.out.printf("the number", "number_given", "is", "binaryVersion", "binary");
}
}

2 个答案:

答案 0 :(得分:0)

对不起,但描述对我来说并不是很清楚。您是否只是尝试使用switch语句将输入值(0到8之间)转换为二进制格式(如2 - &gt; 10,7&gt; 111)?如果是这样,此代码将起作用。如果没有,你能为我澄清一下这个问题吗?

谢谢!

public static void main(String args[]) {
    Scanner input = new Scanner(System.in);

    System.out.println("Enter number between 0 and 8"); 
    int number = input.nextInt();
    int binaryRepresentation = -1;

    switch (number)
    {
    case 0:
        binaryRepresentation = 0;
        break;
    case 1:
        binaryRepresentation = 1;
        break;
    case 2:
        binaryRepresentation = 10;
        break;
    case 3:
        binaryRepresentation = 11;
        break;
    case 4:
        binaryRepresentation = 100;
        break;
    case 5:
        binaryRepresentation = 101;
        break;
    case 6:
        binaryRepresentation = 110;
        break;
    case 7:
        binaryRepresentation = 111;
        break;
    case 8:
        binaryRepresentation = 1000;
        break;
    }

    System.out.printf("the number " + number + " is " + binaryRepresentation + " in binary (-1 means invalid input)"); 
}

答案 1 :(得分:0)

自己做家务,查看http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html开关案例定义。如果您真的想要二进制表示的良好解决方案,那么请查看Integer类的API文档 http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html?is-external=true

使用API​​ doc是您作为Java程序员需要学习的第一件事。