I had to create a 10x10 array and multiply each col and row, this wasn't a problem. However, I need help on how to grab only the odd columns and print a total, as well as the even. My java is only entry level so I can better understand it explain if possible.
class multiplyArray
{
private static final int tableSize = 10;
public static void main(String[] args)
{
int table[][] = new int [tableSize][tableSize];
for (int r=1; r<=10; r++)
{
for (int c=1; c<=10; c++)
{
System.out.printf(r*c+"\t");
}
System.out.println();
}
}
}
class oddArray
{
public static void main(String[] args)
{
int table[][] = new int [10][10];
for (int r=0; r<table.length; r++)
{
int total = 0;
for (int c=1; c<=table[r].length; c+=2)
{
System.out.printf(r*c+"\t");
total+= table[c][r];
}
System.out.println();
System.out.println(total);
}
}
}
You can increment column by 2 instead of 1 in for loop * (i.e c += 2) which will provide you only odd columns of every rows, as you have already started the inner loop from 1 which is needed in case of odd columns but for outer loop you have to start it with 0 because array index starts with 0 not 1. Moreover, declare one total variable to add all odd column values to it in loop. One thing to add change condition in loop to r < table.length and c < table[r].length
* Assuming you have inserted values in array, you can have c += 2 instead of c++ in loop.
Related
So I help tutor an Algebra 2 class at my local high school, and the class is currently looking over matrices. Though not there, they will eventually get to multiplication of matrices. After taking Computer Science last year and learning Java, the teacher I help thought I should try to write a program to multiple matrices.
At the moment, I have up to defining the numbers for the first array that holds the information for the first matrix. However, I have a small issue. As represented by this picture:
the line asking for the index integers is being repeated after already recording the integers. I assume this is due to my layered for loops, but I can't be for certain. Usually new eyes see problems clearer. Any who could help me would be appreciated.
Code:
package matrixmultiplication;
import java.util.*;
public class MatrixMultiplication {
public static void main(String[] args) {
System.out.println("What is the size of the first matrix?");
int matrix1Rows = matrixRows();
int matrix1Columns = matrixColumns();
int[] matrix1 = new int[matrix1Rows * matrix1Columns];
doubleSpace();
System.out.println("What is the size of the second matrix?");
int matrix2Rows = matrixRows();
int matrix2Columns = matrixColumns();
int[] matrix2 = new int[matrix2Rows * matrix2Columns];
doubleSpace();
if (matrix1Columns != matrix2Rows) {
System.out.println("These cannot be multiplied!");
System.exit(0);
} else {
matrix1Numbers(matrix1Rows, matrix1Columns);
}
}
public static int matrixRows() {
System.out.print("Rows:");
Scanner rowSc = new Scanner(System.in);
int rows = rowSc.nextInt();
return rows;
}
public static int matrixColumns() {
System.out.print("Columns:");
Scanner colSc = new Scanner(System.in);
int cols = colSc.nextInt();
return cols;
}
public static int[] matrix1Numbers(int rows, int cols) {
int[] numb = new int[rows * cols];
for (int j = 0; j <= numb.length; j += rows) {
for (int i = 1; i <= cols; i++) {
for (int k = 1; k <= rows; k++) {
System.out.println("What is the value for index ("
+ k + "," + i + ")?");
Scanner inp = new Scanner(System.in);
if (j + k <= numb.length) {
numb[j + k - 1] = inp.nextInt();
}
}
}
}
for (int i = 0; i < numb.length; i++) {
System.out.println(numb[i]);
}
return numb;
}
public static void doubleSpace() {
System.out.println();
System.out.println();
}
}
I use NetBeans 8.2 and the latest working version of Java for NetBeans.
I'm not familiar with the matrixmultiplication package, so I may be rambling here.
for (int j = 0; j <= numb.length; j += rows){
I'm not entirely sure what the outer for loop your have is for, but this most outer for loop causes you to ask for the values of the indices cols times more than you want.
I feel that you originally wanted to use this outer for loop to iterate through each row, and wasn't planning on having the second for loop iterating through cols perhaps?
Also, Kevin Anderson mentions this above. You might avoid this problem altogether if you return a double int array as opposed to storing all values in the matrix in a single dimension. I personally feel it would make more sense.
Just nitpicking, but I wouldn't make a new scanner every time you want to use one in a different method. You could just make a field at the top of your class, instantiate it once in your main method, and then pass it in as a parameter to all methods using the scanner.
Im currently writing some code that print Pascal's Triangle. I need to use a 2D array for each row but don't know how to get the internal array to have a variable length, as it will also always changed based on what row it is int, for example:
public int[][] pascalTriangle(int n) {
int[][] array = new int[n + 1][]
}
As you can see I know how to get the outer array to have the size of Pascal's Triangle that I need, but I don't know how to get a variable length for the row that corresponds with the line it is currently on.
Also how would I print this 2D array?
Essentially what you want to happen is get the size of each row.
for(int i=0; i<array.size;i++){//this loops through the first part of array
for(int j=0;j<array[i].size;j++){//this loops through the now row
//do something
}
}
You should be able to use this example to also print the triangle now.
This is my first answer on StackOverFlow. I am a freshman and have just studied Java as part of my degree.
To make every step clear, I will put different codes in different methods.
Say n tells us how many rows that we are going to print for the triangle.
public static int[][] createPascalTriangle(int n){
//We first declare a 2D array, we know the number of rows
int[][] triangle = new int[n][];
//Then we specify each row with different lengths
for(int i = 0; i < n; i++){
triangle[i] = new int[i+1]; //Be careful with i+1 here.
}
//Finally we fill each row with numbers
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
triangle[i][j] = calculateNumber(i, j);
}
}
return triangle;
}
//This method is used to calculate the number of the specific location
//in pascal triangle. For example, if i=0, j=0, we refer to the first row, first number.
public static int calculateNumber(int i, int j){
if(j==0){
return 1;
}
int numerator = computeFactorial(i);
int denominator = (computeFactorial(j)*computeFactorial(i-j));
int result = numerator/denominator;
return result;
}
//This method is used to calculate Factorial of a given integer.
public static int computeFactorial(int num){
int result = 1;
for(int i = 1; i <= num; i++){
result = result * i;
}
return result;
}
Finally, in the main method, we first create a pascalTriangle and then print it out using for loop:
public static void main(String[] args) {
int[][] pascalTriangle = createPascalTriangle(6);
for(int i = 0; i < pascalTriangle.length; i++){
for(int j = 0; j < pascalTriangle[i].length; j++){
System.out.print(pascalTriangle[i][j] + " ");
}
System.out.println();
}
}
This will give an output like this:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Write the code required to allocate a ragged 2-D int array such that the first row has space to store 1 value, the second row can store 2 values, the third row has space to store 3 values, etc. up until the 50th row which has space to store 50 values.
I know for the above question I have to essentially create a pyramid with a 2 dimensional array. I don't really know how to manipulate 2D arrays, any help will be great. This is my code thus far, not sure how to allocate space like the question above says:
import java.util.Arrays;
public class Ragged2D {
public static void main(String[] args) {
int[][] boo = new int[50][];
for(int i = 0; i < boo.length; i++){
for(int k = 0; k< boo[i].length; k++){
}
}
System.out.println(Arrays.toString(boo));
}
}
This is how you initialize a row of the 2D array:
public static void main(String[] args) {
int[][] boo = new int[50][];
for(int i = 0; i < boo.length; i++){
boo[i] = new int[i+1]; // initialize the i'th row to have i+1 elements
for(int k = 0; k< boo[i].length; k++){
boo[i][k] = ...
}
}
System.out.println(Arrays.deepToString(boo)); // this change is required to print 2D array
}
I guess this is what you need
int[][] boo = new int[50][];
for (int i=0;i<50;i++) {
boo[i] = new int[i+1];
}
This way boo[0] can contain 1 element (boo[0][0]), boo[1] can contain 2 elements (boo[0][0] and boo[0][1]) etc.
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++;
}
}
}
I have declared an array that i would like to multiply the value of the first column by value of the second column of each row and create a grand sum of these products. I have tried the code listing below, what am i missing
public class Arrays {
public static void(String[] args) {
int array_x[][]={{9,8},{2,17},{49,4},{13,119},{2,19},{11,47},{3,73}};
int sum = 0;
for (int i = 0; i < array_x.length; i++) {
for (int j = 0; j < array_x.length; j++) {
array_x[i][j] = i * j;
System.out.println("\n" + array_x[i][j])
}
}
}
}
The output should be something like
9*8=72
2*17=34 etc then sum the whole results as 72+34+....
The code you wrote had several issues, including the fact that it would not compile because you had a different number of open and closed brackets, you didn't specify the function name (which I assumed to be main) and there was a ; missing. However the biggest issue was a logical one: you only need a single for to do what you want to do. You know that the indices of the second dimension of the array are going to be 0 and 1, because as you said the array has only two columns. Also, you need to accumulate the products into sum, instead you initialized sum to 0 and never updated it. Finally, the instruction array_x[i][j] = i * j multiplies the indices instead of the values, so the result is not what you expect, and this result is put into array_x, which is the wrong place because you really don't need to alter the input array.
class Arrays{
public static void main(String[] args){
int array_x[][]={{9,8},{2,17},{49,4},{13,119},{2,19},{11,47},{3,73}};
int sum=0;
for(int i=0;i<array_x.length;i++) {
int prod = array_x[i][0] * array_x[i][1];
System.out.println("\n"+prod);
sum += prod;
}
System.out.println("Final: " + sum);
}
}
The code you originally wrote is actually what you need to build a multiplication table, but in that case you need an array with an equal number of rows and columns.
public class Arrays {
public static void main (String[] args) {
int array_x[][]={{9,8},{2,17},{49,4},{13,119},{2,19},{11,47},{3,73}};
int multiply[] = new int[7];
for (int i = 0; i < array_x.length; i++) {
multiply[i] = array_x[i][0] * array_x[i][1];
}
int sum = 0;
for(int i = 0; i < multiply.length; i++)
{
System.out.println(array_x[i][0] + "*" + array_x[i][1] + "=" + multiply[i]);
sum += multiply[i];
}
System.out.println("Sum:" + sum);
}
}