繁体   English   中英

如何扫描数组并将输入与数组元素进行比较

[英]How to scan an array and compare an input to the elements of the array

我正在尝试制作一个十进制到二进制的转换器,这部分代码只是一个测试示例。 在此测试程序中,我想打印出数组的每个元素,但似乎无法使程序做到这一点。

这是我当前的代码:

int[] nums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
    int dec;
    int out = 0;
    Scanner scan = new Scanner(System.in);

    System.out.println("Type decimal number.");
    dec = scan.nextInt();

    for( nums[out] = nums[out] ; out < 16 ; out++ );
    {
            System.out.println(out + "\n");//I want to print each element just to test my code .
    }

这是我得到的输出:

16

我应该在哪里得到这个:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

有人可以告诉我我在做什么错吗?

因为只有一个您只得到16 ; 在for循环的末尾。

for(nums [out] = nums [out]; out <16; out ++);

如果将其删除,您的代码将可以正常工作。 顺便说一句,您应该考虑按照PNS建议更改代码。

如果要打印nums数组的内容,只需在for循环中初始化out参数:

for (int out = 0; out < nums.length ; out++);
{
   System.out.println(nums[out] + "\n");
}

如果要打印通过Scanner读取的号码,请直接执行以下操作:

System.out.println(dec + "\n");

当然,以上内容不做任何转换,也不做任何比较,因此,如果需要类似的内容,则需要澄清此问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM