简体   繁体   中英

How to scan an array and compare an input to the elements of the array

I'm trying to make a decimal to binary converter and this part of code is just a test sample. In this test program, I want to print out each element of the array and I just can't seem to make the program do that.

Here is my current code:

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 .
    }

This is the output I get:

16

Where I should be getting this:

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

Can someone please show me what I'm doing wrong?

You are getting only 16 because there is a ; at the end of for loop.

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

If you remove it, ur code will should work. By the way you should consider changing the code as PNS suggested.

If you want to print contents of the nums array, just initialize the out parameter in the for loop:

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

If you want to print the number read via Scanner , do that directly:

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

The above, of course, does not do any conversion, nor does it do any comparison, so if something like that is required, the question needs to be clarified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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