简体   繁体   中英

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

I am currently learning Java and am completing exercises based on it; however, there is a specific issue that I am facing with one of the exercises. The task is described below:

Elements in position

Given a matrix "nxn" containing the numbers a 0 to n2 - 1, return the number of elements that are in the correct position.

For example given a matrix 3x3:

 4 2 6 0 8 5 7 1 3

The correct position of each number is shown in the following matrix:

 0 1 2 3 4 5 6 7 8

The software, having the first matrix as input, should print the value 1, because only 5 is in the correct position.but now i have changed the number of elements in the correct posistion to two it should print two but i get 1 1 im not sure how can i add those 1 and 1 to get two.

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);

You have declared the count variable inside the for loop and also printing the result inside the loop. Here is the correct code to do that -

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);
   } 
} 

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