take a matrix as input form the user .search a given number of x and print the indices at which it occurs in java

Viewed 15

The code below:

package javaFullcourse;

import java.util.Scanner;

public class TwoD {

    public static void main(String[] args) {
        System.out.println("Enter array elements:");
        Scanner s=new Scanner(System.in);
        int rows=s.nextInt();
        int cols=s.nextInt();
        int numbers[][]=new int[rows][cols];
        for(int i=0;i<rows;i++) {
            for(int j=0;j<rows;j++) {
                numbers[i][j]=s.nextInt();
            }
        }
        
        int x=s.nextInt();
        for(int i=0;i<rows;i++) {
            for(int j=0;j<rows;j++) {
                if(numbers[i][j]==x) {
                    System.out.print("x is found at location("+i+","+j+")");
                }
            }
        }
    }
}

It automatically posts the indices without the user's input of the given number. Why?? What I am doing wrong? Please help.

1 Answers

The for loop on columns should use j<cols

Changing the for loops from

for(int j=0;j<rows;j++)

to

for(int j=0;j<cols;j++)

would solve the issue.

Since the code was reading the wrong number of elements in the array, it was taking the number to be find within the array input itself.

Related