Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
For the question below use 2d array greetings seen below:
![image of 2D array][1]
"bob"
"joe"
"billy"
"george"
"janise"
"dell"
The code that I wrote is:
public class c
{
// instance variables - replace the example
below with your own
private int columns; int rows;
/**
* Constructor for objects of class c
*/
public c()
{
int columns = 2;
int rows = 3;
String[][] newArray = new String[columns][rows];
newArray[0][0] = "bob";
newArray[0][1] = "joe";
newArray[1][0] = "billy";
newArray[1][1] = "george";
newArray[1][2] = "janise";
newArray[2][2] = "dell";
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
System.out.println(newArray[i][j]);
}
}
}
}
When creating the array, you need to use new String[rows][columns], not new String[columns][rows].
The third row should then be assigned using newArray[2][0] and newArray[2][1].
You can use an array initializer to create the array in a much easier way:
String[][] newArray = { { "hello", "ni hao" },
{ "konnichiwa", "hola" },
{ "guten tag", "bonjour" } };
So... your code is close to being correct.
The first mistake is that you mixed the columns and rows: You are defining your array to have two columns, but in the end, you are using three (0, 1, 2).
The second mistake is in the last two assignments: You really did confuse the numbering here.
Your finished constructor should look like this:
int columns = 2;
int rows = 3;
String[][] newArray = new String[rows][columns];
newArray[0][0] = "hello";
newArray[0][1] = "ni hao";
newArray[1][0] = "konnichiwa";
newArray[1][1] = "hola";
newArray[2][0] = "guten tag";
newArray[2][1] = "bonjur";
for(int i = 0; i < rows; i++){
for(int j = 0; j < columns; j++){
System.out.println(newArray[i][j]);
}
}
Related
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 5 years ago.
Recently I've been slamming by head against this piece of code:
for(int i = 0; i < cols; i++) {
for(int j = 0; j < rows; j++) {
SqrTileNormal temp = new SqrTileNormal(i, j, this, ID.Tile);
setTile(temp);
}
}
//additional info
public void setTile(Tile tile) {
int xPosGrid = tile.getXPosGrid();
int yPosGrid = tile.getYPosGrid();
System.out.println("Coords: (" + xPosGrid + ", " + yPosGrid + ")");
this.tiles.get(xPosGrid).set(yPosGrid, tile);
}
//how the nested array looks like.
protected List<ArrayList<Tile>> tiles;
It's part of a constructor which is supposed to fill a two-dimensional array with SqrTileNormal. I have found what the issue is: Every iteration of the for loop keeps rewriting the previous iterations, so they all end up whit the same xPosGrid and you see this:
I have been trying some things but I usually keep the overwriting issue and I don't want to make it unnecessarily complicated and long. Does anyone know of a solution to this problem? Any help would be appreciated!
Edit:
What I had:
[[null, null, null...][null, null, null...][(null, null, null...]
What I want:
What I get:
[[(10, 0),(10, 1),(10, 2)...][(10, 0),(10, 1),(10, 2)...][(10, 0),(10, 1),(10, 2)]...]
The problem is in how you initialize this.tiles, you are not showing how you do it but possibly you are setting just 1 array list, so in fact you have ten times the same value list.
Your this.tiles init should look like:
private static List<List<Tile>> getListOfLists() {
int numcol = 5;
int numrow = 5;
List<List<Tile>> bidiArray = new ArrayList<>();
for (int i = 0; i < numcol; i++) {
List<String> sublist = new ArrayList<>();
bidiArray.add(sublist);
for (int j = 0; j < numrow; j++) {
sublist.add(null);
}
}
return bidiArray;
}
But in fact, dealing with a fixed number of columns and rows I would rather use arrays such as :
Tile[][] bidiArray = new Tile[numcol][numrow];
And then set it like this:
this.tiles[xPosGrid][yPosGrid]= tile;
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
My problem is to add the sum of each row in a 2d array, and put those values in a new 1d array.
This is my code
public static int[] sumRow(int[][] N){
int[] rowSum = new int[N.length];
for(int i = 0; i<N.length;i++){
for(int j = 0; j<N[i].length; j++){
rowSum[i] = N[i][j] + N[i+1][j+1];
}
}
return rowSum;
}
But it is not working, please help.
public static int[] sumRow(int[][] N){
int[] rowSum = new int[N.length];
for(int i = 0; i<N.length;i++){
rowSum[i] = 0; //<= initialize value
for(int j = 0; j<N[i].length; j++){
rowSum[i] += N[i][j]; //<= sum of row
}
}
return rowSum;
}
You have written most of the code right but you need to add each row so, you need to add N[0][1], ....N[0][N[0].length - 1] in row 0. Now just plug i and j values and write on paper to be much clear.
Try this.
public static int[] sumRow(int[][] N) {
return Stream.of(N)
.mapToInt(a -> IntStream.of(a).sum())
.toArray();
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
i have program that makes operations on string and this is the principal function of one of those operations,this works perfectly,but it is not efficient:
private void printString(ArrayList<String> operations, ArrayList<String> set) {
int numerOfStrings = 0;
int numberOfletters = 0;
String toPrint = operations.get(1);
outOfLoop: for (int i = 0; i < set.size(); i++) {
String[] toFind = set.get(i).split(" ");
for (int k = 0; k < toFind.length; k++) {
if (toPrint.equals(toFind[k])) {
String[] splited = set.get(i).split(" ");
for (int j = 0; j < splited.length; j++) {
numberOfletters += splited[j].length();
}
numerOfStrings = splited.length;
break outOfLoop;
}
}
}
System.out.println(numerOfStrings + " " + numberOfletters);
}
explanation:
this function takes as parameter a an arrayList of operations, and an arraylist of set:
for the arraylist of operations i get always a specific position so,i don't iterate , it is always O(1)
for the arrayList of set i have to iterate,or rather, as I think of that to proceed:
so , for example, if have as operation print foo i have to do these steps:
first of all i have to find where foo is :
inside set i can have this situation:
position 1 : {car tree hotel}
...
position n : {foo lemon coffee}
when i find the string foo i have to print the number of strings inside that position and the number of letters of each string,so in this case i will print :
3(number of strings) 14(number of letters)
my program works,and also this function works, but it is a nasty solution,and not efficent,what do you think, how can I improve in efficiency in my program?
question inserted on code Review
try this version:
private void printString(ArrayList<String> operations, ArrayList<String> set) {
int numerOfStrings = 0;
int numberOfletters = 0;
String toPrint = operations.get(1);
for (String s : set) {
if (s.contains(toPrint)) {
String[] arr = s.split(" ");
numerOfStrings = arr.length;
numberOfletters = s.length() - (numerOfStrings - 1);
break;
}
}
System.out.println(numerOfStrings + " " + numberOfletters);
}
The 'worst' case here would be O(n2), because of for loop O(n) and contains O(n).
hope it helps.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a doubt.
I am developing the following code which will be a multplication table for a number that you manually introduce. What I cannot get is to print the table. I don't know what is going on because as far as I know, all the code is right written.
public class Tabla
{
public static void main (String[] args)
{
int n=4;
Tabla table = new Tabla ();
int dato [];
dato=table.producto(n);
for (int j=1;j<=10;j++)
{System.out.println(dato[j]);}
}
public int [] producto(int num)
{
int a[]={'0'};
for (int i=1;i<=10;i++)
{a[i]=num*i;}
return a;
}
}
Any ideas??
Thanks in advance!
**I changed the code to:
public class Tabla
{
public static void main (String[] args)
{
int n=4;
int j;
Tabla table = new Tabla ();
int dato[]=new int [10];
dato=table.producto(n);
for (j=0;j<10;j++)
{System.out.println(dato[j]);
}
}
public int [] producto(int num)
{
// make a 10-element array
int a[] = new int[10];
// fill up the array with products
for (int i = 0; i < 10; i++)
{a[i] = num * (i+1); }
return a;
}
}
Works like a charm!
Now I am wondering why the compiler threw the "ArrayIndexOutOfBoundsException" when I had the for cycle as for (int i = 1; i <=10; i++)
Thanks for the help! :D
Building off of Wasserman's answer, what you should have written is as follows:
public int[] producto(int num)
{
// make a 10-element array
int a[] = new int[10];
// fill up the array with products
for (int i = 0; i < 10; i++)
a[i] = num * (i + 1);
return a;
}
You created a single-element array, whereas you wanted a 10-element array to fill up.
Two problems:
int a[]={'0'};
This line creates an array a with only one element -- not the 11 you're trying to fill -- and moreover, that one element is the ASCII code for the character 0, which is almost certainly not what you want.
Not sure if my mind is just numb or I am just stupid, but for some reason the logic behind this escapes me. Essentially in an android app I am pulling CSV information through a PHP script. That information gets displayed like
value00,value01,value02,value03,value04;value10,value11,value12,value13,value14;value20, etc...
now I want to set up a two dimensional array where thisArray[0][0] = value00, thisArray[1][1] = value11, thisArray[1][4] = value14, etc. The code I have will split by the ";" but I can't figure out how to then split that array into a two dimensional array set up the way I want. This is what I have: (httpMessage is the string containing the above information)
String[][] secondSplit;//
String[] firstSplit;//
String currvalue;//
firstSplit = httpMessage.split(";");
for(int i=0; i<firstSplit.length; i++) {
Log.d("EFFs" + Integer.toString(i),firstSplit[i]);
}
LogCat shows the desired behavior, EFFs0 = line 1, EFFs1 = line 2, just the way I want it. But now, how do I get that second dimension? Also, since I am 100% sure this is a dumb question with an easy answer I'll throw in another, is there an easy way to tell if a string is a number?
You could do the following:
secondSplit = new String[firstSplit.length][];
for(int i=0; i<firstSplit.length; i++){
secondSplit[i] = firstSplit[i].split(",");
}
Pretty sure that would work. Let me know if it doesn't! Hope that helps!
If you know how many rows and columns there are you can use the Scanner class like this (recently learned this from this answer):
Scanner sc = new Scanner(input).useDelimiter("[,;]");
final int M = 5;
final int N = 2;
String[][] matrix = new String[M][N];
for (int r = 0; r < M; r++) {
for (int c = 0; c < N; c++) {
matrix[r][c] = sc.next();
}
}
//Just to see that it worked
for(String[] row : matrix) {
for(String col : row) {
System.out.print(col+",");
}
System.out.println();
}