Okay, so I need to print 10 rows from 1 to 10 and 15 columns in every row from 1 to 15 with lines in between numbers. The second subroutine runs on its own, but only prints 0's and the first subroutine is me trying to give value to rows and columns, but I know I'm doing it very wrong. Any help is appreciated
static int ROWS = 10;
static int COLUMNS = 15;
static int[][] myArray = new int[10][15];
static int i; // loops through the number of rows
static int j; // loops through the number of columns
static int num1 = 0;
static int num2 = 0;
public static void vlueArray() {
for (i = 1; i < ROWS; i++) {
myArray[i][j]= num1++;
for (j = 1; j < COLUMNS; j++) {
myArray[i][j] = num2++;
System.out.print(myArray[i][j]);
}
System.out.println("");
}
}
public static void display2DArray() {
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLUMNS; j++) {
System.out.print(myArray[i][j] + " | ");
}
System.out.println("");
System.out.println("_____________________________________________________________");
}
}
you have not initialized elements in array and that is why you are getting zero displayed because int values are always initialized by the compiler even if you don't initialize them. The default value of int is 0.
Initialize your 2D array like this:
int[][] myArray = new int[10][15]{{2,3},{3,5},..........};
Hope this helps.
There are two issues here. First, you don't have very good syntax, while the way you have this set up does work, let me give you a couple of tips about settings this up, and then we can fix your problem fairly easily.
Some general rules here:
You don't have to initialize loop variables in the class variables, just initialize them in the loop structure (I'll show you this below).
Use the ROW and COLUMN in declaring your array, it helps make sure the array length values are the same throughout.
Your loop for creating the values in vlueArray is incorrect. I'll show you some correct formatting for placing these values below.
When you array is initialized, each place in the array (if it is an integer array) is automatically given a value of zero. You can change this, but since the first method doesn't run correctly, printing the values in the array without changing them will give the array of zeros.
Now, it seems like you want to just have 1 - 15 on 10 different rows. To do this, you only need one variable, so my response code will only have one variable, but if this isn't what you want, I'd be glad to help you get a different setup.
So now that you have a little bit of background information, let's get you some working code.
static int ROWS = 10; //Your row count.
static int COLUMNS = 15; //Your column count.
static int num = 0; //Our number.
//Using the constants to make sure rows and columns values match everywhere.
static int[][] myArray = new int[ROWS][COLUMNS];
public static void fillArray() {
//Initializing the loop variables in the loop is the common practice.
//Also, since the first index is zero, the loop needs to start at 0, not 1.
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLUMNS; j++) {
//If you want 0 - 14, use `num++`.
//If you want 1-15, use `++num`.
myArray[i][j] = num++;
}
num = 0; //This sets num back to zero after cycling through a whole row.
}
//Your display method works just fine.
public static void display2DArray() {
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLUMNS; j++) {
System.out.print(myArray[i][j] + " | ");
}
System.out.println("");
System.out.println("_____________________________________________________________");
}
Related
So, what I am trying to do is to fill a 2D array with zeros in random places a specific amount of times. Let's say that it has to be 20 zeros in an array of 90 places. What I have done so far is to declare a 2D array and fill it with random numbers. And my next thought was to simply choose random positions and replace them with zeros. Any idea how I could do that?
int[][] myboard = new int[9][9];
for (int i = 0; i < myboard.length; i++) {
for (int j = 0; j < myboard[i].length; j++) {
myboard[i][j] = (int) (Math.random() * 10);
}
}
It is a rather simple way to achieve the goal, but it should do the job. So you need to get the length of each row. After you have done that you can call a function that will give you a random number between some start point and the length of the row. Here is some code sample to show you what I mean:
import java.util.concurrent.ThreadLocalRandom;
import java.util.Arrays;
public class Example {
public static void main(String []args) {
int[][] myboard = new int[9][9];
for (int i = 0; i < myboard.length; i++) {
for (int j = 0; j < myboard[i].length; j++) {
// fill the row with random vals
myboard[i][j] = GetRandomNumber(0, myboard[i].length);
}
// sneak as much zeros as your heart content
int random = GetRandomNumber(0, myboard[i].length);
myboard[i][random] = 0;
}
System.out.println(Arrays.deepToString(myboard));
}
private static int GetRandomNumber(int min, int max) {
/*
min is the start point
max is the curr row len
*/
return ThreadLocalRandom.current().nextInt(min, max);
}
}
A pseudo code would look like:
while (num_zeros_filled < 20):
row = random()%total_rows
col = random()%total_cols
if (arr[row][col] == 0): # already filled in with 0
continue
else:
arr[row][col] = 0
num_zeros_filled += 1
This, however, could take infinite time theoretically if only those cells are generated which have already been filled with 0. A better approach would be to map the two-dimensional array into a 1-d array, and then sample out only from those cells which haven't been filled with 0 yet.
I have an atomic integer array of size 10. I am using this array to organize numbers 1-10 sent in by threads. This 1-10 will eventually be able to change to be a range of numbers larger than 10 and the list is to contain the 10 greatest numbers in that range. I can see the numbers going into the loops and recognizing that they are greater than a number currently there. However, there is never more than 2 numbers in the array when it is printed out. I have tried to trace my code in debug mode, however, it looks as if it is working as intended to me. I feel like there may be a simple error to my logic? I am completely sure all values are entering in the function as I have triple checked this. I start at the end of the array which should contain the highest value and then swap downwards once the slot has been determined. I would appreciate the assistance. This is just a simple experiment I am doing in order to grasp the basics before I try to tackle a homework assignment.
Here an example of my code:
public class testing{
static AtomicIntegerArray maxList = new AtomicIntegerArray(10);
final static int n = 10;
static void setMax(int value)
{
for(int i = 9; i >= 0; i--)
{
if(value > maxList.get(i))
{
int temp = maxList.get(i);
maxList.set(i,value);
if(i == 0)
{
maxList.set(i, value);
}
else
{ for(int j = i-1; j > 0; j--)
{
maxList.set(j, temp);
temp = maxList.get(j-1);
}
}
break;
}
}
public static void main(String[] args)
{
for (int i = 0; i < n; i++)
{
setMax(i);
}
}
}
Here is an example of how it is being called:
Brooke, there is a small bug in your 'j' loop. You had saved the state of a variable (temp), however your logic in the j loop lost the state. This new logic preserves the state of the previous element in the list.
Try this:
for (int j = i - 1; j >= 0; j--) {
int t2 = maxList.get(j);
maxList.set(j, temp);
temp = t2;
}
I'm creating a "Deal or no deal" code assignment for school. I am trying to creating 26 "case" objects in my "cases" arraylist using a for loop, however when I try to test my code it will not let me access anything above index 13. I get an arraylist out of bounds error.
public void createCases()
{
int amount;
int counter1 = 1;
int amountFound;
int allzero;
//Make a list of possible winning amounts
int amounts[] = new int[26];
for(int i = 0; i <= 25; i++) {
amounts[i] = counter1;
counter1++;
}
//Copy the winning amounts from amounts to amountsRandom... randomly.
int amountsRandom[] = new int[26];
for(int i = 0; i <= 25; i++) {
do {
amountFound = (int)(Math.random() * 25);
} while(amountFound == 0);
amountsRandom[i] = amounts[amountFound];
amountFound = 0;
}
//Take the amounts in index order and make them part of the case objects in the array list.
for(int i = 0; i <= 25; i++) {
cases.add(new Case(i++ , amountsRandom[i-1]));
}
}
I declared my cases arraylist outside of this method so it can be accessed by the entire class.
You are incrementing i twice: once in the for loop, once in the constructor call.
In your for loop where you add the Case ojects to the cases arraylist
for(int i = 0; i <= 25; i++) {
cases.add(new Case(i++, amountsRandom[i-1]));
}
You are calling i++ two times, so i will iterate twice per loop. Because of this, it only loops through 13 times instead of 26. You might want to change it to new Case(i + 1, amountsRandom[i-1])
I'm trying to make an encryption program where the user enters a message and then converts the "letters into numbers".
For example the user enters a ABCD as his message. The converted number would be 1 2 3 4 and the numbers are stored into a one dimensional integer array. What I want to do is be able to put it into a 2x2 matrix with the use of two dimensional arrays.
Here's a snippet of my code:
int data[] = new int[] {10,20,30,40};
*for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for (int ctr=0; ictr<data.length(); ictr++){
a[i][j] = data[ctr];}
}
}
I know there's something wrong with the code but I am really lost.
How do I output it as the following?
10 20
30 40
(instead of just 10,20,30,40)
Here's one way of doing it. It's not the only way. Basically, for each cell in the output, you calculate the corresponding index of the initial array, then do the assignment.
int data[] = new int[] {10, 20, 30, 40, 50, 60};
int width = 3;
int height = 2;
int[][] result = new int[height][width];
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
result[i][j] = data[i * width + j];
}
}
Seems like you want to output a 2xn matrix while still having the values stored in a one-dimensional array. If that's the case then you can to this:
Assume the cardinality m of your set of values is known. Then, since you want it to be 2 rows, you calculate n=ceil(m/2), which will be the column count for your 2xn matrix. Note that if m is odd then you will only have n-1 values in your second row.
Then, for your array data (one-dimension array) which stores the values, just do
for(i=0;i<2;i++) // For each row
{
for(j=0;j<n;j++) // For each column,
// where index is baseline+j in the original one-dim array
{
System.out.print(data[i*n+j]);
}
}
But make sure you check the very last value for an odd cardinality set. Also you may want to do Integer.toString() to print the values.
Your code is close but not quite right. Specifically, your innermost loop (the one with ctr) doesn't accomplish much: it really just repeatedly sets the current a[i][j] to every value in the 1-D array, ultimately ending up with the last value in the array in every cell. Your main problem is confusion around how to work ctr into those loops.
There are two general approaches for what you are trying to do here. The general assumption I am making is that you want to pack an array of length L into an M x N 2-D array, where M x N = L exactly.
The first approach is to iterate through the 2D array, pulling the appropriate value from the 1-D array. For example (I'm using M and N for sizes below):
for (int i = 0, ctr = 0; i < M; ++ i) {
for (int j = 0; j < N; ++ j, ++ ctr) {
a[i][j] = data[ctr];
}
} // The final value of ctr would be L, since L = M * N.
Here, we use i and j as the 2-D indices, and start ctr at 0 and just increment it as we go to step through the 1-D array. This approach has another variation, which is to calculate the source index explicitly rather than using an increment, for example:
for (int i = 0; i < M; ++ i) {
for (int j = 0; j < N; ++ j) {
int ctr = i * N + j;
a[i][j] = data[ctr];
}
}
The second approach is to instead iterate through the 1-D array, and calculate the destination position in the 2-D array. Modulo and integer division can help with that:
for (int ctr = 0; ctr < L; ++ ctr) {
int i = ctr / N;
int j = ctr % N;
a[i][j] = data[ctr];
}
All of these approaches work. Some may be more convenient than others depending on your situation. Note that the two explicitly calculated approaches can be more convenient if you have to do other transformations at the same time, e.g. the last approach above would make it very easy to, say, flip your 2-D matrix horizontally.
check this solution, it works for any length of data
public class ArrayTest
{
public static void main(String[] args)
{
int data[] = new int[] {10,20,30,40,50};
int length,limit1,limit2;
length=data.length;
if(length%2==0)
{
limit1=data.length/2;
limit2=2;
}
else
{
limit1=data.length/2+1;
limit2=2;
}
int data2[][] = new int[limit1][limit2];
int ctr=0;
//stores data in 2d array
for(int i=0;i<limit1;i++)
{
for(int j=0;j<limit2;j++)
{
if(ctr<length)
{
data2[i][j] = data[ctr];
ctr++;
}
else
{
break;
}
}
}
ctr=0;
//prints data from 2d array
for(int i=0;i<limit1;i++)
{
for(int j=0;j<limit2;j++)
{
if(ctr<length)
{
System.out.println(data2[i][j]);
ctr++;
}
else
{
break;
}
}
}
}
}
Just to keep my skills sharp, I decided to write a small programme that prints out the values of an array, after being given two variables that each contain a different value.
My expectation was that each value would show onscreen, but this did not happen. Instead, only the last element's value was displayed onscreen (in the code below, being the number "2" --> That is an integer, not a string).
Why is this?
Also, why does dynamic initialisation produce the result I wish, but not the way I do it in the code?
Many thanks.
int[] arrayOne;
arrayOne = new int[2];
int numOne = 1;`
int numTwo = 2;`
for (int i = 0; i < arrayOne.length; i++) {`
arrayOne[i] = numOne;
arrayOne[i] = numTwo;
System.out.println(arrayOne[i]);
}
If you want to put the values of two variables into an array, you need to use two assignments:
arrayOne[0] = numOne;
arrayTwo[1] = numTwo;
Now you can use a for loop to print out the contents of the array.
This kind of defeats the purpose of using an array, though.
You're setting different values to same location, causing only last value to be saved.
Your code similar to doing:
arrayOne[0] = 1;
arrayOne[0] = 2;
After these two lines, arrayOne[0] will hold the value of 2.
If you want to put these two values, you need to put them in different places:
arrayOne[0] = 1;
arrayOne[1] = 2;
In Java (and in almost any language I know), an array can only contain one vale per cell i.e. if you do "array[i] = 1" and after "array[i] = 2" , then the i-cell will CHANGE its value from 1 to 2, not append the value 2 after the 1. In the end, youre array will contain numTwo in every single cell.
If you want to initialize the array with a different value in each cell, I'm afraid you need to do it manually, not using the loop.
You need to do the population of your array before you iterate through it with the loop.
arrayOne[0] = numOne;
arrayOne[1] = numTwo;
Then do your loop:
for (int i = 0; i < arrayOne.length; i++)
{
System.out.println(arrayOne[i]);
}
Many ways to initialize an array...
int[] a = new int[2];
a[0] = 1;
a[1] = 2;
Or:
int[] a = new int[2];
for( int i = 0; i < a.length; i++ ){
a[i] = i + 1;
}
Or:
int[] a = new int[]{ 1, 2 };
Or.
int valOne = 1;
int valTwo = 2;
int[] a = new int[]{ valOne, valTwo };
Take care when you see more than one assignment to the same array element in a loop as you have it before the println. Is this what you want? The second one wins and sets the current (i-th) element to 2.
You need to do something like this:
public class demo{
private static int i = 0;
private static int[] demo = new int[10];
public static void main(String[] args){
for(int i = 0; i < 10; i++){
addElementToArray(i);
}
for(int i = 0; i < demo.length; i++){
System.out.println(demo[i]);
}
addElementToArray(i);
}
public static void addElementToArray(int input){
try{
demo[i] = input;
i++;
}catch(ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
Don't set the values inside the for-loop either, that is (imo) plain stupid, for what you are trying to achieve