Multiplication table not working Array index out of bounds - java

I added the plus 1 here: for (int i = 1; i < x + 1; i++) {
for (int j = 1; j < y + 1; j++)
so that the program would grab all the numbers except the one right before what I mean is..
If I enter 10 for the Maximum x value and 10 for the y (without the plus 1) this is what the output shows:
Would you like a power table or a multiplication table?
Press 1 for Power
Press 2 for Multiplication
2
Maximum x value?
10
Maximum y value?
10
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
I don't know why this wont work please help this is the code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int defaulVa = 1;
int defaulEx = 2;
System.out.println("Would you like a power table or a multiplication table?"
+ "\n Press 1 for Power"
+ "\n Press 2 for Multiplicatiion");
int a = sc.nextInt();
System.out.println("Maximum x value?");
int x = sc.nextInt();
System.out.println("Maximum y value?");
int y = sc.nextInt();
switch (a) {
case 1:
System.out.println("How would you like your base?"
+ "\nPress 1 for preset value"
+ "\nPress 2 for acending value");
int answer = sc.nextInt();
switch (answer) {
case 1:
System.out.println("What value?");
int value = sc.nextInt();
powerTable(x, y, value, defaulVa);
break;
case 2:
System.out.println("How would you like your exponent?"
+ "\nPress 1 for preset value"
+ "\nPress 2 for acending value");
int d = sc.nextInt();
switch (d) {
case 1:
System.out.println("What value?");
int d2 = sc.nextInt();
powerTable(x, y, defaulVa, d2);
break;
case 2:
powerTable(x, y, defaulVa, defaulEx);
break;
default:
break;
}
break;
default:
break;
}
break;
case 2:
multiplicationTable(x, y);
break;
default:
System.out.println("I see you can't follow simple instructions...");
System.exit(0);
break;
}
}
public static int[][] powerTable(int arrayDimensionX, int arrayDimensionY, int value, int value2) {
int[][] myArray;
myArray = new int[arrayDimensionX][arrayDimensionY];
for (int i = 1; i < myArray.length; i++) {
for (int j = 1; j < myArray[i].length; j++) {
if (value == 1) {
value = myArray[i][j] = i * j;
} else if (value != 1) {
value++;
}
myArray[i][j] = ((int) Math.pow(value, value2));
}
}
for (int i = 1; i < arrayDimensionX; i++) {
for (int j = 1; j < arrayDimensionY; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
return myArray;
}
public static int[][] multiplicationTable(int x, int y) {
int[][] myArray;
myArray = new int[x][y];
for (int i = 1; i < myArray.length; i++) {
for (int j = 1; j < myArray.length; j++) {
myArray[i][j] = i * j;
}
}
for (int i = 1; i < x + 1; i++) {
for (int j = 1; j < y + 1; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
return null;
}
}

Arrays are 0 indexed (they start at 0 and the last index is length - 1)
I would say...
for (int i = 1; i < x + 1; i++) {
for (int j = 1; j < y + 1; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
Should be...
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
You'd need to change the loop that builds the table to look something more like...
for (int i = 0; i < myArray.length; i++) {
for (int j = 0; j < myArray.length; j++) {
myArray[i][j] = (1 + i) * (1 + j); // <-- Modify the indices here instead...
}
}
Have a look at Arrays for more details

Why does your multiplicationTable function have an int[][] return type, when you return null? Would be better to just make it a void function, if you don't plan on having it return the array.
Anyway, since all the function does in print to the screen, the function is over complicated. Could be made much simpler, something like this:
public static void multiplicationTable(int x, int y)
{
for (int i = 1; i <= x; i++)
{
for (int j = 1; j <= y; j++)
System.out.print(i * j);
System.out.println();
}
}
But if you want it left as is, your ArrayIndexOutOfBounds exception is likely occuring here:
for (int i = 1; i < x + 1; i++) {
for (int j = 1; j < y + 1; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
Because x and y are the size of the array, making your loop go to i < x + 1 and i < y + 1 will throw the exception, because it is trying to access a non-existing index. If you change it to i < x and i < y it shouldn't throw the exception:
for (int i = 1; i < x; i++) {
for (int j = 1; j < y; j++) {
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
However, even that will not give you the desired output, as it skips the first element of the array, because array indexes start at 0, not 1, meaning the multiplications for 1 will be missing from your table.

Related

how to print pattern where start and end element is not same

How to print a pattern where i and j variable are not supposed to be printed for pattern rows? I try many times I change values without results.
int k = 1, p = 0;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
p += k;
System.out.print(p + " ");
}
k++;
System.out.println();
}
The above code is the generated output:
1
3 5
8 11 14
18 22 26 30
35 40 45 50 55
The desired output:
1
3 5
5 8 11
7 11 15 19
9 14 19 24 29
p must be updated after each i loop, using the current value of k. The following output can be generated using this code:
int k = 0;
for (int i = 1; i <= 5; i++) {
int p = k++;
for (int j = 1; j <= i; j++) {
p += k;
System.out.print(p + " ");
}
System.out.println();
}
For better formatting, you can use
System.out.printf("%-4d", p);
I'd write it this way:
int numRows = 5;
for (int row = 1; row <= numRows; row++) {
for (int col = 1, p = (row*2)-1; col <= row; col++, p+=row) {
System.out.print(p + " ");
}
System.out.println();
}
The pattern I see is as follows:
The first Row is designated as Row #1 (not zero)
The starting number in each row is (Row * 2) - 1
Each Row has the same number of Columns as the current Row number
In each Row, the numbers are incremented by the current Row number

How can i create a numeric pattern that starts from right to left side in java?

i need to create a numeric pattern just like i mentioned in the title.
It should be like;
0 0 0 0 1
0 0 0 2 3
0 0 4 5 6
0 7 8 9 10
11 12 13 14 15
I can do this;
int[][] Example = new int [5][5];
int c = 1;
for (int satir = 0; satir < Example.length; satir++) {
for (int sutun = 0; sutun < Example.length; sutun++) {
if (sutun <= satir) {
if (c < 10) System.out.print(" ");
System.out.print(" " + c++);
} else {
System.out.print(" " + 0);
}
}
System.out.println();
}
}
}
The pattern is simply count down the zeros in the row, then increment the counter for the remaining columns.
final int N = 5; // rows and columns
int zeros = N;
int counter = 0;
for (int row = 0 ; row < N; row++) {
zeros--; // first row 4 zeros, next 3, ...
int z = 0; // pre-initialize the column counter
// print the zeros
for (; z < zeros; z++) {
System.out.printf("%02d ", 0);
}
// print the numbers
for (; z < N; z++) {
System.out.printf("%02d ", ++counter);
}
System.out.println(); // end line
}
You could extract out the inner loop to a function based on the number of zeros that are needed and the value of the first number that is required
int printLine(final int lineLength, int zeros, int n) {
int column = 0;
for (; column < zeros; column++) {
System.out.printf("%02d ", 0);
}
for (; column < lineLength; column++) {
System.out.printf("%02d ", n++);
}
System.out.println();
return n; // to update the next line
}
Then you have
final int N = 5; // rows and columns
int lastValue = 1; // last value in row
for (int zeros = N - 1; zeros >= 0; zeros--) {
lastValue = printLine(N, zeros, lastValue);
}
Which results in
00 00 00 00 01
00 00 00 02 03
00 00 04 05 06
00 07 08 09 10
11 12 13 14 15
public static void main(String[] args) {
int n = 5;
int k = 0;
int[][] a = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j >= n - i - 1)
a[i][j] = ++k;
else
a[i][j] = 0;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%2d ", a[i][j]);
}
System.out.println();
}
}
If your want auto margin
int log = (int) Math.log10(n*(n+1)/2)+1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.printf("%"+log+"d ", a[i][j]);
}
System.out.println();
}
Simply:
int n = 10; // rows
int m = 10; // columns
int[][] a = new int[n][m];
int counter = 1;
for(int i = 0; i < n; i++) {
for(int j = m-1-i; j < m; j++) {
a[i][j] = counter++;
}
}
// print
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
System.out.print(String.format("%02d ", a[i][j]));
}
System.out.println();
}
Try this.
int size = 6;
for (int i = 0, k = 1; i < size; ++i) {
for (int j = 0; j < size; ++j)
System.out.printf("%3d", i + j >= size - 1 ? k++ : 0);
System.out.println();
}
result:
0 0 0 0 0 1
0 0 0 0 2 3
0 0 0 4 5 6
0 0 7 8 9 10
0 11 12 13 14 15
16 17 18 19 20 21

can't find how to program this number pattern

Number Pattern
I am asked to enter a number rc, and based on rc construct this pattern. I am able to initialize the table but without the highlighted numbers:
int [][] num2 = new int [rc][rc];
counter = 1;
for(int i = 0; i < rc; i++){
if(i!=0)
counter--;
for(int j =0; j < rc; j++){
num2 [i] [j] = counter;
counter ++;
}
}
Any hints or ideas?
You got it partially right. The numbers printed on each row are the same but the start point is incremented by 1 each time. Thus, you can use variable i again to shift it.
int [][] num2 = new int [rc][rc];
int counter = 1;
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
num2[i][(j + i) % rc] = counter++;
}
}
The following code is working fine for your problem.
int rc=5;
int [][] num2 = new int [rc][rc];
int counter = 1;
for(int i = 0; i < rc; i++){
for(int j =i; j < rc; j++){
num2 [i] [j] = counter;
counter ++;
}
for(int k =0; k < rc; k++){
if(num2[i][k]==0){
num2 [i] [k] = counter;
counter++;
}
System.out.print(num2[i][k]+"\t");
}
System.out.println();
}
The logic behind my solution is:
First fill an array from 1 - N, where N is the user input (or
rc in this case):
Then, we check if it's not the first line, if it is, we simply print
the numbers in order.
Now, we have to know which numbers go first:
In the line 1 (remember it starts from 0), it must print the number at [1][4] in [1][0], so our loop substracts rc - i + j, this gives: 5 - 1 + 0, which in fact is index [4].
We know that after we've printed the last numbers first, we must continue the sequence, so we print index: [1][0] at [1][1] (Why 1, 2? Because otherwise we would get something like the example below, that's why we need to substract 1 to it
1 2 3 4 5
10 7 8 9 10
And that's it:
public class StrangePattern {
public static void main(String[] args) {
int rc = 5;
int number = 1;
int spaces = 0;
int[][] numbers = new int[rc][rc];
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
numbers[i][j] = number;
number++;
}
}
for (int i = 0; i < rc; i++) {
for (int j = 0; j < rc; j++) {
if (i != 0) {
if (j < i) {
System.out.print(numbers[i][rc - i + j] + "\t");
} else {
System.out.print(numbers[i][j - spaces] + "\t");
}
} else {
System.out.print(numbers[i][j] + "\t");
}
}
spaces++;
System.out.println();
}
}
}
Which provides this output:
1 2 3 4 5
10 6 7 8 9
14 15 11 12 13
18 19 20 16 17
22 23 24 25 21
And this one for rc = 3:
1 2 3
6 4 5
8 9 7

Pascal's Triangle Format [duplicate]

This question already has answers here:
Pascal's triangle 2d array - formatting printed output
(5 answers)
Closed 1 year ago.
The assignment is to create Pascal's Triangle without using arrays. I have the method that produces the values for the triangle below. The method accepts an integer for the maximum number of rows the user wants printed.
public static void triangle(int maxRows) {
int r, num;
for (int i = 0; i <= maxRows; i++) {
num = 1;
r = i + 1;
for (int col = 0; col <= i; col++) {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
}
System.out.println();
}
}
I need to format the values of the triangle such that it looks like a triangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
I can't for the life of me figure out how to do that. Please answer keeping in mind that I'm a beginner in Java programming.
public static long pascalTriangle(int r, int k) {
if (r == 1 || k <= 1 || k >= r) return 1L;
return pascalTriangle(r - 1, k - 1) + pascalTriangle(r - 1, k);
}
This method allows you to find the k-th value of r-th row.
This is a good start, where it's homework, I'll leave the rest to you:
int maxRows = 6;
int r, num;
for (int i = 0; i <= maxRows; i++) {
num = 1;
r = i + 1;
//pre-spacing
for (int j = maxRows - i; j > 0; j--) {
System.out.print(" ");
}
for (int col = 0; col <= i; col++) {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
}
System.out.println();
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
In each row you will need to print:
n spaces
m numbers
n spaces
Your job is to figure out n (which will be zero in the last line) and m based on row number.
[This is more like a comment but I needed more formatting options than comments provide]
You need to print the spaces (like others have mentioned) and also as this is homework I'm leaving it to you but you might want to look at this handy little function
System.out.printf();
Here is a handy reference guide
Also note that you will need to take into account that some numbers are more than 1 digit long!
import java.util.*;
class Mine {
public static void main(String ar[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1; i < n; i++) {
int size = 1;
for (int j = 1; j <= i; j++) {
int a[] = new int[size];
int d[] = new int[size];
for (int k = 1; k <= size; k++) {
a[1] = 1;
a[size] = 1;
for (int p = 1; p <= size; p++) {
d[p] = a[p];
}
if (size >= 3) {
for (int m = 2; m < size; m++) {
a[m] = d[m] + d[m - 1];
}
}
}
for (int y = 0; y < size; y++) {
System.out.print(a[y]);
}
System.out.println(" ");
}
++size;
}
}
}
public class HelloWorld {
public static void main(String[] args) {
int s = 7;
int k = 1;
int r;
for (int i = 1; i <= s; i++) {
int num = 1;
r = i;
int col = 0;
for (int j = 1; j <= 2 * s - 1; j++) {
if (j <= s - i)
System.out.print(" ");
else if (j >= s + i)
System.out.print(" ");
else {
if (k % 2 == 0) {
System.out.print(" ");
} else {
if (col > 0) {
num = num * (r - col) / col;
}
System.out.print(num + " ");
col++;
}
k++;
}
}
System.out.println("");
k = 1;
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
You can try this code in java. It's simple :)
public class PascalTriangle {
public static void main(String[] args) {
int rows = 10;
for (int i = 0; i < rows; i++) {
int number = 1;
System.out.format("%" + (rows - i) * 2 + "s", "");
for (int j = 0; j <= i; j++) {
System.out.format("%4d", number);
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
Code perfectly prints pascal triangle:
public static void main(String[] args) {
int a, num;
for (int i = 0; i <= 4; i++) {
num = 1;
a = i + 1;
for (int j = 4; j > 0; j--) {
if (j > i)
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
if (j > 0)
num = num * (a - j) / j;
System.out.print(num + " ");
}
System.out.println();
}
}
Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

help java matrix?

I need help, I got a problem with this matrix, I need to have it in this way:
1 2 3 4 = 10
2 4 6 8 = 20
3 6 9 12 = 30
4 8 12 16 = 40
But I have it in this way:
1 2 3 4 1
2 4 6 8 2
3 6 9 12 3
4 8 12 16 4
I dont know how can we do that, I intent but nothing
This is my code:
public class Matrix {
public static void main(String args[]) {
int mult = 4;
for (int i = 1; i <= mult; i++) {
// System.out.println();
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
int suma = 0;
suma = operacion + suma;
System.out.print(operacion + " ");
}
int sum = 0;
sum = i + sum;
System.out.println(sum);
}
}
}
bye
When you do this:
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
int suma = 0;
suma = operacion + suma;
suma is always equal to operacion, because you set it to 0 every time and then add operacion.
You want to do this:
int suma = 0;
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
suma += operacion;
Put int sum = 0 outside the second for loop.
int suma = 0;
for (int i = 1; i <= mult; i++) {
// System.out.println();
suma =0;
for (int j = 1; j <= mult; j++) {
int operacion = i * j;
suma = operacion + suma;
System.out.print(operacion + " ");
}
System.out.println(suma);
}
You should take a look to String.format() or PrintStream.printf(). I think others allready helped you with the sum-problem. So try to print the values out like this:
for (int i = 0; i < 4; i++)
{
int[] values = new int[4];
int sum = 0;
for (int j = 0; j < 4; j++)
{
values[i] = (i+1) * (j+1);
sum += values[i];
}
System.out.printf("%-4d%-4d%-4d%-4d = %d\n", values[0], values[1], values[2], values[3], sum);
}
Try also to remove all the minus signs (-) from the last line and see what you like the most.
You are resetting sum to 0 just before you use it. You probably want for sum to be reset before your inner loop, added to inside your inner loop and printed outside your inner loop.
Also for your final println, print (" = " + sum) instead of just sum.
Trying not to actually correct your code since you mentioned this is an exercise (homework)--and thank you for tagging it. I wish more answerers would look for that sign as an indication that the person needs to learn and doesn't need the answer coded for them.

Categories

Resources