//Given a number n i want to generate the corresponding 2-d matrix for it .
//for example for n = 1 my 2-D matrix should be
for n = 1
1 2
3 4
for n = 2
1 2 5 6
3 4 7 8
9 10 13 14
11 12 15 16
for n = 3
1 2 5 6 17 18 21 22
3 4 7 8 19 20 23 24
9 10 13 14 25 26 29 30
11 12 15 16 27 28 31 32
33 34 37 38 49 50 53 54
35 36 39 40 51 52 55 56
41 42 45 46 57 58 61 62
43 44 47 48 59 60 63 64
The problem could be solved using recursion. For example, the code below prints exactly the required matrix for a given n.
import java.util.Scanner;
public class Main {
public static void main(final String[] args) {
final Scanner scanner = new Scanner(System.in);
final int n = scanner.nextInt();
final int[][] matrix = create(1, (int) Math.pow(2, n));
print(matrix);
}
private static int[][] create(final int startValue, final int size) {
if (size == 1) {
return new int[][]{{startValue}};
} else {
final int half = size / 2;
final int step = half * half;
return combine(create(startValue, half), create(startValue + step, half),
create(startValue + 2 * step, half), create(startValue + 3 * step, half));
}
}
private static int[][] combine(final int[][] m1, final int[][] m2, final int[][] m3, final int[][] m4) {
final int initialSize = m1.length;
final int sizeOfResult = initialSize * 2;
final int[][] result = new int[sizeOfResult][sizeOfResult];
for (int row = 0; row < initialSize; row++) {
for (int col = 0; col < initialSize; col++) {
result[row][col] = m1[row][col];
result[row][col + initialSize] = m2[row][col];
result[row + initialSize][col] = m3[row][col];
result[row + initialSize][col + initialSize] = m4[row][col];
}
}
return result;
}
private static void print(final int[][] matrix) {
for (final int[] row : matrix) {
for (final int val : row) {
System.out.printf("%-5d", val);
}
System.out.println();
}
}
}
Related
I'm having trouble with an assignment where we are required to print out this array:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
My code is somewhat correct but it is not printing 10 and 19 where it should be.
My output:
Choose a number for the rows from 0 to 16.
5
Choose a number for the columns from 0 to 16
5
1 0 10 0 19
2 9 11 18 20
3 8 12 17 21
4 7 13 16 22
5 6 14 15 23
My code:
//snake move with the number
import java.util.Scanner;
public class SnakeMove {
public static void main(String[] args) {
//create Scanner object
Scanner inScan = new Scanner(System.in);
//prompt the user to choose number for the Row from 0 to 16
System.out.println("Choose a number for the rows from 0 to 16.");
//take the input from user with nextInt() method
//use the variable int row
int row = inScan.nextInt();
//prompt the user to choose number for the Col from 0 to 16
System.out.println("Choose a number for the columns from 0 to 16");
//take the input from user with nextInt()
//use the variable int col
int col = inScan.nextInt();
if (row != col) {
System.out.println("Run the program again and choose the same number for Row and Col");
System.exit(0);
}
int[][] arr = move(row, col);
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}//main method
static int[][] move(int row, int col) {
boolean flag = true;
int count = 1;
int[][] array = new int[row][col];
for (int j = 0; j < array[0].length; j++) {
if (flag) {
for (int i = 0; i < array.length; i++) {
//assign the increment value of count
// to specific array cells
array[i][j] = count;
count++;
}
flag = false;
} else {
//row decrement going up
for (int i = array.length - 1; i > 0; i--) {
//assign the increment value of count
// to specific array cells
array[i][j] = count;
count++;
}
flag = true;
}
}//column increment
return array;
}//move method
}//end SnakeMove class
Can anyone detect what is causing the error? Any help would be appreciated.
I believe this is a good alternative and easy to understand. Do comment if you have a simplified version of the same.
Code:
import java.util.Arrays;
import java.util.Scanner;
public class SnakePatternProblem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // *INPUT*
int row = scanner.nextInt();
int col = scanner.nextInt();
int[][] array = new int[row][col];
// Initializing first row of the array with a generalized expression
for (int i = 0; i < col; i++) {
if (i % 2 != 0) array[0][i] = col * (i+1);
else array[0][i] = (col * i) + 1;
}
array[0][0] = 1; // this element is not covered in the above loop.
// Nested loop for incrementing and decrementing as per the first row of elements.
for (int i= 1; i< row; i++){
for (int j=0; j< col; j++){
if(j%2==0) array[i][j] = array[i-1][j] + 1;
else array[i][j] = array[i-1][j] - 1;
}
}
System.out.println(Arrays.deepToString(array)); // *OUTPUT
}
}
Explanation:
Consider first row of 5 x 5 matrix named "arr" with snake pattern:
1 10 11 20 21
The element in the odd column is equivalent to ((currentColumn + 1) * Total_No_Of_columns);
Example: arr[0][1] = (1 + 1)* 5 = 10
The element in the even column is equivalent to (currentColumn * Total_No_Of_columns) + 1;
Example: arra[0][2] = (2 * 5) + 1 = 11;
Important Note: element at first row, first column is Zero
arr[0][0] = 1 -> must be declared
Now, the remaining matrix is incrementing or decrementing loop from the first element in that column.
Elements with even column number gets incremented by 1 in each row from the first element of that column.
1 -> First element of column-0
2 -> (1 + 1)
3 -> (2 + 1).... so on
4
5
Elements with odd column number gets decremented by 1 in each row from the first element of that column.
10 -> First element of column - 1
9 -> (10 - 1)
8 -> (9 - 1).... so on
7
6
This will generate the "snaking" pattern you described.
It could be simplified with ternary but this makes it more readable I think
It would be interesting to find a more clever way about it though, if anyone finds a better way pls comment
public static int[][] genArray(int length) {
int[][] arr = new int[length][length];
int counter = 0;
for (int col = 0; col < arr.length; col++) {
if (col % 2 == 0) {
for (int row = 0; row < arr.length; row++) {
arr[row][col] = counter++;
}
} else {
for (int row = arr.length - 1; row >= 0; row--) {
System.out.println("row: " + row + ", col: " + col);
arr[row][col] = counter++;
}
}
}
}
return arr;
}
You can create such an array as follows:
int m = 5;
int n = 4;
int[][] snakeArr = IntStream.range(0, n)
.mapToObj(i -> IntStream.range(0, m)
// even row - straight order,
// odd row - reverse order
.map(j -> (i % 2 == 0 ? j : m - j - 1) + i * m + 1)
.toArray())
.toArray(int[][]::new);
// output
Arrays.stream(snakeArr)
.map(row -> Arrays.stream(row)
.mapToObj(e -> String.format("%2d", e))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
Transposing snake array:
int[][] transposedSA = new int[m][n];
IntStream.range(0, m).forEach(i ->
IntStream.range(0, n).forEach(j ->
transposedSA[i][j] = snakeArr[j][i]));
// output
Arrays.stream(transposedSA)
.map(row -> Arrays.stream(row)
.mapToObj(e -> String.format("%2d", e))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
1 10 11 20
2 9 12 19
3 8 13 18
4 7 14 17
5 6 15 16
An easy way to do it is to create a 2-D array as shown below and then print its transpose.
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25
It is a 2-D array of the dimension, LEN x LEN, where LEN = 5.
The above pattern goes like this:
The pattern starts with a start value of 1.
When the main loop counter is an even number, the counter, which assigns a value to the array, starts with start value and increases by one, LEN times. Finally, it sets start for the next row to start with final_value_of_the_array_value_assignment_counter - 1 + LEN.
When the main loop counter is an odd number, the counter, which assigns a value to the array, starts with start value and decreases by one LEN times. Finally, it sets start for the next row to start with start + 1.
The transpose of the above matrix will look like:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
In terms of code, we can write it as:
public class Main {
public static void main(String[] args) {
final int LEN = 5;
int[][] arr = new int[LEN][LEN];
int start = 1, j, k, col;
for (int i = 0; i < LEN; i++) {
if (i % 2 == 0) {
k = 1;
for (j = start, col = 0; k <= LEN; j++, k++, col++) {
arr[i][col] = j;
}
start = j - 1 + LEN;
} else {
k = 1;
for (j = start, col = 0; k <= LEN; j--, k++, col++) {
arr[i][col] = j;
}
start++;
}
}
// Print the transpose of the matrix
for (int r = 0; r < LEN; r++) {
for (int c = 0; c < LEN; c++) {
System.out.print(arr[c][r] + "\t");
}
System.out.println();
}
}
}
Output:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
Change the value of LEN to 10 and you will get the following pattern:
1 20 21 40 41 60 61 80 81 100
2 19 22 39 42 59 62 79 82 99
3 18 23 38 43 58 63 78 83 98
4 17 24 37 44 57 64 77 84 97
5 16 25 36 45 56 65 76 85 96
6 15 26 35 46 55 66 75 86 95
7 14 27 34 47 54 67 74 87 94
8 13 28 33 48 53 68 73 88 93
9 12 29 32 49 52 69 72 89 92
10 11 30 31 50 51 70 71 90 91
I coded a Magic Square program with a driver and a class. The only problem I'm having is adding up the rows, columns, and diagonals. I made a int constant called "col" for column, that counts up 1 each time an entire row is summed. Therefore, the multi-dimensional array would first sum [0,0],[0,1],[0,2] to whatever size the square is, and then col would be incremented, changing to [1,0],[1,1],[1,2] etc. However, after my adding method computes one row, goes to print, and comes back for the next row, col is set back to 0. Is there a way I can prevent it from resetting and keep its incrementation? I think that's the final step. Note: I only put the col on the row and column sum methods so far, I just want to get it to work for those first.
Note: Please make sure you name the text file correctly when transferring the text given here
Thank you all in advance.
// ****************************************************************
// MagicSquare.java
//
// Text below is to be filled by student.
//
// ****************************************************************
import java.util.Scanner;
public class MagicSquare
{
int[][] square;
public MagicSquare(int size)
{
square = new int[size][size];
}
int col = 0;
//--------------------------------------
//return the sum of the values in the given row
//--------------------------------------
private int sumMagicRow(int size,int col)
{
int sum = 0;
for (int i=0;i<(size);i++)
{
sum += square[col][i];
}
col++;
return sum;
}
//--------------------------------------
//return the sum of the values in the given column
//--------------------------------------
private int sumMagicCol(int size, int col)
{
int sum = 0;
for (int i=0;i<size;i++)
{
sum += square[col][i];
}
col++;
return sum;
}
//--------------------------------------
//return the sum of the values in the main diagonal
//--------------------------------------
private int sumMagicDiagMain(int size)
{
int sum = 0;
for (int i=0;i<size;i++)
{
sum += square[i][i];
}
return sum;
}
//--------------------------------------
//return the sum of the values in the other ("reverse") diagonal
//--------------------------------------
private int sumMagicDiagRev(int size)
{
int sum = 0;
for (int i=0;i<size;i++)
{
sum += square[i][(size-1)-i];
}
return sum;
}
//--------------------------------------
//return true if the square is magic (all rows, cols, and diags
// have same sum), false otherwise
//--------------------------------------
public boolean isMagicSquare(int size)
{
boolean answer =false;
if(sumMagicCol(size,col)==sumMagicRow(size,col) && sumMagicRow(size,col)==sumMagicDiagMain(size) && sumMagicDiagMain(size)==sumMagicDiagRev(size))
{
answer=true;
}
return answer;
}
//--------------------------------------
//compute and display sums of square including row, column, main diagonal, and other diagonal
//--------------------------------------
public void printMagicSquareSums(int size)
{
for(int i=0;i<size;i++)
{
System.out.println("Sum of row " + i + " is: " + sumMagicRow(size,col));
}
for(int i=0;i<size;i++)
{
System.out.println("Sum of column " + i + " is: " + sumMagicCol(size,col));
}
for(int i=0;i<size;i++)
{
System.out.println("Sum of row " + i + " is: " + sumMagicDiagMain(size));
}
for(int i=0;i<size;i++)
{
System.out.println("Sum of row " + i + " is: " + sumMagicDiagRev(size));
}
}
//--------------------------------------
//read info into the square from the input stream associated with
//the Scanner parameter
//--------------------------------------
public void readSquare(Scanner scan)
{
for (int row = 0; row < square.length; row++)
for (int col = 0; col < square.length; col++)
square[row][col] = scan.nextInt();
}
//--------------------------------------
//print the contents of the square, neatly formatted
//--------------------------------------
public void printSquare(int size)
{
int column=0;
for(int x=0;x<size;x++)
{
for(int i=0;i<size;i++)
{
System.out.printf("%3d ",square[x][i]);
}
System.out.println("");
}
}
}
Driver program:
// ****************************************************************
// MagicSquareTest.java
//
// Text below is to be filled by student.
//
// ****************************************************************
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
public class MagicSquareTest
{
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(new File("magicText.txt"));
// make sure that the file magicData is in the current directory
int count = 1; //count which square we're on
int size = scan.nextInt(); //size of next square
int mem = size;
//Expecting -1 at bottom of input file
while (size != -1)
{
//create a new Square of the given size
MagicSquare s = new MagicSquare(size);
size=mem;
//call its read method to read the values of the square
System.out.println("\n***** Square " + count + " *****");
s.readSquare(scan);
//print the square
s.printSquare(size);
//print the square id
//System.out.println(count);
//print the sums
s.printMagicSquareSums(size);
//determine and print whether it is a magic square
System.out.println(s.isMagicSquare(size));
//get size of next square
size = scan.nextInt();
count++;
}
}
}
Text File (that reads into array)
3
8 1 6
3 5 7
4 9 2
7
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
4
48 9 6 39
27 18 21 36
15 30 33 24
12 45 42 3
3
6 2 7
1 5 3
2 9 4
4
3 16 2 13
6 9 7 12
10 5 11 8
15 4 14 1
5
17 24 15 8 1
23 5 16 14 7
4 6 22 13 20
10 12 3 21 19
11 18 9 2 25
7
30 39 48 1 10 28 19
38 47 7 9 18 29 27
46 6 8 17 26 37 35
5 14 16 25 34 45 36
13 15 24 33 42 4 44
21 23 32 41 43 12 3
22 31 40 49 2 20 11
-1
I find your code very weird and you still have a lot to fix in it in my opinion. But for your specific question:
private int sumMagicRow(int size,int col)
{
int sum = 0;
for (int i=0;i<(size);i++)
{
sum += square[col][i];
}
col++;
return sum;
}
Here you give col to the method and it is different then the field (it's not constant) col in the class. In col++ you increment that sumMagicRow(int size,int col). If you want to increment the class instance value you should use this.col which says use the col which is not defined in that particular scope (method) but on class level.
Unfortunately reading through your code I think it will not solve the problem because sooner or later you will want col to go back to 0 ;) otherwise if you keep adding to it you will leave the bounds of the array. For example if you have square with size 3 and you go read col1, col2, col3 when you go to rows col will be already 3 and you will try to read row 4. It would be better to rethink your algorithm. There are many things to improve.
For example if you have a loop for 1 to N (size of square) isn't one loop enough to check all rows/column/diagonals with some mathematics? I believe it should be ;)
int size = 50;
// Generates non-duplicated random numbers
int[] values = new int[51];
int[] list = new int[size];
for( int i = 0; i < 51; i++ )
values[i] = i;
Random rand = new Random();
int listSize = 0;
int myList = 0;
while( true )
{
int value = rand.nextInt(51);
if( values[ value ] == 0 )
continue; // number already used
list[ myList++ ] = value;
values[ value ] = 0;
if( myList == size || myList == 50 )
break;
}
// Displays non-duplicated random generated numbers
for(int element : list)
System.out.print(element + " ");
I would like to set a large array of numbers to a designated length per line to make all the numbers appear as though they're in a block with the left and right sides even like so:
> 1 2 3 4 5 6 7 8 9 10
> 11 12 13 14 15 16 17 18 19 20
> 21 22 23 24 25 26 27 28 29 30
> 31 32 33 34 35 36 37 38 39 40
> 41 42 43 44 45 46 47 48 49 50
How do I accomplish this using an enhanced for loop? Thanks for your help!
Add a new line after read 10 value
for(int i=0; i<list.length; i++){
System.out.printf(" %-2d",list[i]); //Format left justified
if ((i+1)%10==0){
System.out.println(); // Add a new line after 10
}
}
I'm making a board for snakes and ladders, so far I've got the board printed out in descending order. However, I need the board to be printed out the proper way.
EDIT: "Spiraling down" means
100...91
81...90
80...71
...
This is my code:
public class PrintGrid
{
public static void main(String[] args)
{
final int Rows=10;
final int columns=10;
int position =100;
int board [][]= new int [Rows][columns];
for (int row =0; row <=Rows-1;row++)
{
for(int col = 0; col <=columns-1; col ++)
{
board [row][col]= position;
position--;
}
System.out.println(" ");
}
}
}
I am trying to get the output to print the board in a spiraled fashion, i.e:
100,99,98,97,96,95,94,93,92,91
81,82,83,84,85,86,87,88,89,90
80,79,78,77,76,75,74,73,72,71
However it is printing out like this,
100,99,98,97,96,95,94,93,92,91
90,89,88,87,86,85,84,83,82,81
80,79,78,77,76,75,74,73,72,71
Any help would be great!
Try this:
package com.stackoverflow.q22099123;
public class PrintGrid
{
public static void main(String[] args)
{
int numRows = 10;
int numColumns = 10;
int numSpaces = numRows * numColumns;
int[][] board = new int[numRows][numColumns];
for (int space = 0; space < numSpaces; space++)
{
int row = space / numRows;
int column = space % numColumns;
if (row % 2 == 0)
{
board[row][column] = (numSpaces - space);
}
else
{
board[row][(numColumns - column) - 1] = (numSpaces - space);
}
}
for (int[] row : board)
{
for (int col : row)
{
System.out.printf("%4d", col);
}
System.out.println();
}
}
}
Prints:
100 99 98 97 96 95 94 93 92 91
81 82 83 84 85 86 87 88 89 90
80 79 78 77 76 75 74 73 72 71
61 62 63 64 65 66 67 68 69 70
60 59 58 57 56 55 54 53 52 51
41 42 43 44 45 46 47 48 49 50
40 39 38 37 36 35 34 33 32 31
21 22 23 24 25 26 27 28 29 30
20 19 18 17 16 15 14 13 12 11
1 2 3 4 5 6 7 8 9 10
To be honest though, if you're making a snakes and ladders game, how the board is organized is really more of a display problem. It would probably make more sense to store the game spaces as an ascending 1D array (to make counting moves easier) and worry about handling the display of the board separately.
I'd be inclined to isolate the complexity into a function:
private static int getNumber(int row, int col)
{
return row % 2 == 0 ? 100 - row * 10 - col : 91 - row * 10 + col;
}
Where getNumber(0, 0) will return 100.
To generate your grid, use
for (int row = 0; row < 10; ++row){
for (int col = 0; col < 10; ++col){
System.out.print(getNumber(row, col) + " ");
}
System.out.println();
}
for (int row =0; row <=Rows-1;row++)
{
for(int col = 0; col <=columns-1; col ++)
{
if(row%2 == 1)
board[row][9-col] = position;
else
board[row][col] = position
position--;
}
}
I think you might be trying to structure it as above? You need to put in the if and else statements to make sure you add the values to the array backwards for every other array.
As stated by #Jon Quarfoth, displaying the board should probably be handled separately from actually internally storing each cell-position. But since this is a relatively complicated way of displaying a sequence of positions, I'd recommend pre-determining the positions of each cell, and storing them in an x/y coordinate, in a CellPosition object.
public class CellPosition {
public final int rowIdx; //X
public final int colIdx; //Y
public final int positionNum;
public class CellPosition(int rowIdx, int colIdx, int positionNum) {
this.rowIdx = rowIdx;
this.colIdx = colIdx;
this.positionNum = positionNum;
}
}
However, I found the filling the two-dimensional array in a "spiraling fashion" to be quite a difficult-but-interesting problem. Here's my solution, which I solved by creating a "SpiralGridPositionIterator" (although it doesn't implement Iterator).
The main class:
import java.util.NoSuchElementException;
/**
<P>{#code java SpiralPositionXmpl}</P>
**/
public class SpiralPositionXmpl {
public static final void main(String[] ignored) {
int rows = 10;
int cols = 10;
int[][] boardPositions = new int[rows][cols];
SpiralGridPositionIterator gridPosItr = new SpiralGridPositionIterator(rows, cols);
int positionNum = rows * cols; //Start at max and descend
//Fill the array
while(gridPosItr.hasNext()) {
gridPosItr.goToNext();
//System.out.println("[" + gridPosItr.getRowIdx() + "," + gridPosItr.getColIdx() + "]=" + positionNum);
boardPositions[gridPosItr.getRowIdx()][gridPosItr.getColIdx()] = positionNum--;
}
//Display
for(int rowIdx = 0; rowIdx < rows; rowIdx++) {
for(int colIdx = 0; colIdx < cols; colIdx++) {
System.out.print(boardPositions[rowIdx][colIdx] + " ");
}
System.out.println();
}
}
}
The iterator:
class SpiralGridPositionIterator {
//config
public final int rows;
public final int cols;
//state
private int rowIdx;
private int colIdx;
private boolean isColIdxAsc;
//internal
private final int colsMinus1;
private final int rowsMinus1;
public SpiralGridPositionIterator(int rows, int cols) {
this.rows = rows;
this.cols = cols;
colIdx = -1; //MUST initialize to -1 (See "First time is a special case")
rowIdx = 0;
isColIdxAsc = true;
colsMinus1 = cols - 1;
rowsMinus1 = rows - 1;
}
public boolean hasNext() {
if(getRowIdx() < rowsMinus1) {
return true;
}
return (isColIdxAsc
? getColIdx() < colsMinus1
: getColIdx() > 0);
}
public void goToNext() {
if(colIdx == -1) {
//First time is a special case. (See "MUST initialize to -1")
colIdx = 0;
rowIdx = 0;
return;
}
if(!hasNext()) {
throw new NoSuchElementException();
}
if(isColIdxAsc) {
if(getColIdx() < colsMinus1) {
colIdx++;
} else {
//In last column
isColIdxAsc = !isColIdxAsc;
rowIdx++;
}
//ELSE: Descending
} else if(getColIdx() > 0) {
colIdx--;
} else {
//In first column
isColIdxAsc = !isColIdxAsc;
rowIdx++;
}
}
public int getRowIdx() {
return rowIdx;
}
public int getColIdx() {
return colIdx;
}
}
Output:
[C:\java_code\]java SpiralPositionXmpl
100 99 98 97 96 95 94 93 92 91
81 82 83 84 85 86 87 88 89 90
80 79 78 77 76 75 74 73 72 71
61 62 63 64 65 66 67 68 69 70
60 59 58 57 56 55 54 53 52 51
41 42 43 44 45 46 47 48 49 50
40 39 38 37 36 35 34 33 32 31
21 22 23 24 25 26 27 28 29 30
20 19 18 17 16 15 14 13 12 11
1 2 3 4 5 6 7 8 9 10
My program outputs the table like this:
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144
I need to make it look a little better. Need your help.
This is my code:
int a;
int b;
for (a=1; a<=12; ++a)
{
for (b=1; b<=12; ++b)
{
System.out.print(a*b+" ");
}
System.out.println();
}
Use String System.out.printf(""). Like:
System.out.printf("%4d",a*b);
or
System.out.print(String.format("%4d",a*b));
You should use printf in order to format your output.
System.out.printf("%4d", (a*b));
Check the syntax for the format argument here.
Try to give tab space
System.out.print(a * b + "\t");
try
public static void main(String[] args) {
int a;
int b;
int sum;
for (a = 1; a <= 12; ++a) {
for (b = 1; b <= 12; ++b) {
sum = a * b;
System.out.print(sum);
if(sum < 10){
System.out.print(" ");
}else if(sum >= 100){
System.out.print(" ");
}else if(sum >= 10){
System.out.print(" ");
}
}
System.out.println();
}
}
or
public static void main(String[] args) {
int a;
int b;
for (a = 1; a <= 12; ++a) {
for (b = 1; b <= 12; ++b) {
System.out.printf("%4d", (a*b));
}
System.out.println();
}
}
Use:
System.out.print(a*b+"\t");
which uses a escape sequence that will tab each value appropriately.
I sugest to use a table like here
response.getWriter().append("<table><body>");
for (int i = 1; i < width +1 ; i++) {
response.getWriter().append("<tr>");
for (int j = 1; j < height +1; j++) {
response.getWriter().append("<td>").append(String.format("%4d",i*j)).append("</td>");
}
response.getWriter().append("</tr>");
}
response.getWriter().append("</body></table>");
public class JavaApplication21 {
public static void main(String[] args) {
for(int i=1;i<13;i++) {
for(int j=1;j<=12;j++) {
System.out.printf("%d x %d = %d \n",i,j,(i*j));
System.out.println();
}
}
}
}
package rest;
public class doubt {
public static void main (String[] args) {
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
System.out.printf("%4d",i*j);//+i*j+" ");
}
System.out.println("\n");
}
}
}