Count characters in a multidimensional array, Java - java

Below is my code:
public int maxTurns = 0;
public String[][] bombBoard = new String[9][9];
...
public void loadBombs()
{
//loadArray();
Random randomGen = new Random();
for (int u=1; u<=9; u++)
{
int randomRow = randomGen.nextInt(9);
int randomCol= randomGen.nextInt(9);
bombBoard[randomRow][randomCol] = "#";
}
//counting #'s -- setting variable
for (int d = 0; d < bombBoard[bombRow].length; d++)
{
for (int e = 0; e < bombBoard[bombCol].length; e++)
{
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
{
maxTurns++;
}
}
}
All I want to do is count the amount of (#)'s in the multidimensional array and assign it to a variable called maxTurns.
Probably very simple, just having a super hard time with it tonight. Too much time away from Java >.<

This line is equating the character # with the entire dth row or eth row. Does not make sense really because an array row cannot equal to a single character.
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
Instead, access a single cell like this
if (bombBoard[d][e].equals("#"))
And initialize maxTurns before counting i.e. before your for loop:
maxTurns = 0;

You need to change the if codition
if (bombBoard[d].equals("#") || bombBoard[e].equals("#"))
to
if (bombBoard[d][e].equals("#"))
You are using 2D Array, and do array[i][j] can populate its value for a gavin position.

do you want to count from the whole array or certain parts of the array only?
From the code snippet you gave above, I can't really tell how you iterate the array since I'm not sure what is
bombBoard[bombRow].length and bombBoard[bombCol].length
But if you want to iterate the whole array, think you should just use:
for (int d = 0; d < 9; d++) // as you declared earlier, the size of array is 9
{
for (int e = 0; e < 9; e++) // as you declared earlier, the size of array is 9
{
if (bombBoard[d][e].equals("#"))
{
maxTurns++;
}
}
}

Related

2D array filling | ArrayIndexOutOfBoundsException error

good afternoon! hi all! 1st time posting
for my assignment we are filling arrays using arithmetic and nested for loops. i've done a complete filling of a 2D array before using prime numbers, although i think i'm messing up somewhere..
when doing the line int priorNum = arr[r-1][c]; (see full code below) i run into an exception. i am trying to overwrite other lines in my array with this new equation, but must i be stopped by this utmost unchivalrous java error.
the error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 10
my array: int[][] arrayDimension = new int[10][6];
public static void populate2D (int[][] arr) {
//hardcode in values first :)
//and then peek up one row, but you can't go above the original row
arr[0][1] = 10;
arr[0][2] = 100;
arr[0][3] = 500;
arr[0][4] = 1000;
arr[0][5] = 5000;
int count = 0;
//for each row..
for (int r = 0; r < arr.length; r++) { //for each row
for ( int c = 0; c < arr[r].length; c++) { //for each column
arr[r][0] = count;
//never navigate out of bounds
//row 0 is where we're at.. how to populate further rows..?
int priorNum = arr[r-1][c];
int nextNum = priorNum * 2;
arr[r][c] = nextNum;
//can't look back .. SO go UP one.. which is r - 1 goes back one.. and then the length goes - 1
//when c is - peek UP a row < and enter last column.. ^
}
count++;
}
}
i left in some notes that i wrote if you can understand what i'm trying to go for :)
i can also offer this printArray method i wrote for any testing you'd like to try!
public static void print2DArray(int[][] arr) {
for ( int r = 0; r < arr.length; r++) {
for ( int c = 0; c < arr[r].length; c++) {
System.out.print(arr[r][c] + "\t");
}
System.out.println();
}
}
}
thank you for any replies / assistance! everyone here seems very nice, i could not find my type of question that deals with my answer so i felt bad about posting hehe
The problem I can see is that in the first iteration when int priorNum = arr[r-1][c]; gets executed, r = 0, as specified by your outer for loop.
So you are basically trying to access an element of your 2D array using a negative index, which will result in an ArrayIndexOutOfBoundException being thrown.
You could adopt an if statement that will handle the first iteration so that you will not access a prior index.
You could also look at the Array access section of the following article:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html
Hope this helped.

2d array check the rows value with an if statement

So I am trying to loop through the rows of a 2d array to check the if the row matches the property of a method. How can I use an if to just check the row? This is my code
public void recordWhiplashPoints(ConnectionToClient client, int vote){
int[][] votecount = new int[game.getPlayers().length][0];
outside:
if(game.getRecordedAnswers() <= game.getPlayers().length){
for (int i = 0; i < game.getPlayers().length; i++) {
for (int q = 0; q < votecount.length; q++) {
if(votecount[q] == vote){
//do stuff
}
}
}
}
}
So where votecount[row] is. Can I compare that with the property vote some how?
So for two dimensional arrays, which is basically just an array of arrays, you get a member array using something like votecount[i], and you get a member of that array with votecount[i][q]. I think the following is the code you want:
int[][] votecount = new int[game.getPlayers().length][0];
outside:
if(game.getRecordedAnswers() <= game.getPlayers().length){
for (int i = 0; i < length; i++) {
// note that we need to compare against the array votecount[i]
for (int q = 0; q < votecount[i].length; q++) {
// here we access the actual element votecount[i][q]
if(votecount[i][q] == vote){
//do stuff
}
}
}
}
Not sure if this is what you're looking for, but one way to do so would be to use for-each loops
public void recordWhiplashPoints(ConnectionToClient client, int vote){
int[][] votecount = new int[game.getPlayers().length][0];
outside:
if(game.getRecordedAnswers() <= game.getPlayers().length){
for (int[] i : votecount) {
for (int q : i) {
if(q == vote){
//do stuff
}
}
}
}
}
Essentially the first for-each loop goes through each array the 2d votecount array, and then the second for-each loop goes through each of those 1D arrays. If you have any questions just ask.
However, I don't understand how your second if statement will be true, as you never change votecount from anything other that the default, which is a 2D array filled with 0's.

Filling two new arrays from existing array

I already have one Array with random numbers between 0-999.
I also have created two new arrays, one with correct the size to hold all numbers 0-499, and one with the correct size for numbers 500-999.
Problem is to then loop through the Array holding all numbers and copying the right numbers 0-499 and 500-999 to the new Arrays.
Anyone know the correct way to do this? Have spent many days now trying to figure this out.
What i got so far:
public static void main(String[] args) {
Scanner scannerObject = new Scanner(System.in);
Random generator = new Random();
System.out.print("How many numbers between 0 - 999?" );
int number= scannerObject.nextInt();
int [] total= new int[number];
for(int index = 0; index < total.length; index++ )
{
total[index] = generator.nextInt(1000);
}
System.out.println("Here are the random numbers:");
for(int index = 0; index < total.length; index++ )
{
System.out.print(total[index]+ " ");
}
int lowNumber=0;
int largeNumber = 0;
for(int index = 0; index < total.length; index++ )
{
if (total[index] < 500)
{
lowNumber++;
}
if (total[index] >= 500)
{
largeNumber++;
}
}
System.out.println();
System.out.println(lowNumber);
System.out.println(largeNumber);
int [] totalLownumber = new int [lowNumber];
int [] totalLargeNumber = new int [largeNumber];
for(int index = 0; index < total.length; index++ )
{ // TODO
}
}
2 of the approaches you can take are as follows:
You can go through the initial array, count the elements you have, and use the counter values to define the size of the arrays you need. You then go over the original array once again and copy the elements to their respective array. You can use the counter values once again (you would need to reset them first) to allow you to keep track in which array location will the current number need to go. This should be similar to what you are doing.
Consider using a variable length data structure such as a List (ArrayList in Java). This would allow you to go over your original array and assign the numbers to their respective list (let's call them largeNumberList and lowNumberList). Since these collections have a dynamic size, you would only need to traverse the array once and assign as you go along.
The latter approach is usually what is used more often, however, since it would seem that this question is related to homework, I would recommend you try both approaches and compare them.
Try this:
int lowIndex = 0;
int largeIndex = 0;
for(int index = 0; index < total.length; index++ ) {
if (total[index] < 500) {
totalLowNumber[lowIndex++] = total[index];
} else {
totalLargeNumber[largeIndex++] = total[index];
}

Appending to double Array method

So, I have a method like this
public String[][] getArgs(){
And, I want it to get results out of a for loop:
for(int i = 0; i < length; i++){
But how do I append them to the array instead of just returning them?
Create a String[][] array inside your method, fill this array inside a loop (or in any other way) and return that array in the end.
If you are sure you want to have only one for loop (instead of two, typical for 2-dimensional array), ensure your loop will go through the number of examples equal to the number of fields in your String[][] array. Then you can calculate the double-dimension array indexes from your single loop-iterator, for example:
for(int i = 0; i < length; i++){
int a = i % numberOfCollumnsInOutput;
int b = i / numberOfCollumnsInOutput;
String[a][b] = sourceForYourData[i];
}
(Of course which array dimension you treat as collumns (and which to be rows) depends on yourself only.) However, it is much more typical to go through an n-dimensional array using n nested loops, like this (example for 2d array, like the one you want to output):
for(int i = 0; i < dimensionOne; i++){
for(int j = 0; j < dimensionTwo; j++){
array[i][j] = someData;
}
}
For your interest. A sample code according to Byakuya.
public String[][] getArgs(){
int row = 3;
int column =4;
String [][] args = new String[row][column];
for(int i=0;i<row;i++)
for(int j=0;j<column;j++)
args[i][j] = "*";
return args;
}
You can make a LinkedList from that array, and then append the elements to it, and then create a new array from it. If you are not sure i'll post some code.

Where does this program get its numbers from, and why is this caused by increasing 1 array size? (Java)

This program simply is supposed to eliminate duplicates from an array. However, the second for loop in the eliminate method was throwing an out of bounds exception. I was looking and couldnt see how that could be, so I figured I would increase the array size by 1 so that I would get it to work with the only downside being an extra 0 tacked onto the end.
To my surprise, when I increased tracker[]'s size from 10 to 11, the program prints out every number from 0 to 9 even if I dont imput most of those numbers. Where do those numbers come from, and why am I having this problem?
import java.util.*;
class nodupes
{
public static void main(String[] args)
{
int[] dataset = new int[10];
//getting the numbers
for (int i = 0; i <= 9 ; i++)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter a one digit number");
dataset[i] = input.nextInt();
}
int[] answer = (eliminateduplicates(dataset));
System.out.println(Arrays.toString(answer));
}
public static int[] eliminateduplicates(int[] numbers)
{
boolean[] tracker = new boolean[11];
int arraysize = 1;
for(int k = 0; k <= 9; k++)
{
if(tracker[numbers[k]] == false)
{
arraysize++;
tracker[numbers[k]] = true;
}
}
int[] singles = new int[arraysize];
for(int l = 0; l <= arraysize; l++)
{
if(tracker[l] == true)
{
singles[l] = l;
}
}
return singles;
}
}
The exception was occuring at this part
if(tracker[l] == true)
but only when trackers size was 10. At 11 it just prints [0,1,2,3,4,5,6,7,8,9]
EDIT: The arraysize = 1 was a hold over from debugging, originally it was at 0
EDIT: Fixed it up, but now there is a 0 at the end, even though the array should be getting completely filled.
public static int[] eliminateduplicates(int[] numbers)
{
boolean[] tracker = new boolean[10];
int arraysize = 0;
for(int k = 0; k < numbers.length; k++)
{
if(tracker[numbers[k]] == false)
{
arraysize++;
tracker[numbers[k]] = true;
}
}
int[] singles = new int[arraysize];
int counter = 0;
for(int l = 0; l < arraysize; l++)
{
if(tracker[l] == true)
{
singles[counter] = l;
counter++;
}
}
return singles;
}
Since arrays start at 0, your arraysize will be one larger than the number of unique numbers, so your final loop goes through one too many times. In other words "l" (letter l -- try using a different variable name) will get to 11 if you have 10 unique numbers and tracker only has item 0-10, thus an out of bounds exception. Try changing the declaration to
int arraysize = 0;
Once again defeated by <=
for(int l = 0; l <= arraysize; l++)
An array size of 10 means 0-9, this loop will go 0-10
For where the numbers are coming from,
singles[l] = l;
is assigning the count values into singles fields, so singles[1] is assigned 1, etc.
Edit like 20 because I should really be asleep. Realizing I probably just did your homework for you so I removed the code.
arraySize should start at 0, because you start with no numbers and begin to add to this size as you find duplicates. Assuming there was only 1 number repeated ten times, you would've created an array of size 2 to store 1 number. int arraysize = 0;
Your first for loop should loop through numbers, so it makes sense to use the length of numbers in the loop constraint. for( int i = 0; i < numbers.length; i ++)
For the second for loop: you need to traverse the entire tracker array, so might as well use the length for that (tracker.length). Fewer magic numbers is always a good thing. You also need another variables to keep track of your place in the singles array. If numbers was an array of 10 9s, then only tracker[9] would be true, but this should be placed in singles[0]. Again, bad job from me of explaining but it's hard without diagrams.
Derp derp, I feel like being nice/going to bed, so voila, the code I used (it worked the one time I tried to test it):
public static int[] eliminateduplicates(int[] numbers)
{
boolean[] tracker = new boolean[10];
int arraysize = 0;
for(int k = 0; k < numbers.length; k++)
{
if(tracker[numbers[k]] == false)
{
arraysize++;
tracker[numbers[k]] = true;
}
}
int[] singles = new int[arraysize];
for(int l = 0, count = 0; l < tracker.length; l++)
{
if(tracker[l] == true)
{
singles[count++] = l;
}
}
return singles;
}
I feel you are doing too much of processing for getting a no duplicate, if you dont have the restriction of not using Collections then you can try this
public class NoDupes {
public static void main(String[] args) {
Integer[] dataset = new Integer[10];
for (int i = 0; i < 10; i++) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a one digit number");
dataset[i] = input.nextInt();
}
Integer[] arr = eliminateduplicates(dataset);
for (Integer integer : arr) {
System.out.println(integer);
}
}
public static Integer[] eliminateduplicates(Integer[] numbers) {
return new HashSet<Integer>(Arrays.asList(numbers)).toArray(new Integer[]{});
}
}
To answer your question your final loop is going one index more than the size.
The range of valid indexes in an array in Java is [0, SIZE), ie. from 0 up to arraysize-1.
The reason you're getting the exception is because in your loop you're iterating from 0 to arraysize inclusively, 1 index too far:
for(int l = 0; l <= arraysize; l++)
Therefore when you get to if(tracker[l] == true) in the last iteration, l will equal arraysize and tracker[l] will be outside the bounds of the array. You can easily fix this by changing <= to < in your for loop condition.
The reason that the problem goes away when the size of your array is changed from 10 to 11 has to do with arraysize being incremented up to 10 in the for loop above the one causing the problems. This time, singles[10] is a valid element in the array since the range of indexes in your array is now [0, 11).
EDIT: Actually arraysize has the potential to be incremented to 11, I thought it was initialised to 0 in which case it would only get to 10. Either way the above is still valid; the last index you try and access in your array must be 1 less than the length of your array in order to avoid the exception you're getting, since arrays are zero-based. So yeah, long story short, <= should be <.

Categories