Creating matrix with the Scanner class

Asked

Viewed 40 times

1

I’m trying to fill a 5x5 matrix but when I run the ORDER in the finish entry, the code returns me the matrix filled with the word END.

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Digite");
    String s = sc.nextLine();
    String m[][] = new String[5][5];
    while (!s.equals("FIM")){
        System.out.println("Digite:");
        s = sc.nextLine();
        for (int i = 0; i < m.length; i++) {
            for (int j = 0; j < m.length; j++) {
                m[i][j] = s;
            }
        }
    }   
    sc.close();
    for (int i = 0; i < m.length; i++) {
        for (int j = 0; j < m.length; j++) {
            System.out.println(m[i][j]);
        }
    }   
  }     
 }

Code out:

 FIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIMFIM

desired output from the matrix with all letters typed:

q w e r t a d r t h j a v a s p y t h o t r e f g
  • the code must be able to be closed at any time at the FIM.

1 answer

1


What happens when you type anything? This thing is put in s, and then you go through the whole matrix and put s in all the elements of it.

If you want each element to have a different value, then the reading has to stay within the loop:

Scanner sc = new Scanner(System.in);
String m[][] = new String[5][5];
principal: for (int i = 0; i < m.length; i++) {
    for (int j = 0; j < m[i].length; j++) {
        System.out.println("Digite algo (ou FIM para encerrar):");
        String s = sc.nextLine();
        if ("FIM".equals(s))
            break principal; // encerra o for externo
        m[i][j] = s;
    }
}

That is, if you type "END", it already closes the loop and does not put the value in the matrix. I used a label (principal, but could be any name) so that the break interrupt the for external (without this, it would interrupt only the for intern).

And in the for intern I used m[i].length, since the "matrix" is actually an array of arrays, and each one can have a different size (in this case it does not, but anyway it is more guaranteed that I will always go through the correct sizes).


It is worth remembering that if the loop is interrupted in the middle, the elements that received no value will be null. It was not clear what to do in this case (if it is to print anyway). But there already another story...

  • Thanks friend, helped me a lot, this is an excerpt of the code, my intention is to create a square matrix of characters and search a word that is inside it, if it does not find false returns.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.