簡體   English   中英

如何在正確的 position 中打印元素總數?

[英]How can i print total number of elements in the correct position?

我目前正在學習Java,並在此基礎上完成練習; 但是,我在其中一項練習中遇到了一個特定問題。 任務描述如下:

position 中的元素

給定一個包含數字 a 0 到 n2 - 1 的矩陣“nxn”,返回正確 position 中的元素數。

例如給定一個 3x3 矩陣:

 4 2 6 0 8 5 7 1 3

每個數字的正確 position 如以下矩陣所示:

 0 1 2 3 4 5 6 7 8

將第一個矩陣作為輸入的軟件應該打印值 1,因為只有 5 在正確的 position 中。但是現在我已經將正確位置的元素數量更改為兩個它應該打印兩個但我得到 1 1 im不知道如何添加那些 1 和 1 以獲得兩個。

public class HelloWorld {

    public static void main(String[] args) {
        // Prints "Hello, World" to the terminal window.
        System.out.println("Hello, World");
        
         int[] arr = {4,2,6,0,8,5,7,1,8};
         
        for(int i = 0; i < arr.length ; i++) {
          
          int count = 0;
          if (arr[i] == i) {
count++;
System.out.println(+ count);

您已經在 for 循環內聲明了 count 變量,並在循環內打印了結果。 這是執行此操作的正確代碼-

public class HelloWorld {

    public static void main(String[] args) {
        // Prints "Hello, World" to the terminal window.
        System.out.println("Hello, World");
        
        int[] arr = {4,2,6,0,8,5,7,1,8};
        int count = 0;
        for(int i = 0; i < arr.length ; i++) {
          if (arr[i] == i) {
            count++;
          }
       } 
       System.out.println(count);
   } 
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM