I am looking for the dimensions of a 2d array. Not the fixed values assigned to the array, but the values containing integers. Example:
int a[][] = new int[4][5];
a[1][1] = 1;
a[1][2] = 2;
a[1][3] = -2;
a[1][4] = 0;
a[2][1] = -3;
a[2][2] = 4;
a[2][3] = 7;
a[2][4] = 2;
a[3][1] = 6;
a[3][2] = 0;
a[3][3] = 3;
a[3][4] = 1;
Only 3 variables are used out of 4, and 4 variables used out of 5. How can you tell what is actually there versus what is assigned to be there?
array.length;
array[0].length;
The previous code will only give you the fixed variable assigned to the array. But what if your not using all the variables? In other words I am looking for an output of 3 for columns and 4 for rows.
In your code example, you are using all variables in the array. Just because you haven't assigned anything to them, they are still sitting there.
If you want to determine whether or not you've assigned a value to each element in the array, you need to initialize everything to a default value, and then just compare against the default value.
A variation on that option is to declare them as int?, which is a nullable int. That would allow you to set everything to null, and then you'll know that the elements that are no longer null have had a value assigned to them.
You can't do it dynamically. Once you've initiated your matrix like that (new int[4][5]) you have and matrix of 0.
You must initiate the matrix ant set an invalid value to all posistions, something like -1 or whatever you wan't and iterate over it to discover the result
// using Integer instead of int, which is a nullable object
Integer a[][] = new Integer[4][5];
int cnt1 = 0;
for(int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
if(a[i][j] != null) {
cnt1++;
}
}
}
System.out.println(cnt1 + " array indices are non-null.");
// using int
int b[][] = new int[4][5];
for(int i = 0; i < b.length; i++) {
for(int j = 0; j < b[i].length; j++) {
b[i][j] = -9999;
}
}
int cnt2 = 0;
for(int i = 0; i < b.length; i++) {
for(int j = 0; j < b[i].length; j++) {
// pick a value that will never be assigned
if(b[i][j] != -9999) {
cnt2++;
}
}
}
System.out.println(cnt2 + " array indices are not -9999.");
Related
I would like to remove a particular number from the array
Integer[] arr = new Integer[7];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
Collections.shuffle(Arrays.asList(arr));
This is creating numbers from 0-7
But I dont need 0,I need value from 1-7
The first value written into your array is 0 because you initialize i with 0 in the for loop.
Therefore your loop will only insert the values 0 - 6.
Change this initialisation to i = 1 and in addition you also need to change the condition of the for loop to arr.length + 1 or i <= arr.length, so it will count up to 7.
Integer[] arr = new Integer[7];
for (int i = 1; i < arr.length + 1; i++) {
arr[i] = i;
}
What you also can do instead of changing the loop itself, is to change the loop body. Just add 1 to i when assigning it to arr[i]:
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
In this case i will count from 0 to 6, and assign 1 to 7 to your array
Change your int i = 0 to int i = 1 like this:
Integer[] arr = new Integer[7];
for(int i = 1; i <8; i++){
int value = i-1;
arr[value] = i;
}
Collections.shuffle(Arrays.asList(arr));
for(int i = 0; i < arr.length; i++){
System.out.println("Result:"+arr[i]);
}
Console message:
Result:7
Result:2
Result:6
Result:5
Result:4
Result:1
Result:3
So I have been working on this problem for a while now. I keep getting an ArrayIndexOutOfBoundsException but I am unable to locate where the issue lies. If someone could point me in the right direction, I would really appreciate it! Thanks!
public class Answer {
public static void main(String[] args){
double[] y = {23, 11.1, 50.4};
double[] x = {22.2, 46, 100.0};
Answer answer = new Answer();
answer.answer(y, x);
}
public static int answer(double[] y, double[] x) {
int result = 0;
double percent_1, percent_2;
double[] compareList_1 = new double[x.length];
double[] compareList_2 = new double[y.length];
// Calculate percent of first 2 x value array items with y
// all y values. Store the results in a seperate list.
for(int i = 0; i < x.length; i++){
percent_1 = compare(y[i], x[0]);
percent_2 = compare(y[i], x[1]);
compareList_1[i] = percent_1;
compareList_2[i] = percent_2;
}
// Compare those lists to find common number
// There you have your answer.
result = (int)compareLists(compareList_1, compareList_2);
return result;
}
// Calculates percentage from x and y values
public static double compare(double y, double x){
double result = 1 - (y/x);
return result;
}
// Finds common value in lists
public static double compareLists(double[] list_1, double[] list_2){
for(int i = 0; i < list_1.length + 1; i++){
for(int j = 0; j < list_2.length + 1; j++){
if(list_1[i] == list_2[j]){
return list_1[i];
}
}
}
// Just cus this shouldn't ever return.
return 100;
}
}
In your iteration (compareLists), you should use 'length' (not length + 1)
for(int i = 0; i < list_1.length; i++)
for(int j = 0; j < list_2.length; i++)
I think the problerm is in
for(int i = 0; i < list_1.length + 1; i++){
for(int j = 0; j < list_2.length + 1; j++){
i < list_1.length + 1 or j < list_2.length + 1 change it to
for(int i = 0; i < list_1.length; i++){
for(int j = 0; j < list_2.length ; j++){
remove +1 from each condition.For j < list_2.length + 1 the list_2.length will give you length of array ie lastIndex +1 and you are adding another +1 in it causing loop condition to be j<lastIndex +1 giving you index error on the last iteration of loop in the line if(list_1[i] == list_2[j]){ for list_2[j]
Also in answer method you declare array by
double[] compareList_1 = new double[x.length];
double[] compareList_2 = new double[y.length];
and in the loop you are iterating upto x.length if x.length is greater than y.length the you can get the Index error in compareList_2[i] = percent_2;(inside the loop) because its length is y.length.
I apologize if I'm not clear. I'm new to programming. So lets say I have a char[10][10]. And there are two+ chars I want to assign at intervals for example i[0][0] to i[5][7] have Y and the rest have N. How would I do that if its possible? I've been trying to figure it out for 6+ hours.
One possible solution would be to have a 'for' block that goes through the rows and another 'for' block that goes through the columns. it could be something like
char[] arr= {'Y','N'};
int counter = 0; // <- these are optional depending on what you choose below
for(int j=0;j<10;j++){
for(int k=0;k<10;k++){
// i[j][k]= here you should assign the value
counter++;
}
}
The way to assign the value depends on what you want to do. If you want to have it to generate randomly you can do something like i[j][k]= arr[(int)(Math.random()*2)] or if you want to have it alternate between Y and N you could have a counter variable and assign i[j][k]= arr[counter%2] . If you want to assign the first half to 'Y' and the other half to 'N' i[j][k]= (counter<=50)?'Y':'N';. And the particular case you ask would be i[j][k]= (j<=5 && k<=7)?'Y':'N';It really depends much on what you want to do
This can be done with loops.
for(int i = 0; i < 5; i++){
for(int j = 0; j < 7; j++){
i[i][j] = 'N';
}
for(int j = 7; j < 10; j++){
i[i][j] = 'Y';
}
}
for(int i = 5; i < 10; i++){
for(int j = 0; j < 10; j++){
i[i][j] = 'Y';
}
}
char[][] theArray = new char[10][10]
upToX = 5; // limit for rows
upToY = 7; // limit for columns
for(int i = 0; i < 10; i++ ){
for(int j = 0; j< 10; j++ ){
if((i+1)*(j+1) <= (upToX+1)*(upToY+1)){
theArray[i][j] = 'Y';
}
else{
theArray[i][j] = 'N';
}
}
}
Try using for-loops and if-else. Since you are looking for yes/no type values, I just used boolean type in my example
boolean[][] arr = new boolean[10][10];
for(int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[i].length; j++) {
if(i < 6 && j < 8)
arr[i][j] = true;
else
arr[i][j] = false;
}
}
I have an array called blockHeights, which contains 3 values inside of it, namely 1,2,3. So blockHeights[0] is equal to 1.
I also have a loop:
for (int i = 1; i <= blockHeights.length; i++)
In the first time around the loop, I want to create a variable called totalBlockHeights where it is
int totalBlockHeights = blockHeights[0] + blockHeights [1] + blockHeights [2];
However, in the next loop I want that variable to change, so that it only adds blockHeights[1] and blockHeights[2] together, ignoring blockHeights[0].
How would I go about doing this?
Try the following (I'm assuming the third iteration should only include blockHeights[2], following the pattern):
for (int i = 1; i <= blockHeights.length; i++) {
int totalBlockHeights;
for (int j = i - 1; j < blockHeights.length; j++) { // all block heights from here onwards
totalBlockHeights += blockHeights[j];
}
// do whatever
}
Well, if you want the sum of your array, and the sum of the array without first value
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++){
totalBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println("totalBlockHeights without first value = " + (totalBlockHeights - blockHeights[0]));
this way you only loop once
Try following code:
public class Loop {
public static void main(String[] argv) {
int[] blockHeights = new int[] {1, 2, 3};
int totalBlockHeights = 0;
for(int i = 0; i < blockHeights.length; i++) {
totalBlockHeights = 0;
for(int j = i; j < blockHeights.length; j++) {
totalBlockHeights += blockHeights[j];
}
System.out.println(totalBlockHeights);
}
}
}
int[] blockHeights = new int[] { 1, 2, 3 };
int totalBlockHeights = 0;
int customBlockHeights = 0;
for (int i = 0; i < blockHeights.length; i++) {
totalBlockHeights += blockHeights[i];
if (i == 0) {
continue;
}
customBlockHeights += blockHeights[i];
}
System.out.println(totalBlockHeights);
System.out.println(customBlockHeights);
This will print:
6
5
You dont need two for to achieve that.
you can perform this on two for loop outer loop for (int i = 1; i <= blockHeights.length; i++), and in inner loop (take a variable j) you can do like int totalBlockHeights = totalBlockHeights + blockHeights[j], and for i<j, you can just continue the for loop.
as answered by btrs20
I'm working on a program that requires me to take in a 1-D String array from a file and turn it into a 2-D array. Taking in the array from the file works fine, but I can't get the second part to work.
The code I'm working with is:
char[][] array2 = new char [7][5];
for (int i = 0; i < array1.length; i++)
{
array2[i]= array[i].toCharArray();
}
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 7; j++)
{
System.out.println(array2[i][j]);
}
}
The array is supposed to print in a grid format, but is printing downward.
Any help is appreciated, thanks.
Use print instead of println in inner loop and after each loop print a blank line with println.
for (int i = 0; i < 7; i++) // see changes 5/7. You did "new char[7][5]" not [5][7]
{
for (int j = 0; j < 5; j++) // see changes 7/5
{
System.out.print(array2[i][j]);
}
System.out.println();
}
Update:
Following is a program that convert String array to 2D char array.
public class StringToChar {
public static void main(String[] args) {
String[] strArr = { "HELLO", "WORLD" };
char[][] char2D = new char[strArr.length][];
for (int i = 0; i < strArr.length; i++) {
char2D[i] = strArr[i].toCharArray();
}
for (char[] char1D : char2D) {
for (char c : char1D)
System.out.print(c + " ");
System.out.println();
}
}
}
few suggestions,
replace char[][] array2 = new char [7][5]; with char[][] array2 = new char [array1.length][]; (where array1 holds your strings), so your 2d array will have as many rows as you have strings
your loop
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 7; j++)
....
}
change to
for (int i = 0; i < array2.length; i++)
{
for (int j = 0; j < array2[i].length; j++)
....
another thing is if you want your string printed in rows, use System.out.print, and whenever you finished inner loop, print out'\n' character
You are using println, which is why each character is printed on its own line. You must use print instead.
Note that your initialization with
new char [7][5];
doesn't work as you expect because the inner arrays will be overwritten. Use
new char[7][]
for the same result, but more clarity as to your intent. Here
for (int i = 0; i < 5; i++)
for (int j = 0; j < 7; j++)
you have apparently reversed the order of indices: you are iterating only through 5 outer arrays, but you have allocated 7. What you should do instead is check against the actual array length and not a hardcoded number. The inner array may be of any size, after all (it depends on the string length).
Have a look at the String.toCharArray()
If it is printing downwards then change
for (int i = 0; i < 7; i++) //row loop
{
for (int j = 0; j < 5; j++) //column loop
{
System.out.print(array2[i][j]);
}
System.out.println(); //add here
}
Have a look at
formatting
print vs println