簡體   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