0

I'm trying to get this code to run, but I keep getting an error saying:

at main.Main.flipVertically(Main.java:403) which is the code below.

img[row][col] = img[height - row - 1][col];

I don't know what's wrong with the code or the error they are talking about.

Here's the rest of the code:

public static int[][] flipVertically(int[][] img) {

    String dir = "image.jpg";

    img = Util.readImageToMatrix(dir);


    int height = img[0].length;
    int width = img.length;

    for(int row = 0; row < height/2; row++)
        {

            for(int col = 0; col < width; col++)
            {
                int p = img[row][col];
                img[row][col] = img[height - row - 1][col];
                img[height - row - 1][col] = p;
            }
        }
    return img;


}
Slurp123
  • 3
  • 3
  • 2
    *"I keep getting this error"* - include the error in your question please. – Anish Sana Jan 27 '18 at 23:12
  • Ok, I added what I could. It's not specifying the error though. – Slurp123 Jan 27 '18 at 23:19
  • `at main.Main.flipVertically(Main.java:403)` is part of stacktrace. What is at its start? Please see [What is a stack trace, and how can I use it to debug my application errors?](https://stackoverflow.com/q/3988788) – Pshemo Jan 27 '18 at 23:21
  • "at main.Main.flipVertically(Main.java:403)" is **where** the error is, you need to post **what** the error is (which should be on one of the lines above that). Also, you should post a [mcve]. – Bernhard Barker Jan 27 '18 at 23:21

1 Answers1

1
  1. height and width swapped

    int height = img.length;
    int width = img[0].length;
    
  2. you souldnt read the matrix in the loop and use the parameter img from function input, or better create a new matrix.

  3. you can swap entire rows like:

    public static void flipVertically(int[][] img) {
    
        int height = img.length;
        int width = img[0].length;  
    
        for(int row = 0; row < height/2; row++)
        {
            int [] myrow =  img[row];
            img [row] = img[height - row - 1];
    
            img[height - row - 1] = myrow;          
        }      
    }
    
Pshemo
  • 122,468
  • 25
  • 185
  • 269
user8426627
  • 903
  • 1
  • 9
  • 19
  • Ahh ok, I see. In the code I have the [0] was with height so I thought that's where it would go below too. – Slurp123 Jan 27 '18 at 23:29