How to Fill 2D Array With the User'S Input

trying to fill a 2D array by user-input how to do it?

 public int[][] fill(){
int[][] data = new int[row][col];
Scanner in = new Scanner(System.in)

.....

return data;

}

You were declaring data array to length

 [0][0]

This is why the error is. Change the statement to above given code.

UPDATE

   public int[][] fill(){ 
int[][] data = new int[row][col];
Scanner in = new Scanner(System.in);
for(int row = 0; row< matrix.length; row++){
for(int col = 0 ;col< matrix[row].length; col++){
System.out.println("enter the elementss for the Matrix");
data[row][col] = in.nextInt();
} System.out.println();
}

for(int row = 0; row< matrix.length; row++){
for(int col = 0 ;col< matrix[row].length; col++){
System.out.println(data[row][col]);
}
System.out.println();
}
return data;

}

This will give you the desired output , add it to fill method before the return statement

How do I fill 2D Array with the user's input? [duplicate]

In your fillLgArray function where you stated: You didn't know what to put for indexing into the user input string, there is a formula for indexing a 1D array to treat it as a 2D array. There are two variations for this formula one is for Row - Colum major and the other is for Col - Row major. In your particular situation if the user enters this from the console:

abcdabcdabcdabcd

You can count on the fact that std::string is very much like std::vector only that std::string stores its contents as char_type and has special member functions for working with string manipulation other than that std::string at the core is basically a specialized version of std::vector. Both of these containers from the stl are wrappers around a contiguous block of memory that it allocates into dynamic memory. These containers wrap around a type [size] array and they grow dynamically.

So knowing this we can treat the text from the console "abcdabcdabcdabcd" as an 1D array of characters like this:

 0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15
[a] [b] [c] [d] [a] [b] [c] [d] [a] [b] [c] [d] [a] [b] [c] [d]

So when you are traversing a double for loop to index into a 2D array you have to mentally step through the loop on each iteration.

In C languages such as C & C++ the indexing of a flat 1D array to represent a 2D array is Row-Major so the formula is as follows:

for ( row = 0; row < 4; row++ ) {
for ( col = 0; col < 4; col ++ ) {
2darray[row][col] = 1darray[(row * row_size or width) + col];
}
}

This has already been asked and answered here! Map a 2D array onto a 1D

Here is a working example of your code in a minimal, complete verifiable example:

#include <string>
#include <iostream>
#include <exception>

#define LG_GRID = 4;

void fillArray( char grid[][LG_GRID] ) {
std::string userInput;
std::cout << "Please enter 16 characters\n";
std::cin >> userInput;

if( userInput.length() < 16 )
throw std::runtime_error( "Not enough characters" );
if( userInput.length() > 16 )
userInput = userInput.substr( 0, 16 );

std::cout << "You entered " << userInput << '\n';

for( int row = 0; row < LG_GRID; row++ ) {
for( int col = 0; col < LG_GRID; col++ ) {
// grid[row][col] = userInput[row * LG_GRID + col];
grid[row][col] = userInput.at( row * LG_GRID + col );
// both lines above will work however `string.at()` will throw an out of range exception.
}
}
}

void displayArray( char grid[][LG_GRID] ) {
for( int row = 0; row < LG_GRID; row++ ) {
for( int col = 0; col < LG_GRID; col++ ) {
std::cout << grid[row][col] << " ";
}
std::cout << '\n';
}
}

int main() {
try {
char myGrid[LG_GRID][LG_GRID];
fillArray( myGrid );
displayArray( myGrid );

} catch( const std::runtime_error& e ) {
std::cerr << e.what() << '\n';
return EXIT_FAILURE;
}

return EXIT_SUCCESS;
}

And using the input you described: "abcdabcdabcdabcd" The output on the console to this program is:

Please enter 16 characters
abcdabcdabcdabcd
You entered abcdabcdabcabcd
a b c d
a b c d
a b c d
a b c d

JAVA populate 2D array with user input

You should just do this;

double twoDm[][] = new double[4][4];
Scanner scan = new Scanner(System.in);
int i, j;

for (i = 0; i < 4; i++) {
System.out.print("Enter 4 numbers seperated by comma: ");
String[] line = scan.nextLine().split(",");
for (j = 0; j < 4; j++) {
twoDm[i][j] = Double.parseDouble(line[j]);

}
}

scan.close();

You should not forget to close the scanner too!

How to populate a 2D array in Java using user input?

I've edited your code and posted it below. This is a general outline of how to solve it:

  1. Use string.split("!") to separate your String by the delimiter '!'. This returns an array

  2. Then, use string.split("") to separate the String into individual characters

Code posted below:

private static int[][] parseTwoDimension(String strInput)
{
String[] rows = strInput.split("!");
int[][] arr = new int[rows.length()][];

for(int i = 0; i < rows.length; i++)
{
String[] elements = rows[i].split("");
int[] intElements = new int[elements.length];

for(int j = 0; j < elements.length; j++)
{
intElements[j] = Integer.parseInt(elements[j]);
}
arr[i] = intElements;
}
}

Let me know if this works. The string.split() function is really useful when parsing Strings into arrays

How to populate a 2d array via user input?

You can use .GetUpperBound(dimension) to obtain the maximum bound (in the example below, it will return 1 for each dimension) for a specific dimension. Once you've got that, you just need to go through each position (I'm assuming you just need to fill data at each position).

Here's a sample:

int[,] items = new int[2, 2];
int width = items.GetUpperBound(0) + 1;
int height = items.GetUpperBound(1) + 1;
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
string input;
int inputValue;
do
{
Console.WriteLine($"Please input value for ({x},{y}): ");
}
while (!int.TryParse(input = Console.ReadLine(), out inputValue));
items[x, y] = inputValue;
}
}

Or if you do need the user to be able to specify where the sales value goes, you can update your code to add some validation checks:

while (exit != "yes")
{
Console.WriteLine("What is the department number that you would like to enter sales for? Enter 9 to exit");
int departmentNo = int.Parse(Console.ReadLine());
if (departmentNo > departments.GetUpperBound(0) || departmentNo < 0)
{
Console.WriteLine("Please enter a valid department number.");
continue;
}
Console.WriteLine("What day would you like to enter sales for?");
int input = int.Parse(Console.ReadLine());
if (input > departments.GetUpperBound(1) || input < 0)
{
Console.WriteLine("Please enter a valid input.");
continue;
}

Console.WriteLine("Enter sales");
if (!decimal.TryParse(Console.ReadLine(), out decimal value))
{
Console.WriteLine("Please enter a valid sales figure.");
continue;
}
departments[departmentNo, input] = value;
Console.WriteLine("If you are finished, enter yes");
exit = Console.ReadLine();
}

You probably want to change it to be similar to my example above so that you don't have to restart the entire loop again if the input is bad.

How to fill 2D array using input (scanner method) without spaces

You're problem is that you defined the variable l in the nested for loop. Consequently, when that loop returns, l is deleted.

What you would need to do is define l before the first loop, that way its scope is the whole method.

...
char[][] TikTakToe = new char[3][3];
System.out.print("Enter cells: ");
String enter = scanner.next();
int l = 0; // <-- **I moved the declaration here**
for (int i = 0; i < TikTakToe.length; i++) {
for (int j = 0 /*removed the declaration from here*/; j < TikTakToe[i].length && l < enter.length(); j++, l++) {
TikTakToe[i][j] = enter.charAt(l);
}
}
...


Related Topics



Leave a reply



Submit