package SinemaSalonu;
public class SinemaSalonu {
public static void main(String args[]) {
int[][] matrix = new int[10][20];
for (int k = 0; k < 10; k++) {
matrix[k][0] = k + 1;
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(" " + matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("\n\n" + " " + "P E R D E");
}
}
when i run this code the resulting matrix' last row is not centered with others cause of the number "10" in the last row. it caused the row to slightly shift to the right. i want to fix this and center each row.
In order to align the lines with a single digit with the lines that start with two digit replace your printing:
System.out.print(" " + matrix[i][j] + " ");
with:
int n = matrix[i][j];
System.out.print(" " + (n < 10 ? " " + n : n) );
It will add an extra space before each line that starts with a single digit.
It will look like this:
Related
I'm getting an error on line 66 c[rowA][colB] = c[rowA][colB] + a[rowA][colA]*b[colA][colB];. I went through the indices by hand, just can't figure out where the index went wrong. Help is greatly appreciated.
package arrayproducts;
import javax.swing.JOptionPane;
public class ArrayProducts {
public static void main(String[] args) {
String output = "";
int rowA = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of rows for MatrixA."));
int colA = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of columns for MatrixA."));
int rowB = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of rows for MatrixB."));
int colB = Integer.parseInt(JOptionPane.showInputDialog("\nEnter the number of columns for MatrixB."));
if( colA != rowB){
output += "Cannot perform matrix operation: Inner matrix dimensions must agree.";
output += "\nMatrixA has a dimension of "+ rowA + " x " + colA + ".";
output += "\nMatrixB has a dimension of "+ rowB + " x " + colB + ".";
JOptionPane.showMessageDialog(null, output);
return;
} else {
output += "\nDot Product Begin:";
int [][] a = new int[rowA][colA];
output += "\nMatrixA has a dimension of "+ rowA + " x " + colA + ".";
int [][] b = new int[rowB][colB];
output += "\nMatrixA has a dimension of "+ rowB + " x " + colB + ".";
JOptionPane.showMessageDialog(null, output);
int [][] c = new int[rowA][colB];
////
// enter first matrix
for(int i = 0; i < rowA; i++){
for(int j = 0; j < colA; j++){
a[i][j] = Integer.parseInt(
JOptionPane.showInputDialog("\nEnter an integer for MatrixA, row " + (i+1) + " and column " + (j+1) + "."));
}
}
// add first matrix to output
output += "\nThe first matrix is: \n";
for(int i=0; i < rowA; i++){
for(int j=0; j < colA; j++){
output += " " + a[i][j];
}
output += "\n";
}
JOptionPane.showMessageDialog(null, output);
////
// enter second matrix
for(int i = 0; i < rowB; i++){
for(int j = 0; j < colB; j++){
b[i][j] = Integer.parseInt(
JOptionPane.showInputDialog("\nEnter an integer for MatrixB, row " + (i+1) + " and column " + (j+1) + "."));
}
}
// add second matrix to output
output += "\nThe second matrix is: \n";
for(int i=0; i < rowB; i++){
for(int j=0; j < colB; j++){
output += " " + b[i][j];
}
output += "\n";
}
JOptionPane.showMessageDialog(null, output);
////
// compute the product
for(int i = 0; i < rowA; i++){
for(int j = 0; j < colB; j++){
for(int k = 0; k < colA ; k++){ // either colA or rowB will work here
c[rowA][colB] = c[rowA][colB] + a[rowA][colA]*b[colA][colB];
}
}
}
output += "\nThe product of MatrixA and MatriB is:\n";
for(int i=0; i < rowA; i++){
for(int j=0; j < colB; j++){
output += " " + c[rowA][colB];
}
output += "\n";
}
JOptionPane.showMessageDialog(null, output);
}
}
}
I guess you meant to use the indices i,j,k instead of rowA, colB etc in the following code.
c[rowA][colB] = c[rowA][colB] + a[rowA][colA]*b[colA][colB];
I will show you a simple example.
int[] a = new int[3];
That mean a can have only 3 values.
a[0], a[1] and a[2]
If you try a[3] it will be out of bound.
So. You have
int [][] c = new int[rowA][colB];
And try to access c[rowA][colB] which is out of bound.
In your three for loops, I think, you want to use i,j and k.
I am new to Java and there's this one question that makes me wonder. How to make the for inner loop more efficient in this code?
for (int i = 2; i <= 100; i++) {
System.out.print("Factors of " + i + " is: ");
for (int j = 2; j < i; j++) {
if (i % j == 0) System.out.print(j + " ");
}
System.out.println();
}
I was just trying to get the factors of numbers from 2 to 100 but how can i make the inner loop more efficient?
It's a little bit number theory involved here but if you do this it would be efficient specially when the 100 is replaced with something much bigger:
for (int i = 2; i <= 100; i++) {
System.out.print("Factors of " + i + " is: ");
for (int j = 2; j <= (int) Math.sqrt(i); j++) {
if (i % j == 0) System.out.print(j + " " + i / j + " ");
}
System.out.println();
}
You could use the fact that for every divisor a of i there is a number b such that a * b = i.
Find all divisors a <= sqrt(i) and save b = i/a and print these values later.
final int num = 100;
int[] divisors = new int[(int) Math.sqrt(num)];
for (int i = 2; i <= num; i++) {
System.out.print("Factors of " + i + " is: ");
int j = 2;
int index = 0;
for (; j * j < i; j++) {
if (i % j == 0) {
System.out.print(j + " ");
divisors[index++] = i / j;
}
}
if (j * j == i) {
// print sqrt(i) only once, if it's integral
System.out.print(j + " ");
}
while (--index >= 0) {
System.out.print(divisors[index] + " ");
}
System.out.println();
}
This way your inner loop needs only O(sqrt(i)) instead of O(i) operations.
This code time complexity is O(N2).
public static void main(String[] args) {
for (int i = 2; i <= 100; i++) {
System.out.print("Factors of " + i + " is: ");
for (int j = i/2; j > 1; j--) {
if (i % j == 0) System.out.print(j + " ");
}
System.out.println();
}
}
Try this,as your code output will be displayed as follows (ascending order)
Factors of 24 is: 2 3 4 6 8 12
please be noticed, but this given code will be displayed output as follows (descending order )
Factors of 24 is: 12 8 6 4 3 2
I'm working on a small game that essentially has piles of coins, and you must take some coins from a pile then the program prints out the resulting piles in the format:
Pile 1: ****
Pile 2: *****
Pile 3: **
I have an array list that store all these values like so:
List<Integer> coins = new ArrayList<>();
[4,5,2]
But I can't figure out how to get it to properly print the *'s.
How can I write this code to print out a * for each value in an element. IE 4 *'s if the element value is 4?
Here is my current method:
static void printGameState(){
for(int i = 0; i <= coins.size()-1; i++){
int k = i+1;
System.out.print("Pile " + k + ": ");
for(int j = 0; j <= coins.indexOf(i); j++){
System.out.print("*");
}
}
}
Instead of using this condition:
j <= coins.indexOf(i);
Use this condition:
j < coins.get(i);
Try it:
for(int i = 0; i <= coins.size()-1; i++) {
int k = i+1;
System.out.print("Pile " + k + ": ");
for(int j = 0; j < coins.get(i); j++) {
System.out.print("*");
}
System.out.println();
}
You'll get:
Pile 1: ****
Pile 2: *****
Pile 3: **
You should be using < instead of <=. Also, you should be able to use get(i) to take the value at index i.
static void printGameState(){
for(int i = 0; i < coins.size(); i++){
int k = i+1;
System.out.print("Pile " + k + ": ");
for(int j = 0; j < coins.get(i); j++){
System.out.print("*");
}
}
}
You could also make it a bit cleaner by forming another method to print * such as:
public void ast(int n){
for(int i=0; i<n; i++){
System.out.print("*");
}
}
Then the contents of printGameState loop would be
int k = i+1;
System.out.print("Pile " + k + ": ");
ast(coins.get(i));
You have to look at the values of the different stacks by accessing the array coins[i] instead of using the number of stacks as stack height:
static void printGameState(){
for(int i = 0; i < coins.size(); i++) {
// Build the coin stack
String coinStack = "";
for(int j = 0; j < coins.get(i); j++) {
coinStack += "*";
}
// And output it
System.out.println("Pile " + (i + 1) + ": " + coinStack);
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm having a hard time outputting the the average of each row in this array that I'm trying to run:
int x, y, val;
double sum=0, ave, sumtot;
System.out.print("Enter rows: ");
x = khel.nextInt();
System.out.print("Enter columns: ");
y = khel.nextInt();
double[][] myArray = new double[x][y];
val = x * y;
System.out.print("Enter " + val + " numbers: ");
for(int i=0; i<myArray.length; i++)
{
for(int j=0; j<myArray[i].length; j++)
{
myArray[i][j] = khel.nextDouble();
}
}
System.out.println("My Array Table:");
for(int i=0; i<myArray.length; i++)
{
for(int j=0; j<myArray[i].length; j++)
{
System.out.print("" + myArray[i][j] + "\t");
sum = sum + myArray[i][j];
}
sumtot = sum;
System.out.println("");
}
System.out.println("The sum of all numbers is " + sum + ".");
ave = sum / val;
System.out.println("The average of all numbers is " + ave + ".");
Hope you guys can help me with this.:)
You might want to try out is something like this (with slightly cleaned up code). If you need to store the data for averages of each row rather than just printing them on fly, you could add them into an array or arraylist.
double sum=0, ave;
int x = khel.nextInt();
int y = khel.nextInt(); // input for array sizes
int val = x * y;
double rowSum; // something to contain data
double[][] myArray = new double[x][y];
for(int i=0; i < myArray.length; i++)
{
for(int j=0; j < myArray[i].length; j++)
{
myArray[i][j] = khel.nextDouble(); // input for array content
}
}
for(int i=0; i < myArray.length; i++)
{
rowSum = 0; // reset value each row
for(int j=0; j < myArray[i].length; j++)
{
System.out.print(myArray[i][j] + "\t");
sum += myArray[i][j];
rowSum += myArray[i][j]; // add value from array
}
System.out.println(rowSum / (double)myArray[i].length); // print average from each row
System.out.println("");
}
System.out.println("The sum of all numbers is " + sum + ".");
// this is the average of the whole table
ave = sum / val;
System.out.println("The average of all numbers is " + ave + ".");
Review the logic of this and apply it in your code (assume that array[5][5] already has values)...
for( int row = 0; row < 5; row++ )
{
int rowSum = 0;
for( int column = 0; column < 5; column++ )
{
rowSum += array[row][column];
}
System.out.println( String.format( "Sum of values in row %d: %d", row, rowSum ) );
System.out.println( String.format( "Average of values in row %d: %d\n", row, ( rowSum / 5 ) ) );
}
If you just want to output the average per row, editing from what you current have. You can do this:
for(int i=0; i<myArray.length; i++)
{
for(int j=0; j<myArray[i].length; j++)
{
rowSum += myArray[i][j]; //Calculate sum of each row
}
System.out.println("Avg for row " + (i+1) + ":" + rowSum/(double)myArray.length);
rowSum = 0; //reset value for calculation for next row
}
Take note of where I placed the println() statement. Placing it after the inner loop will ensure it prints after all column values are added in each row.
I finally got it! Thank you for all your output guys!:) It drew closer to getting it right.:) Here's how I did it:
int x, y, val, i, j, row=1;
double sum=0, ave, rowSum;
System.out.print("Enter rows: ");
x = khel.nextInt();
System.out.print("Enter columns: ");
y = khel.nextInt();
double[][] myArray = new double[x][y];
val = x * y;
System.out.print("Enter " + val + " numbers: ");
for(i=0; i<myArray.length; i++)
{
for(j=0; j<myArray[i].length; j++)
{
myArray[i][j] = khel.nextDouble();
}
}
System.out.println("My Array Table:");
for(i=0; i<myArray.length; i++)
{
rowSum = 0;
for(j=0; j<myArray[i].length; j++)
{
System.out.print("" + myArray[i][j] + "\t");
sum = sum + myArray[i][j];
rowSum = rowSum + myArray[i][j];
}
rowSum = rowSum / myArray[i].length;
System.out.println("");
System.out.println("The average of the row " + row + " is " + rowSum + ".");
row++;
}
System.out.println("The sum of all numbers is " + sum + ".");
ave = sum / val;
System.out.println("The average of all numbers is " + ave + ".");
}
}
Your inputs helped me a lot. Thanks a bunch.:)
i have a 2D array 3X5 and i need the to multiply each element in column one, and so forth. This is what ive attempted without any luck. the result is not correct. i tried storing each column into an array and multiply each element from that array but i get the same results.
edit: yes i am aware there is no multiplication in this code, that is because it yields an incorrect product.
for(int j = 0; j < 5; j++){
double v = 0.0;
double[] ex = new double[3];
double volumeBox1 = 0.0;
for(int i = 0; i < 3; i++){
v = d[i][j];
System.out.println(v);
for(int z = 0; z < 3; z++){
ex[z] = v;
}
}
System.out.println("The volume of box " + (j+1) + " is: " + volumeBox1);
I will assume your matrix is 5 x 3, which is more logical and convenient than 3 x 5 for this use case :
for (int i = 0 ; i < d.length ; j++) {
double vol = 1;
for (int j = 0 ; j < d[i].length ; j++) {
vol *= d[i][j];
}
System.out.println("The volume of box " + (j + 1) + " is: " + vol);
}
This can of course be done with a 3 x 5 matrix but I think it makes less sense to iterate on the columns :
for (int j = 0 ; j < d[0].length ; j++) {
double vol = 1;
for (int i = 0 ; i < d.length ; i++) {
vol *= d[i][j];
}
System.out.println("The volume of box " + (j + 1) + " is: " + vol);
}