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);
}
}
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 trying to print out an array but only print out the distinct numbers in that array.
For example: if the array has {5,5,3,6,3,5,2,1}
then it would print {5,3,6,2,1}
each time i do it either i only print the non repeating numbers, in this example {6,2,1} or i print them all. then i didnt it the way the assignment suggested
the assignment wants me to check the array before i place a value into it to see if its there first. If not then add it but if so dont.
now i just keep getting out of bounds error or it just prints everything.
any ideas on what i should do
import java.util.Scanner;
public class DistinctNums {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int value;
int count = 0;
int[] distinct = new int[6];
System.out.println("Enter Six Random Numbers: ");
for (int i = 0; i < 6; i++)
{
value = input.nextInt(); //places users input into a variable
for (int j = 0; i < distinct.length; j++) {
if (value != distinct[j]) //check to see if its in the array by making sure its not equal to anything in the array
{
distinct[count] = value; // if its not equal then place it in array
count++; // increase counter for the array
}
}
}
// Displays the number of distinct numbers and the
// distinct numbers separated by exactly one space
System.out.println("The number of distinct numbers is " + count);
System.out.print("The distinct numbers are");
for (int i = 0; i < distinct.length; i++)
{
System.out.println(distinct[i] + " ");
}
System.out.println("\n");
}
}
Always remember - if you want a single copy of elements then you need to use set.
Set is a collection of distinct objects.
In Java, you have something called HashSet. And if you want the order to be maintained then use LinkedHashSet.
int [] intputArray = {5,5,3,6,3,5,2,1};
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
//add all the elements into set
for(int number:intputArray) {
set.add(number);
}
for(int element:set) {
System.out.print(element+" ");
}
You can make this using help array with lenght of 10 if the order is not important.
int [] intputArray = {5,5,3,6,3,5,2,1};
int [] helpArray = new int[10];
for(int i = 0; i < intputArray.length ; i++){
helpArray[intputArray[i]]++;
}
for(int i = 0; i < helpArray.length ; i++){
if(helpArray[i] > 0){
System.out.print(i + " ");
}
}
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
This is the original prompt:
Write program that declares a 2-dimensional array of doubles called scores with three rows and three columns. Use a nested while loop to get the nine (3 x 3) doubles from the user at the command line. Finally, use a nested for loop to compute the average of the doubles in each row and output these three averages to the command line.
Here is my code:
import java.util.Scanner;
public class Scorer {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double [][] scores = new double[3][3];
double value = 0;
int i = 0;
int j;
while (i < 3) {
j = 0;
while (j < 3) {
System.out.print("Enter a number: ");
value = scnr.nextDouble();
scores[i][j] = value;
j++;
}
i++;
}
int average = 0;
for (i = 0; i < scores.length; i++) {
for (j = 0; j < scores[i].length; j++) {
average += value;
value = value / scores[i][j];
System.out.println(value);
}
}
}
}
The part that I need help on is the nested for loop at the bottom of the code. This code is supposed to compute the average of the numbers that are entered; however, I am confused on how to do that with the nested for loop.
you're almost there!
Here are the things you need to do:
1)you've to initialize the variable 'average' after the first for loop.
because average needs to be 0 i.e., reset after second for loop ends each time.
2)you've defined "value = value / scores[i][j]" . I don't know why you did that, but "value = scores[i][j]" must solve your problem.
3) you should print the average only thrice i.e., after calculating average of each row. so, print average at the end of second for loop.
Hope this makes it clear.
here's the code for your reference:
for (i = 0; i < 3; i++) {
int average = 0;
for (j = 0; j < 3; j++) {
value = scores[i][j];
average += value;
}
System.out.println(average/3);
}
Ever i represents a row, every j represents a column.
You need the average of every row, meaning that for every same i and every different j for that i you need to store the values and calculate the average.
Looks like homework code. We can give you hints but not write it for you :(
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.