Jump to content

Hi guys, I dont understand why when running my code in the terminal in shows me the following message" Index 2 out of bounds for length 2" Thanks!!!

rubendelope
import java.util.List;
import java.util.ArrayList;

public class multiplyingMatrixes{

        public static void main(String[] args) {
            List<Integer> matriz3 = new ArrayList<>();
         
            int [][] m1 = {{1,2,3},{1,2,3}};
            int [][] m2 = {{0,3,4},{1,0,2}};
            int row1 = m1.length;
            int column2 = m2[0].length;
            int [][] m3 = new int[row1][column2];

           if(row1 != column2){
               System.out.println("the rows from the first matrix; "+ row1+",do not match with the columns form the second matrix: "+ column2+",");

           }
            
            // [2] are the rows and [3] are the columns

          
            int x,y,k;
            // rows that is why x goes until 2
            for(x = 0; x < row1 ; x++);
            //columns that is why y goes until 3
                for(y = 0; y < column2; y++);
                m3[x][y] = 0;
            // we use k to sum all the elements multiplied in the row and column
                    for(k  = 0; k < column2; k++){
                      m3[x][y] += m1[x][k] * m2[k][y];
                     }
                     for ( x = 0; x < row1; x++)
                        for( y = 0; y < column2; y++){

                            System.out.println(m3[x][y]);
                            System.out.println("");
                        }
                        
                    }


        
        
    

           

            }

        
    

    
     

   

Delete this before posting. Please make sure to include the language that you're using in the title, and use the <> button for any code.

 

Link to comment
Share on other sites

Link to post
Share on other sites

57 minutes ago, rubendelope said:

Delete this before posting. Please make sure to include the language that you're using in the title, and use the <> button for any code.

The short answer is that you have your row count and your column count switched.

Main System (Byarlant): Ryzen 7 5800X | Asus B550-Creator ProArt | EK 240mm Basic AIO | 16GB G.Skill DDR4 3200MT/s CAS-14 | XFX Speedster SWFT 210 RX 6600 | Samsung 990 PRO 2TB / Samsung 960 PRO 512GB / 4× Crucial MX500 2TB (RAID-0) | Corsair RM750X | Mellanox ConnectX-3 10G NIC | Inateck USB 3.0 Card | Hyte Y60 Case | Dell U3415W Monitor | Keychron K4 Brown (white backlight)

 

Laptop (Narrative): Lenovo Flex 5 81X20005US | Ryzen 5 4500U | 16GB RAM (soldered) | Vega 6 Graphics | SKHynix P31 1TB NVMe SSD | Intel AX200 Wifi (all-around awesome machine)

 

Proxmox Server (Veda): Ryzen 7 3800XT | AsRock Rack X470D4U | Corsair H80i v2 | 64GB Micron DDR4 ECC 3200MT/s | 4x 10TB WD Whites / 4x 14TB Seagate Exos / 2× Samsung PM963a 960GB SSD | Seasonic Prime Fanless 500W | Intel X540-T2 10G NIC | LSI 9207-8i HBA | Fractal Design Node 804 Case (side panels swapped to show off drives) | VMs: TrueNAS Scale; Ubuntu Server (PiHole/PiVPN/NGINX?); Windows 10 Pro; Ubuntu Server (Apache/MySQL)


Media Center/Video Capture (Jesta Cannon): Ryzen 5 1600X | ASRock B450M Pro4 R2.0 | Noctua NH-L12S | 16GB Crucial DDR4 3200MT/s CAS-22 | EVGA GTX750Ti SC | UMIS NVMe SSD 256GB / Seagate 1.5TB HDD | Corsair CX450M | Viewcast Osprey 260e Video Capture | Mellanox ConnectX-2 10G NIC | LG UH12NS30 BD-ROM | Silverstone Sugo SG-11 Case | Sony XR65A80K

 

Camera: Sony ɑ7II w/ Meike Grip | Sony SEL24240 | Samyang 35mm ƒ/2.8 | Sony SEL50F18F | Sony SEL2870 (kit lens) | PNY Elite Perfomance 512GB SDXC card

 

Network:

Spoiler
                           ┌─────────────── Office/Rack ────────────────────────────────────────────────────────────────────────────┐
Google Fiber Webpass ────── UniFi Security Gateway ─── UniFi Switch 8-60W ─┬─ UniFi Switch Flex XG ═╦═ Veda (Proxmox Virtual Switch)
(500Mbps↑/500Mbps↓)                             UniFi CloudKey Gen2 (PoE) ─┴─ Veda (IPMI)           ╠═ Veda-NAS (HW Passthrough NIC)
╔═══════════════════════════════════════════════════════════════════════════════════════════════════╩═ Narrative (Asus USB 2.5G NIC)
║ ┌────── Closet ──────┐   ┌─────────────── Bedroom ──────────────────────────────────────────────────────┐
╚═ UniFi Switch Flex XG ═╤═ UniFi Switch Flex XG ═╦═ Byarlant
   (PoE)                 │                        ╠═ Narrative (Cable Matters USB-PD 2.5G Ethernet Dongle)
                         │                        ╚═ Jesta Cannon*
                         │ ┌─────────────── Media Center ──────────────────────────────────┐
Notes:                   └─ UniFi Switch 8 ─────────┬─ UniFi Access Point nanoHD (PoE)
═══ is Multi-Gigabit                                ├─ Sony Playstation 4 
─── is Gigabit                                      ├─ Pioneer VSX-S520
* = cable passed to Bedroom from Media Center       ├─ Sony XR65A80K (Google TV)
** = cable passed from Media Center to Bedroom      └─ Work Laptop** (Startech USB-PD Dock)

 

Retired/Other:

Spoiler

Laptop (Rozen-Zulu): Sony VAIO VPCF13WFX | Core i7-740QM | 8GB Patriot DDR3 | GT 425M | Samsung 850EVO 250GB SSD | Blu-ray Drive | Intel 7260 Wifi (lived a good life, retired with honor)

Testbed/Old Desktop (Kshatriya): Xeon X5470 @ 4.0GHz | ZALMAN CNPS9500 | Gigabyte EP45-UD3L | 8GB Nanya DDR2 400MHz | XFX HD6870 DD | OCZ Vertex 3 Max-IOPS 120GB | Corsair CX430M | HooToo USB 3.0 PCIe Card | Osprey 230 Video Capture | NZXT H230 Case

TrueNAS Server (La Vie en Rose): Xeon E3-1241v3 | Supermicro X10SLL-F | Corsair H60 | 32GB Micron DDR3L ECC 1600MHz | 1x Kingston 16GB SSD / Crucial MX500 500GB

Link to comment
Share on other sites

Link to post
Share on other sites

37 minutes ago, AbydosOne said:

The short answer is that you have your row count and your column count switched.

I am sorry,

what do you mean by that?

Link to comment
Share on other sites

Link to post
Share on other sites

20 minutes ago, rubendelope said:

I am sorry,

what do you mean by that?

 

int [][] m1 = {{1,2,3},{1,2,3}};

// column -  1   2   3
// row 1 - [ 1 | 2 | 3 ]
// row 2 - [ 1 | 2 | 3 ]

int row1 = m1.length; // this asks "how many items are in the outside array", which is counting how many rows there are
int column2 = m2[0].length; // this asks "how many items are in the inside array", which is counting how many columns there are

// all good so far, it seems

 

I might have been wrong initially... let's dig into your for-loops...

 

for(x = 0; x < row1 ; x++); // for-loop syntax should have {...} around code to execute after it

// example:

for(x = 0; x < row1 ; x++) {
	System.out.println(x);
}

 

I think that might be more of your issue... try fixing your syntax issues and report back.

 

m3[x][y] += m1[x][k] * m2[k][y]; // if column != row count, "k" will go outside (what your issue refers to) or fail 
                                 // to cover the range of either "rows" or "columns" here

 

...but I think that line above is the issue here.

Main System (Byarlant): Ryzen 7 5800X | Asus B550-Creator ProArt | EK 240mm Basic AIO | 16GB G.Skill DDR4 3200MT/s CAS-14 | XFX Speedster SWFT 210 RX 6600 | Samsung 990 PRO 2TB / Samsung 960 PRO 512GB / 4× Crucial MX500 2TB (RAID-0) | Corsair RM750X | Mellanox ConnectX-3 10G NIC | Inateck USB 3.0 Card | Hyte Y60 Case | Dell U3415W Monitor | Keychron K4 Brown (white backlight)

 

Laptop (Narrative): Lenovo Flex 5 81X20005US | Ryzen 5 4500U | 16GB RAM (soldered) | Vega 6 Graphics | SKHynix P31 1TB NVMe SSD | Intel AX200 Wifi (all-around awesome machine)

 

Proxmox Server (Veda): Ryzen 7 3800XT | AsRock Rack X470D4U | Corsair H80i v2 | 64GB Micron DDR4 ECC 3200MT/s | 4x 10TB WD Whites / 4x 14TB Seagate Exos / 2× Samsung PM963a 960GB SSD | Seasonic Prime Fanless 500W | Intel X540-T2 10G NIC | LSI 9207-8i HBA | Fractal Design Node 804 Case (side panels swapped to show off drives) | VMs: TrueNAS Scale; Ubuntu Server (PiHole/PiVPN/NGINX?); Windows 10 Pro; Ubuntu Server (Apache/MySQL)


Media Center/Video Capture (Jesta Cannon): Ryzen 5 1600X | ASRock B450M Pro4 R2.0 | Noctua NH-L12S | 16GB Crucial DDR4 3200MT/s CAS-22 | EVGA GTX750Ti SC | UMIS NVMe SSD 256GB / Seagate 1.5TB HDD | Corsair CX450M | Viewcast Osprey 260e Video Capture | Mellanox ConnectX-2 10G NIC | LG UH12NS30 BD-ROM | Silverstone Sugo SG-11 Case | Sony XR65A80K

 

Camera: Sony ɑ7II w/ Meike Grip | Sony SEL24240 | Samyang 35mm ƒ/2.8 | Sony SEL50F18F | Sony SEL2870 (kit lens) | PNY Elite Perfomance 512GB SDXC card

 

Network:

Spoiler
                           ┌─────────────── Office/Rack ────────────────────────────────────────────────────────────────────────────┐
Google Fiber Webpass ────── UniFi Security Gateway ─── UniFi Switch 8-60W ─┬─ UniFi Switch Flex XG ═╦═ Veda (Proxmox Virtual Switch)
(500Mbps↑/500Mbps↓)                             UniFi CloudKey Gen2 (PoE) ─┴─ Veda (IPMI)           ╠═ Veda-NAS (HW Passthrough NIC)
╔═══════════════════════════════════════════════════════════════════════════════════════════════════╩═ Narrative (Asus USB 2.5G NIC)
║ ┌────── Closet ──────┐   ┌─────────────── Bedroom ──────────────────────────────────────────────────────┐
╚═ UniFi Switch Flex XG ═╤═ UniFi Switch Flex XG ═╦═ Byarlant
   (PoE)                 │                        ╠═ Narrative (Cable Matters USB-PD 2.5G Ethernet Dongle)
                         │                        ╚═ Jesta Cannon*
                         │ ┌─────────────── Media Center ──────────────────────────────────┐
Notes:                   └─ UniFi Switch 8 ─────────┬─ UniFi Access Point nanoHD (PoE)
═══ is Multi-Gigabit                                ├─ Sony Playstation 4 
─── is Gigabit                                      ├─ Pioneer VSX-S520
* = cable passed to Bedroom from Media Center       ├─ Sony XR65A80K (Google TV)
** = cable passed from Media Center to Bedroom      └─ Work Laptop** (Startech USB-PD Dock)

 

Retired/Other:

Spoiler

Laptop (Rozen-Zulu): Sony VAIO VPCF13WFX | Core i7-740QM | 8GB Patriot DDR3 | GT 425M | Samsung 850EVO 250GB SSD | Blu-ray Drive | Intel 7260 Wifi (lived a good life, retired with honor)

Testbed/Old Desktop (Kshatriya): Xeon X5470 @ 4.0GHz | ZALMAN CNPS9500 | Gigabyte EP45-UD3L | 8GB Nanya DDR2 400MHz | XFX HD6870 DD | OCZ Vertex 3 Max-IOPS 120GB | Corsair CX430M | HooToo USB 3.0 PCIe Card | Osprey 230 Video Capture | NZXT H230 Case

TrueNAS Server (La Vie en Rose): Xeon E3-1241v3 | Supermicro X10SLL-F | Corsair H60 | 32GB Micron DDR3L ECC 1600MHz | 1x Kingston 16GB SSD / Crucial MX500 500GB

Link to comment
Share on other sites

Link to post
Share on other sites

Most languages start index at 0, not 1. So a 2 element array would have element 0 and element 1. So when you iterate through the array, if you are off by 1 you will get an index out of range or out of bounds error.

 

For example, if there are 2 elements in the array and your iterator is 3, since there is no element at index 3 in the array, you get the index out of bounds/range error.

 

You should check that your iterator variables x,y,k are never bigger than the number of elements of the array they are working with.

 

 

23+ yrs IT experience

 

MAIN SYSTEM

Operating System

Windows 10 Pro x64 21H1

Case

Antec Three Hundred Two Gaming

CPU

AMD Ryzen 9 3900X 3.8GHz 12-Core 24-Thread

Motherboard

Asus ROG Strix X570-E Gaming

RAM

G.Skill Trident Z RGB Series 32GB

(2 x 16GB) DDR4 3200 (PC4-25600)

Graphics Card

Asus Nvidia Geforce RTX 2060 Overclocked (Factory) 6GB GDDR6

Dual-Fan EVO Edition

Storage

2 × Samsung 970 EVO Plus Nvme (M.2 2280) SSD 1TB

2 × Samsung 860 QVO SATA III 6.0Gb/s SSD 1TB (RAID1 Array 1)

2 × Hitachi UltraStar HDS721010CLA330 7200RPM SATA III 3.0Gb/s 1TB (RAID1 Array 2)

PSU

Thermaltake Toughpower GF1 850W 80+ Gold

Optical Drive

LG WH16NS40 Super Multi Blue Internal SATA 16x Blu-ray Disc/DVD/CD Rewriter

Displays

HP w2408 widescreen 16:10 1920x1200 @60Hz

HP w2207 widescreen 16:10 1680x1050 @60Hz

Keyboard/Mouse

Logitech MK200 Wired Keyboard/Mouse Combo Kit

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, rubendelope said:

for(x = 0; x < row1 ; x++); //columns that is why y goes until 3
for(y = 0; y < column2; y++);
m3[x][y] = 0;

You made a mistake here, you forgot the brackets. This way the two loops just cycle and increment x and y until they are equal to the length element, which is out of bound for indexing, and THEN you set m3[x][y] (which now means m3[2][3]) to 0. Remember, the loop breaks when the check is no longer true.

 

Instead you want to nest that command inside the loops using brackets:

for(x = 0; x < row1 ; x++){ //columns that is why y goes until 3
  for(y = 0; y < column2; y++){
    m3[x][y] = 0;
  }
}

 

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to comment
Share on other sites

Link to post
Share on other sites

19 minutes ago, Sauron said:

You made a mistake here, you forgot the brackets.

Alternatively, you could remove the semicolons after the for-statements:

for (x = 0; x < row1; x++)         // no semicolon here
    for (y = 0; y < column2; y++)  // or here
        m3[x][y] = 0;              // this is now part of the same statement (i.e. the loops)

Written this way, the line following the for-loop is part of the same statement. Strictly speaking, curly braces are only needed when there are multiple statements inside the for-loop. However, for the sake of readability, I would absolutely recommend to go with the style that @Sauron used.

 

It is easy to miss that someone accidentally added those semicolons. Braces make it much more visible what is part of the loop and what isn't. You can also extend the loop later on without having to remember that you now must use braces instead of them being optional. So braces can help avoid bugs like this.

Remember to either quote or @mention others, so they are notified of your reply

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×