I've got a program where the user is giving the program the size of the array ie(the column and row size) and I am trying to give every position in the array the same value. I'm having an issue with my loop though, here it is.
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
//CODE
}
}
I can see that the issue is I am trying to give a value to a position that doesn't exist but I have no idea how to work around this issue. Any help would be appreciated :)
Try working with length, not with user input:
// ask user for sizes
int col = ...;
int row = ...;
// declare the array, let it be of type int
// it's the last occurence of "row" and "col"
int[][] data = new int[row][col];
// loop the array
for (int r = 0; r < data.length; ++r) { // <- not "row"!
int[] line = data[r];
for (int c = 0; c < line.length; ++c) { // <- not "col"!
// do what you want with line[c], e.g.
// line[c] = 7; // <- sets all array's items to 7
}
}
working with actual array's dimensions just prevent you from accessing non-existing items
From the code snippet you provided it seems you are fine. Maybe the array is not well initialized or you mismatched the row and column numbers. Try to use more specific variable names than 'i' and 'j'.
in java
try{
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
//CODE
}
}
}catch(IndexOutOfBoundsException exp){
System.out.printlv(exp.getMessage());
}
To begin, what makes you say that you "can see that the issue is I am trying to give a value to a position that doesn't exist"? What symptoms are you seeing that makes you believe this?
On the face of it, your code looks fine, however (and this is a big however) you have omitted the most important bits of code, viz the declaration of your 2D array, and the part inside the loop body where you assign the value to the array member. If you add these then I, or somebody else, may be able to help further.
Solution:
int matriz[][] = new int [row][col];
for(int i = 0; i <row; i++){
for(int j = 0; j < col; j++){
matriz[i][j] = 0;
}
}
//try this one
import java.util.Scanner; //Scanner class required for user input.
class xyz
{
public static void main(String ar[])
{
int row,col;
Scanner in=new Scanner(System.in); //defining Object for scanner class
System.out.println("Enter row");
row=in.nextInt();
System.out.println("Enter Column");
col=in.nextInt();
int mat[][]=new int[row][col]; //giving matrix size
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
mat[i][j]=0; //or any value decided by you
}
}
}
}
Related
I am attempting to solve a semi-difficult problem in which I am attempting to create an array and return a 3 dimensional array based on the parameter which happens to be a 2 dimensional int array. The array I'm attempting to return is a String array of 3 dimensions. So here is the code:
public class Displaydata {
static String[][][] makeArray(int[][] dimensions) {
String myArray[][][];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[][][] = new String[i][j][]; //getting error here.
}
}
return myArray;
}
static void printArray(String[][][] a) {
for (int i = 0; i < a.length; i++) {
System.out.println("\nrow_" + i);
for (int j = 0; j < a[i].length; j++) {
System.out.print( "\t");
for (int k = 0; k < a[i][j].length; k++)
System.out.print(a[i][j][k] + " ");
System.out.println();
}
}
}
public static void main(String[] args) {
int [][] dim = new int[5][];
dim[0] = new int[2];
dim[1] = new int[4];
dim[2] = new int[1];
dim[3] = new int[7];
dim[4] = new int[13];
dim[0][0] = 4;
dim[0][1] = 8;
dim[1][0] = 5;
dim[1][1] = 6;
dim[1][2] = 2;
dim[1][3] = 7;
dim[2][0] = 11;
for (int i = 0; i < dim[3].length;i++)
dim[3][i] = 2*i+1;
for (int i = 0; i < dim[4].length;i++)
dim[4][i] = 26- 2*i;
String[][][] threeDee = makeArray(dim);
printArray(threeDee);
}
}
As you can see from the source code, I'm getting an error when I try to create an instance of my 3-dimensional array which I'm attempting to return. I'm supposed to create a three dimensional array with the number of top-level rows determined by the length of dimensions and, for each top-level row i, the number of second-level rows is determined by the length of dimensions[i]. The number of columns in second-level row j of top-level row i is determined by the value of dimensions[i][j]. The value of each array element is the concatenation of its top-level row index with its second-level row index with its column index, where indices are represented by letters : ‘A’ for 0, ‘B’ for 1 etc. (Of course, this will only be true if the indices don’t exceed 25.) I don't necessarily know where I'm going wrong. Thanks!
You should not be initializing the array on every iteration of the loop. Initialize it once outside the loop and then populate it inside the loop.
static String[][][] makeArray(int[][] dimensions) {
String[][][] myArray = new String[25][25][1];
for (int i = 0; i < dimensions.length; i++) {
for (int j = 0; j < dimensions[i].length; j++) {
myArray[i][j][0] = i + "," + j;
}
}
return myArray;
}
I just plugged in values for the size of the first two dimensions, you will need to calculate them based on what you put in there. The 'i' value will always be dimensions.length but the 'j' value will be the largest value returned from dimensions[0].length -> dimensions[n-1].length where 'n' is the number of elements in the second dimension.
Also you will need to set up a way to convert the numbers in 'i' and 'j' to letters, maybe use a Map.
I guess you should initialize the array as
myArray = new String[i][j][]; //getting error here.
I think
myArray[][][] = new String[i][j][]; //getting error here.
should be:
myArray[i][j] = new String[5]; // I have no idea how big you want to go.
And then you can fill in each element of you inner-most array like such:
myArray[i][j][0] = "first item";
myArray[i][j][1] = "second string";
...
I think you should just change that line to:
myArray = new String[i][j][]; //look ma! no compiler error
Also, you would need to initialize myArray to something sensible (perhaps null?)
I am trying to find the longest series of horizontal O's in my 2d array and just print out the longest path. I don't see my logic error, I keep reading over this but don't see my error. I have been stuck here for about 2 days. I am thinking maybe there is something wrong with my finding max length statement? I get an out of bounds error on line 58 and 31. Any advice to what I'm doing wrong would be much appreciated.
public class game {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n][n];
System.out.println("ENTER A PATH: ");
for(int i = 0; i < mazeValue.length; i++ ){
for(int j = 0; j< mazeValue[i].length; j++){
mazeValue[i][j]= kbd.next().charAt(0);
}
}
printMaze(mazeValue);
horizontalPath(mazeValue);
}
public static void printMaze(char mazeValue[][])
{
System.out.println("MAZE");
for(int i = 0; i < mazeValue.length; i ++)
{
for (int j = 0; j < mazeValue[i].length; j++)
{
System.out.printf("%4c",mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void horizontalPath(char mazeValue[][])
{
int horizontalPath=0;
int maxHorizontalCount=0;
int i;
int j;
for(i= 0; i<mazeValue.length; i++){
for(j = 0; j<mazeValue[i].length; j++){
if(mazeValue[i][j]== 'o'){
horizontalPath = horizontalPath + mazeValue[i][j];
}
}
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
}
System.out.printf("Longest horizontal path row %d length %d",i,maxHorizontalCount);
}
}
I'm guessing you have some imports before your code which offsets the line numbers, and your problem is in line 47 in the code above:
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
This block is outside of your for loop over j. This means that by the time control gets here, j will be equal to n, thus causing an index out of bounds.
Also note you're not actually computing a max value of anything, just setting maxHorizontalCount to the value at [i][j]. To compute a max, you should do something like
maxHorizontalCount = maxHorizontalCount > mazeValue[i][j] ? maxHorizontalCount : mazeValue[i][j];
or use Math.max() of course.
My goal is to
Create a 5x5 array and fill it with random integers in the range of 1 to 25.
Print this original array
Process the array, counting the number of odds, evens, and summing all of the elements in the array.
Print the total odds, evens, and the sum.
Im not sure how to do it and my teacher is very confused and cannot help me. I was wondering if i could get some guidance.
Here is my code:
public class Processing {
public static void main(String[] args) {
Random Random = new Random();
int[][] Processing = new int[5][5];
for (int x = 0; x < 5; x++) {
int number = Random.nextInt(25);
Processing[x] = number;
}
for (int i = 0; i < 5; i++) {
Processing[i] = new int[10];
}
}
}
Please follow naming conventions for your variables. See here: http://en.wikipedia.org/wiki/Naming_convention_(programming)#Java
Anyways, you have to nest your loops as follows:
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j++) {
yourArray[i][j] = random.nextInt(25);
}
}
i is the row number and j is the column number, so this would assign values to each element in a row, then move on to the next row.
I'm guessing this is homework so I won't just give away the answer to your other questions, but to set you on the right track, here's how you would print the elements. Again, use two nested loops:
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j++) {
// print elements in one row in a single line
System.out.print(yourArray[i][j] + " ");
}
System.out.println(); //return to the next line to print next row.
}
A while I did an assignment creating a tictactoe program through eclipse. It works well enough, with me clicking empty boxes to place O's, and the program inputting X's afterward. However, I was using a pretty simple code for the placement of X's:
public int putX(){
for(int i=0; i<3;i++)
for(int j = 0;j<3;j++) {
if(position[i][j]==' ') {
position[i][j]='X';
return 0;
}
}
return -1; //some error occurred. This is odd. No cells were free.
}
Because of this, the X's are just placed in the row of each column, going down until the next column. Can someone show me a simple way to randomize this program?
What we want to do is generate an array of all the possible points, and pick one of those points at random. We use a for loop to iterate through all points in the 3x3 array, and add the valid ones to our temporary array, and then we choose a random index, and place an X there.
String[] list = new String[9]; // maximum 9 points
int size = 0;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(position[i][j] == ' ') {
list[size] = "" + i + j;
size++;
}
}
}
int index = (int) (Math.random() * (size+1));
position[Integer.parseInt(list[index].charAt(0))][Integer.parseInt(list[index].charAt(1))] = 'X';
Alternatively, instead of storing the x,y coordinates of the point in a String we could store them in a java.awt.Point like so:
Point[] list = new Point[9]; // maximum 9 points
int size = 0;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
if(position[i][j] == ' ') {
list[size] = new Point(i, j);
size++;
}
}
}
int index = (int) (Math.random() * (size+1));
position[list[index].getX()][list[index].getY()] = 'X';
As you can see, the code for using a Point is practically the same, but instead of parsing the coordinates out of the String, we can just access them directly from the Class.
You should also check to make sure that there are some elements left, by checking if size is still 0 after the for loop. If so, you should probably return -1 (what your existing code does). Otherwise, at the end of the whole code return 0.
I'm declaring a 2d Array with 100 rows and columns. Im trying to get the user to dictate the numbers that go into the array. Im supposed to store the values without storing them in a variable. This is what I have so far but I don't think this is correct
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int [][] nums = new int[100][100];
int digits;
for (int i = 0; i < nums.length; ++i)
{
int[scan.nextInt()][scan.nextInt()];
}
You'll need to use nested for loops for a 2-d array (one for rows and one for columns):
for (int i = 0; i < nums.length; ++i)
for (int j = 0; j < nums[i].length; ++j)
{
nums[i][j] = scan.nextInt();
}
Well, first of all, you are dealing with a two dimensional array, so you will need two loops, one for the rows and the other for the colums.
for(int i=0; i<100; i++)
{
for(int j=0;j<100;j++)
{
nums[i][j] = scan.nextInt();
}
}
This syntax - int[scan.nextInt()][scan.nextInt()]; is not even legal.