2D array Index out of range error

I’m trying to read 2D array values from keyboard

Hi @milad,
a couple of things, why are you trying to explicitly unwrap using the !? instead you can wrap them in an if which will not only unwrap but also give you error handling, like

if let input = readLine(), let vertexCount = Int(input) {
  // The main program comes here
}

The second thing is the way you are looping to get values, it is not clear on which way you are trying to get values. One would assume that since these are 2D values, you are expecting a x,y type of values instead here you are getting y (0…<max) x (0…<max) looped

Lastly, your main question, the code is crashing because you are trying to save data into an array that is not allocated.

this is the way you can get the code to work,

import Foundation

print("Enter vertex count > ", terminator: "")

if let input = readLine(), let vertexCount = Int(input) {
	var matrixAdjancy = [[Int]]()

	for i in 0..<vertexCount {
		var jArray:[Int] = []
		for j in 0..<vertexCount {
			print("Enter a number for \(i), \(j) > ", terminator: "")
			if let input = readLine(), let inputNumber = Int(input) {
				jArray.append(inputNumber)
			} else {
				print("*** Entered non number ***")
			}
		}
		matrixAdjancy.append(jArray)
	}

	print(matrixAdjancy)

} else {
	print(" You have not entered a valid number")
}

cheers,

Jayant

1 Like

This topic was automatically closed after 166 days. New replies are no longer allowed.