How to scan the matrix using only one for?

Asked

Viewed 46 times

-2

The circumstances are in the code that works:

    String[][] compras = new String[][] { { "item 1", "1.70" }, { "item 2", "39.90" }, { "item 3", "9.90" }, { "item 4", "4.90" }, { "item 5", "7.90" } };
            
    int soma = 0;
    for (int i = 0; i < compras.length; i++) {
        for (int j = 0; j < compras[i].length; j++) {

            if (j == 1) {
                soma = (int) (soma + Double.parseDouble(compras[i][j]));
            }
        }
    }

    System.out.println("Total das compras: R$ " + soma);
}
  • Important when posting a question, explain objectively and punctually the difficulty found, accompanied by a [mcve] problem and attempt to solve. To understand what kind of question serves the site and, consequently, avoid closures and negativities worth reading What is the Stack Overflow and the Stack Overflow Survival Guide (summarized) in Portuguese.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

2

In fact, the internal tie makes no sense, it travels through a dimension but only wants one element, so use that element instead of going through all of them. In practice you only need index 1 and not go through it all. So is the way j is variant, but the if makes it only useful as constant.

class Main {
    public static void main (String[] args) {
        String[][] compras = new String[][] {
                { "item 1", "1.70" }, { "item 2", "39.90" }, { "item 3", "9.90" }, { "item 4", "4.90" },
                { "item 5", "7.90" } };
        int soma = 0;
        for (int i = 0; i < compras.length; i++) soma = (int)(soma + Double.parseDouble(compras[i][1]));
        System.out.println("Total das compras: R$ " + soma);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Another important detail is that it seems to be using monetary values that cannot be represented with the type Double.

  • Thank you so much!! helped me a lot!! success!

  • @Mariana see on [tour] that you can accept the answer if she solved your problem.

Browser other questions tagged

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