format 12 by 12 multiplication table - java

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");
}
}
}

Related

Need help figuring it out errors with my code

so I need help figuring it out why my code is not including the number 2 and it is including number 99 on the prime printed line. Do I need to change something on my findPrime()? I tried playing with the index and just got worse.
class Sieve {
private int max;
private boolean[] numbers;
public Sieve(int max) {
if (max < 2) {
throw new IllegalArgumentException();
}
this.max = max;
numbers = new boolean[max];
numbers[0] = false;
numbers[1] = false;
numbers[2] = true;
for (int i = 2; i < max-1; i++) {
numbers[i] = true;
}
}
public void findPrimes() {
for (int num = 2; num < max-1; num++) {
int multiples = num + num;
while (multiples < max-1) {
numbers[multiples-1] = false;
multiples += num;
}
}
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int num = 2; num < max; num++) {
if (numbers[num]) {
builder.append(num+1).append(" ");
}
}
return builder.toString();
}
}
class Driver
{
// MAIN. Find some primes.
public static void main(String [] args)
{
Sieve sieve = null; // We must initialize SIEVE or Java will cry.
// 5 points. This must print "Sieve size must be at least 2." but without the
// quotes.
try
{
sieve = new Sieve(0);
}
catch (IllegalArgumentException oops)
{
System.out.println("Sieve size must be at least 2.");
}
// 5 points. This must print nothing.
try
{
sieve = new Sieve(100);
}
catch (IllegalArgumentException oops)
{
System.out.println("Sieve size must be at least 2.");
}
// 10 points. This must print integers from 2 to 99, separated by blanks.
System.out.println(sieve);
// 10 points. This must print the prime numbers between 2 and 99, separated by
// blanks. They are:
//
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
sieve.findPrimes();
System.out.println(sieve);
}
}
It is displaying this, instead of having the number 2 at the beginning and not having the number 99 at the last line of the program.
Sieve size must be at least 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 99
Your toString() method starts looping at num = 2 (which appends num+1 to the output). Your loop should start at 1.
public String toString() {
StringBuilder builder = new StringBuilder();
for (int num = 1; num < max; num++) { . // used to start at 2
if (numbers[num]) {
builder.append(num+1).append(" ");
}
}
return builder.toString();
}
}
Plus your code sets numbers[1] = false. That should be numbers[1] = true.
You are also looping until < max - 1. Consider looping until < max.
I made a few changes to your code the big things to point out is that you don't need max. Your findPrimes() looks ok but is difficult to read and hard to verify for correctness. Your toString() method should be iterating over every element and if that element is true append it to the list.
also 1 is not prime so numbers[1] = false; is as it should be. Why is 1 not a prime number?
class Sieve {
// private int max; // max is superfluous use numbers.length instead
private boolean[] numbers;
public Sieve(int max) {
if (max < 2) {
throw new IllegalArgumentException();
}
numbers = new boolean[max];
numbers[0] = false;
numbers[1] = false;
numbers[2] = true;
for (int i = 2; i <numbers.length; i++) {
numbers[i] = true;
}
}
public void findPrimes() {
// a bit more compact and neater in my opinion
for (int num=2; num<numbers.length; num++) {
for (int multiple=num+num; multiple<numbers.length; multiple+=num) {
numbers[multiple] = false;
}
}
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
// you should be iterating from 0 to 99
for (int i=0; i<numbers.length; i++) {
if (numbers[i]) {
builder.append(i).append(" ");
}
}
return builder.toString();
}
}
class Driver
{
// MAIN. Find some primes.
public static void main(String [] args)
{
Sieve sieve = null; // We must initialize SIEVE or Java will cry.
// 5 points. This must print "Sieve size must be at least 2." but without the
// quotes.
try
{
sieve = new Sieve(0);
}
catch (IllegalArgumentException oops)
{
System.out.println("Sieve size must be at least 2.");
}
// 5 points. This must print nothing.
try
{
sieve = new Sieve(100);
}
catch (IllegalArgumentException oops)
{
System.out.println("Sieve size must be at least 2.");
}
// 10 points. This must print integers from 2 to 99, separated by blanks.
System.out.println(sieve);
// 10 points. This must print the prime numbers between 2 and 99, separated by
// blanks. They are:
//
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
sieve.findPrimes();
System.out.println(sieve);
}
}

Java for loop with discrete values

I need a for loop that its limit could be exceeded after one ends(one of the limits), I like to declare the limit 9 and start traversing an array to index of 8 then start from 9 and take 9 more steps and so on,until I reach the end of the array, my tries reached to this point but I wonder if it works correctly:
int [] i={9,18,27,36,45,54,63,72,81};
for(int x:i){
for(int j=0;j<x;j++)
{}
}
does the nested for loop going to change the x value after each complete cycle of the inner for loop or not?
then start from 9 and take 9 more steps
Your code doesn't behave as you want, since the inner loop always starts at 0.
There's no need to declare the i array. You can do it like this :
int start = 0;
for (int i = 9; i <= 81; i+=9) {
for (int j = start; j < i; j++) {
}
start = i;
}
Or as phflack suggested :
for (int i = 9; i <= 81; i+=9) {
for (int j = i - 9; j < i; j++) {
}
}
you can use this code:
int start = 0;
for (int i = 9; i <= 81; i+=9) {
for (int j = start; j < i; j++) {
System.out.print(j+" ");
}
System.out.println();
start = i;
//System.out.print(start+" ");
}
}
and you see:
0 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 51 52 53
54 55 56 57 58 59 60 61 62
63 64 65 66 67 68 69 70 71
72 73 74 75 76 77 78 79 80
Another training for you:
int start = 0;
for (int i = 1; i <= 10; i++) {
for (int j = 1; j < i; j++) {
System.out.print(j + " ");
}
System.out.println();
}
and you can see:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
You can use two loop to print like matrix.

Spiraling through a 2d array (l-r, down, r-l, down, l-r, ...)

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

for increment java issue

I'm new to Java. I am trying to create a multiplication table with 12 on each side of the table, so 12 going to the right and 12 going down. On each line, we will see the two values multiple. So my plan is to use 12 very similar for statements to print each of the twelve lines. One value will increment within a loop. The issue is, the first line isn't increment my y value. So it just prints out spaced out 1s.
If you have any suggestions on my latter part of the assignment, it'd be helpful. Once I get the first line to print 12 digits, I can make 11 other for statements. But I feel like there may be a simpler way to get the rest of the statements.
public class Sixthree
{
public static void main (String[] args)
{
int x = 1;
int y = 1;
System.out.print(" ");
for ( int c= x*y; y<= 12; y++)
{
System.out.print(c + " ");
}
}
}
I want the out put to look like this to start off with.:
1 2 3 4 5 6 7 8 9 10 11 12
But the current output looks like this:
1 1 1 1 1 1 1 1 1 1 1 1 1
But I want it to eventually like this: http://math.about.com/blgrid.htm
But without the blue lines.
You are getting all 1s because the loop initialization statement int c= x*y will be executed only once for a for loop. That is it is executed the first time when x=1 and y=1 and since, it is given as the loop initialisation statement and not in the loop body, it is never reevaluated. The for loop works as :
The loop initialisation statement is executed only once at the beginning of the loop. After each iteration the loop update expression is executed and the loop condition is reevaluated. for(loop_initialisation;loop_condition;loop_update) { ... }
So you should update c inside the loop, something like :
for ( int c= x*y; y<= 12; y++)
{
c = x*y;
System.out.print(c + " ");
}
for (int i = 1; i <= 12; i++) {
for (int j = 1; j <= 12; j++){
System.out.printf ("%3d ", j * i);
}
System.out.print ("\n");
}
The above code will give you output similar to what is shown below:
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
You should be using two nested for loops, one to iterate over the values of x, another to iterate over the values of y with each inner loop printing the value of x * y and each outer loop printing a new line character for formatting.
// Pseudo-code //
for(each x) {
for(each y) {
print(product);
}
print(newline);
}
Why it just prints out spaced out 1s ?
It is because you just assign c only once in for-loop. for ( int c= x*y; y<= 12; y++)
When value y is incvreasing, value c is not changing. The values is 1*1=1 (x=1, y=1).
As a result, you see it just prints out spaced out 1s.
You can use nested for loop to implement it.
public class Sixteen {
public static void main(String[] args) {
int x = 12;
int y = 12;
for (int i = 1; i <= x; i++) {
for (int j = 1; j <= y; j++) {
System.out.printf("%d ", i * j);
}
System.out.println();
}
}
}
for (int x = 1; x <= 12; x++)
{
for (int y = 1; y <= 12; y++)
{
int multiply = x * y;
System.out.print(multiply + "\t");
}
System.out.println();
}

Java: Is it possible to make line break x times inside for loop?

I tried to Google and search StackOverflow my question but I didn't found any answers to this.
I have made an array where both size and values are randomly generated. When the array values have been printed 20 times I would like to make a line break, but without printing the rest values with always new line.
Here is my code:
public static void catArr() {
Random rändöm = new Random();
int size = rändöm.nextInt(100);
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = rändöm.nextInt(100);
}
Arrays.sort(arr);
for (int i = 0; i < size; i++) {
System.out.print(" " + arr[i]);
if (i > 20)
System.out.println(); //How to do this only once?
else if (i > 40)
System.out.println(); //Same here?
}
}
And this is one of the generated outputs:
3 8 10 25 30 31 34 38 46 50 55 59 62 66 67 68 68 68 72 76 76 81
82
83
84
86
91
92
93
94
94
97
I think that one way to solve this is using 2-D array, but I would like to know if there is another way.
Yay thanks to Patric, I got the wanted result:
0 2 3 7 7 9 11 14 14 16 18 19 24 25 26 28 28 30 30 31
31 33 33 34 41 41 41 42 43 44 45 46 51 51 52 53 59 60 61 62
62 62 63 65 65 67 67 68 69 70 74 74 76 78 82 83 84 84 87 88
89 93 93 94 94 94 95
try using
if ( ( i % 20 ) == 0 ){
System.out.println();
}
if i divided by 20 leaves no remainder then print a new line!
Maybe
if (i % 20==0)
can solve your else if problem.
Use (++i % 20) == 0 and remove i++ from loop; pre-increment avoid first unwanted line break.
Literally, this will do what you seem to want:
if (i == 20)
System.out.println();
else if (i == 40)
System.out.println();
But I have a feeling that you actually want to add a newline after the 20th, 40th, 60th and so on.
if (i % 20 == 0)
System.out.println();
And if you want to output exactly one newline at the end, then you need something like this:
for (int i = 0; i < size; i++) {
if (i > 1 && i % 20 == 1) {
System.out.println();
System.out.print(" " + arr[i]);
}
System.out.println();
You may use boolean for your Sys outs.
boolean myBoolean = true;
if(myBoolean){
//print
myBoolean = false; //set boolean to false.
}
On the other hand, in my preferences, I still stick with my integer flagging.
int isTrue = 1;
if(isTrue == 1){
//print
isTrue = 0;
}

Categories