Java - Vertical Histogram troubleshoot: broken max value? - java

So after much trial and error I converted my horizontal histogram to a vertical one, at least partially.
It seems that instead of reading the highest number of times used, it simply reads the value of the highest-used number:
How many input values [max:30]?
5
Enter 5 numbers.
2
1
2
0
2
Number Occurrence
0 1
1 1
2 3
========= Vertical Bar ========
2 | *
1 | * * *
===============================
| No | 0 1 2 3 4 5 6 7 8 9
===============================
leaves out the max height of 3 and removes an asterisk
How many input values [max:30]?
1
Enter 1 numbers.
5
Number Occurrence
5 1
========= Vertical Bar ========
5 |
===============================
| No | 0 1 2 3 4 5 6 7 8 9
===============================
does not print
5
Enter 5 numbers.
3
3
3
3
3
Number Occurrence
3 5
========= Vertical Bar ========
3 | *
===============================
| No | 0 1 2 3 4 5 6 7 8 9
===============================
prints the wrong max, the wrong number of asterisks, and in the wrong spot
How many input values [max:30]?
10
Enter 10 numbers.
5
4
3
2
1
1
2
3
4
5
Number Occurrence
1 2
2 2
3 2
4 2
5 2
========= Vertical Bar ========
5 |
4 |
3 |
2 | * * * * *
1 | * * * * *
===============================
| No | 0 1 2 3 4 5 6 7 8 9
===============================
adds whitespace for 5-3
10
Enter 10 numbers.
2
2
3
3
3
4
4
4
4
1
Number Occurrence
1 1
2 2
3 3
4 4
========= Vertical Bar ========
4 | *
3 | * *
2 | * * *
1 | * * * *
===============================
| No | 0 1 2 3 4 5 6 7 8 9
===============================
works as intended although not by design
public class Histogram
{
public static void main(String[] args) {
//variables
Scanner keyboard = new Scanner(System.in);
int numInputs = 1, temp, maximum = 0;
int[] numbers = new int[31];
int[] count = new int[31];
boolean success = false;
//start of program
System.out.println("How many input values [max:30]?");
//while no valid input
while (!success) {
try {
numInputs = keyboard.nextInt(); //get a number
numInputChecker(numInputs); //is it valid?
success = true; //ok
} catch (Exception e) //else get a new number
{
keyboard.nextLine();
System.out.println("Whole numbers 1 through 30 only, please.");
}
}
//reset the loop checker
success = false;
//read numbers to fill that array
System.out.println("Enter " + numInputs + " numbers.");
for (int i = 0; i < numInputs; i++) //from 0 to max number
{
while (!success) //while no valid number
{
try {
numbers[i] = keyboard.nextInt(); //fill the current cell with a number
numberChecker(numbers[i]); //is it valid?
success = true; //ok
} catch (Exception e) //else get a new number
{
keyboard.nextLine();
System.out.println("Whole numbers 0 through 9 only, please.");
}
}
success = false;
}
//for cells not used
for (int i = numInputs; i < numbers.length; i++) {
numbers[i] = 10; //fill with garbage data (to prevent false positive 0s)
}
//take the input and count each use of element
for (int i : numbers) //for 0 to max number
{
temp = i; //get the current value of the cell
count[temp]++; //add the use of that value to a new array's cell
}
System.out.println("Number Occurrence");
for (int i = 0; i < count.length; i++) //from 0 to 9 (expected)
{
if ((count[i] > 0) && (count[i] <= 9)) //if cell not empty and has valid data
{
System.out.println(i + " " + count[i]); //print the current cell and how many times it was used
}
}
System.out.println(); //spacer
//histogram segment
//find the highest-used number
for (int i : count) //for each number
{
if(i > maximum) //if greater than the current max
{
maximum = i; //set to max
}
}
System.out.println("========= Vertical Bar ========");
for (int i = maximum; i > 0; i--) //max through 1
{
if ((count[i] > 0) && (count[i] <=9)) //if has valid data
{
System.out.print((i) + "\t | "); // print the number and a nice line for readability
for (int j = 0; j < count.length; j++) //for the number of times that number was used
{
if ((count[j] > 0) && (count[j] <=9)) //if has valid data
{
if (count[j] >= i) //if that number the max
{
System.out.print("* "); //print an asterisk
}
else
{
System.out.print(" "); //"skip" and keep alignment
}
}
}
System.out.println(); //make a new line
}
}
System.out.println("==============================="); //footer
System.out.println("| No | 0 1 2 3 4 5 6 7 8 9");
System.out.println("===============================");
}
static void numInputChecker(int integer) throws Exception
{
if ((integer < 1) || (integer > 30)) //if 0 or negative, or if 31+
{
throw new Exception(); //say no
}
}
static void numberChecker(int integer) throws Exception
{
if ((integer < 0) || (integer > 9)) //if negative or 10+
{
throw new Exception(); //say no
}
}
}

Your problem is that you have too many if blocks in your asterisks output logic. You're deciding not to print anything at some horizontal positions based on the data, when what you really want to do is print two characters (either a space plus an asterisk or two spaces) at each position horizontally, regardless of if you saw any numbers at that position. So your print code gets simpler and does the right thing if you take out all but one if block to arrive at this:
System.out.println("========= Vertical Bar ========");
// for each count, starting from the max...
for (int i = maximum; i > 0; i--)
{
System.out.print((i) + "\t | ");
// for each number from 0 to the largest number we saw
for (int j = 0; j < count.length; j++)
{
// If the count at this position horizontally is greater than or
// equal to the count vertically (the line number we're on), then
// print an asterisk, else print a blank space.
if (count[j] >= i).
{
System.out.print("* ");
}
else
{
System.out.print(" ");
}
}
System.out.println();
}
System.out.println("===============================");
System.out.println("| No | 0 1 2 3 4 5 6 7 8 9");
System.out.println("===============================");
Here's a pretty complicated result that I was using for testing:
Input:
int[] numbers = { 1, 2, 3, 4, 5, 1, 1, 3, 3, 5, 5, 3, 3, 5, 5, 7 };
Result:
Number Occurrence
1 3
2 1
3 5
4 1
5 5
7 1
========= Vertical Bar ========
5 | * *
4 | * *
3 | * * *
2 | * * *
1 | * * * * * *
===============================
| No | 0 1 2 3 4 5 6 7 8 9
===============================

public class Histogram
{
public static void main(String[] args)
{
//variables
Scanner keyboard = new Scanner(System.in);
int numInputs = 1, temp, maximum = 0;
int[] numbers = new int[31];
int[] count = new int[31];
boolean success = false;
//start of program
System.out.println("How many input values [max:30]?");
//while no valid input
while (!success)
{
try
{
numInputs = keyboard.nextInt(); //get a number
numInputChecker(numInputs); //is it valid?
success = true; //ok
} catch (Exception e) //else get a new number
{
keyboard.nextLine();
System.out.println("Whole numbers 1 through 30 only, please.");
}
}
//reset the loop checker
success = false;
//read numbers to fill that array
System.out.println("Enter " + numInputs + " numbers.");
for (int i = 0; i < numInputs; i++) //from 0 to max number
{
while (!success) //while no valid number
{
try
{
numbers[i] = keyboard.nextInt(); //fill the current cell with a number
numberChecker(numbers[i]); //is it valid?
success = true; //ok
} catch (Exception e) //else get a new number
{
keyboard.nextLine();
System.out.println("Whole numbers 0 through 9 only, please.");
}
}
success = false;
}
//for cells not used
for (int i = numInputs; i < numbers.length; i++)
{
numbers[i] = -1; //fill with garbage data (to prevent false positive 0s)
}
//take the input and count each use of element
for (int i : numbers) //for 0 to max number
{
if (i != -1) //if valid data
{
temp = i; //get the current value of the cell
count[temp]++; //add the use of that value to a new array's cell
}
}
System.out.println("Number Occurrence");
for (int i = 0; i < count.length; i++) //from 0 to 9 (expected)
{
if (count[i] > 0) //if cell has valid data
{
System.out.println(i + " " + count[i]); //print the current cell and how many times it was used
}
}
System.out.println(); //spacer
//histogram segment
//find the highest-used number
for (int k : count) //for 0 to 9
{
if (k > maximum) //if greater than the current max
{
maximum = k; //set to max
}
}
System.out.println("========= Vertical Bar ========");
for (int i = maximum; i > 0; i--) // from max to 1
{
System.out.print((i) + "\t | "); //print the number and a spacer for visibility
for (int j = 0; j < count.length; j++) // from 0 to max
{
if (count[j] >= i) // If the count at this position horizontally is greater than or
// equal to the count vertically (the line number we're on)
{
System.out.print("* "); //print an asterisk
}
else
{
System.out.print(" "); //else print a blank
}
}
System.out.println(); //spacer
}
//footer
System.out.println("===============================");
System.out.println("| No | 0 1 2 3 4 5 6 7 8 9");
System.out.println("===============================");
}
static void numInputChecker(int integer) throws Exception
{
if ((integer < 1) || (integer > 30)) //if 0 or negative, or if 31+
{
throw new Exception(); //say no
}
}
static void numberChecker(int integer) throws Exception
{
if ((integer < 0) || (integer > 9)) //if negative or 10+
{
throw new Exception(); //say no
}
}
}

Related

Printing a squares triangle. How to mirror numbers?

So I've been working on this lab for a while now for my programming class and so far I think I'm on the right track.
However, I'm not quite sure how to mirror the numbers. So pretty much, my code is only printing the top half of the triangle. Anyway here is the actual assignment that was given to us:
Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with n rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console:
1
4 1
9 4 1
16 9 4 1
9 4 1
4 1
1
For full credit, each column should be 3 characters wide and the values should be right justified.
Now here is what I have written for my code so far:
import java.util.Scanner;
public class lab6 {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println(
"Enter a number that is between 1 and 9 (inclusive): ");
// this is the value that the user will enter for # of rows
int rows = kybd.nextInt();
for (int i = rows; i > 0; i--) {
for (int j = rows; j > 0; j--)
System.out.print((rows - j + 1) < i ?
" " : String.format("%3d", j * j));
System.out.println();
}
}
}
And this is what that code PRINTS when I enter 4:
Enter a number that is between 1 and 9 (inclusive):
4
1
4 1
9 4 1
16 9 4 1
As you can see, I can only get the TOP half of the triangle to print out. I've been playing around trying to figure out how to mirror it but I can't seem to figure it out. I've looked on this website for help, and all over the Internet but I can't seem to do it.
Answer is:
public static void main(String... args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter a number that is between 1 and 9 (inclusive): ");
int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows
for (int i = -rows + 1; i < rows; i++) {
for (int j = -rows; j < 0; j++)
System.out.print(abs(i) > j + rows ? " " : String.format("%3d", j * j));
System.out.println();
}
}
Try think of this as how to find points(carthesians) that are betwean three linear functions(area of triangle that lied betwean):
y = 0 // in loops i is y and j is x
y = x + 4
y = -x -4
And here is example result for 4:
And 9:
In the outer loop or stream you have to iterate from 1-n to n-1 (inclusive) and take absolute values for negative numbers. The rest is the same.
If n=6, then the triangle looks like this:
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
25 16 9 4 1
16 9 4 1
9 4 1
4 1
1
Try it online!
int n = 6;
IntStream.rangeClosed(1 - n, n - 1)
.map(Math::abs)
.peek(i -> IntStream.iterate(n, j -> j > 0, j -> j - 1)
// prepare an element
.mapToObj(j -> i > n - j ? " " : String.format("%3d", j * j))
// print out an element
.forEach(System.out::print))
// start new line
.forEach(i -> System.out.println());
See also: Output an ASCII diamond shape using loops
Another alternative :
public static void main(String args[]) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter a number that is between 1 and 9 (inclusive): ");
int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows
int row = rows, increment = -1;
while (row <= rows){
for (int j = rows; j > 0; j--) {
System.out.print(rows - j + 1 < row ? " " : String.format("%3d", j * j));
}
System.out.println();
if(row == 1) {
increment = - increment;
}
row += increment;
}
}
The outer loop from 1-n to n-1 inclusive, and the inner decrementing loop from n to 0. The if condition is the absolute value of i should not be greater than n - j.
Try it online!
int n = 6;
for (int i = 1 - n; i <= n - 1; i++) {
for (int j = n; j > 0; j--)
if (Math.abs(i) > n - j)
System.out.print(" ");
else
System.out.printf("%3d", j * j);
System.out.println();
}
Output:
1
4 1
9 4 1
16 9 4 1
25 16 9 4 1
36 25 16 9 4 1
25 16 9 4 1
16 9 4 1
9 4 1
4 1
1
See also: Invert incrementing triangle pattern

Input matrices from a file

I'm trying to read 2D matrices from an input file.The​ ​input​ ​file​ ​contains​ ​a​ ​series​ ​of​ ​inputs.​ ​First​ ​line​ ​contains​ ​the matrix ​size​ ​​n.​Next​ ​​n line​ ​contains​ ​​n ​integer​ ​each,​ ​i.e.,​ ​an​ ​n*n matrix.​​The​ ​file​ ​ends with​ ​a​ ​zero​ ​as​ ​matrix ​size.A small sample is below.
2
1 1
1 1
3
3 1 2
1 1 2
2 2 1
6
1 2 3 4 2 3
3 3 4 5 2 1
4 3 3 1 2 3
5 4 3 6 2 1
3 2 4 3 4 3
2 3 4 1 5 6
0
I wrote the following code but it doesn't show what i need.
import java.util.*;
import java.io.*;
public class trial{
public static void main(String[] args) {
try{
//System.out.println(new File("input.txt").getAbsolutePath());
Scanner input = new Scanner(new File("./input.txt"));
while (true){
int n = input.nextInt();
//System.out.println("%d",n);
if(n!=0) {
int[][] grid = new int[n][n];
while (input.hasNext()) {
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
grid[row][column] = input.nextInt();
System.out.printf(" %d ", grid[row][column]);
}
System.out.println();
}
System.out.println("Array done");
}
}
input.close();
}
}catch (FileNotFoundException e){
System.out.println("File not found");
}
}
}
The code output is below.It always generates a 2*2 matrix.
1 1
1 1
Array done
3 3
1 2
Array done
1 1
2 2
Array done
2 1
6 1
Array done
2 3
4 2
Array done
3 3
3 4
Array done
5 2
1 4
Array done
3 3
1 2
Array done
3 5
4 3
Array done
6 2
1 3
Array done
2 4
3 4
Array done
3 2
3 4
Array done
1 5
6 0
Array done
First of all, it looks like you want to stop if the user inputs a size of 0, but you don't actually do that, instead you just loop forever. Second, after reading the first matrix, you close the scanner, which isn't what you should do. input.close() should be outside the while loop. Try this.
try {
Scanner input = new Scanner(new File("./input.txt"));
int n;
while (input.hasNextInt() && (n = input.nextInt()) > 0) {
int[][] grid = new int[n][n];
for (int row = 0; row < n; row++) {
for (int column = 0;
column < n && input.hasNextInt(); column++) {
grid[row][column] = input.nextInt();
System.out.printf("a %d ", grid[row][column]);
}
System.out.println();
}
System.out.println("Array done");
}
input.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
In your code you are not check when the nextInt is a size and when is a number in matrix . Another thing is that a 0 in size it is for you an EOF , so you shoul get out .
Below a working example :
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
try{
Scanner input = new Scanner(new File("pathtofile"));
while (true){
int n = input.nextInt();
//System.out.println("%d",n);
int cont =0;
if(n!=0) {
int[][] grid = new int[n][n];
while (input.hasNext() && cont != n) {
for (int row = 0; row < n; row++) {
for (int column = 0; column < n; column++) {
grid[row][column] = input.nextInt();
System.out.printf("a %d ", grid[row][column]);
}
System.out.println();
cont++;
}
System.out.println("Array done");
}
}
else{
input.close();
break;
}
}
}catch (FileNotFoundException e){
System.out.println("File not found");
}
}}
Result :

print 2 arrays like matrix for my assignment

I want my output to be like this e.g. if the user inputs 3:
without using 2d array
1 2 3
1 1 2 3
2 1 4 6
3 3 6 9
My code so far
public void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
int[] cloumnarray = new int[i];
int[] rowarray = new int[i];
for (int z = 0; z <= i - 1; z++) {
cloumnarray[z] = z + 1;
rowarray[z] = z + 1;
}
for (int j = 0; j < i; j++) {
System.out.println(cloumnarray[j] * rowarray[j]);
}
}
I tried different options and can't get this to work properly.
public static void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= i; b++) {
// top corner, don't print nothing
if (a == 0 && b == 0) System.out.print("\t");
// top row 0-1, 0-2, 0-3 etc... just 1,2,3...
else if (a == 0) {
System.out.print(b + "\t");
// last line, print extra line break
if (b == i)
System.out.print("\n");
}
// first column 1-0, 2-0, 3-0... just a + space (tabulator)
else if (b == 0) System.out.print(a + "\t");
// any other cases, are candidates to multiply and give result
else System.out.print(a*b + "\t");
}
//look this is out of scope of nested loops, so,
// in each a iteration, print line break :)
System.out.print("\n");
}
}
public static void main(String[] args) throws Exception {
matrixmutilplication();
}
OUTPUT (3)
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
OUTPUT (5)
1 2 3 4 5
1 1 2 3 4 5
2 2 4 6 8 10
3 3 6 9 12 15
4 4 8 12 16 20
5 5 10 15 20 25
But problem (for me) is the numbers are not padded in the natural order, so, to achieve your goal, exactly as in your demo, will need a bit of padding like this
public static void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a <= i; a++) {
for (int b = 0; b <= i; b++) {
if (a == 0 && b == 0) System.out.print("\t");
else if (a == 0) {
System.out.print(String.format("%3s", b));
if (b == i)
System.out.print("\n");
}
else if (b == 0) System.out.print(a + "\t");
else System.out.print(String.format("%3s", a*b));
}
System.out.print("\n");
}
}
public static void main(String[] args) throws Exception {
matrixmutilplication();
}
OUTPUT (7)
1 2 3 4 5 6 7
1 1 2 3 4 5 6 7
2 2 4 6 8 10 12 14
3 3 6 9 12 15 18 21
4 4 8 12 16 20 24 28
5 5 10 15 20 25 30 35
6 6 12 18 24 30 36 42
7 7 14 21 28 35 42 49
What looks quite good :)
So this should be pretty simple.
public void matrixmutilplication() {
String thenumberofmatrix = JOptionPane.showInputDialog(null, "Enter the number of column and rows ");
int i = Integer.parseInt(thenumberofmatrix);
for (int a = 0; a < i; a++) {
for (int b = 0; b < i; b++) {
System.out.print(a*b + "\t");
}
System.out.print("\n");
}
}
Whenever you're working with a matrix involving two arrays (especially if you're trying to a solve a problem that deals with patterns), you want to have a nested for loop like so:
for(int row = 0; row < numSelected; row++) {
for(int col = 0; col < numSelected; col++) {
...
}
}
That way, each cell in the matrix will be covered. Now using that, you can try multiplying the row index and the col index and storing that to the correct cell.

Java Looping Arrays

How do I make this loop properly? it right now So it loops but it does not loop properly. It does this
Here are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 [1]
How many positions do you want to shift?: 2
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3 [3]
How many positions do you want to shift?: 4
the [] are where its suppose to ask me for my input instead of me just putting in a input
its suppose to run like this:
re are the numbers:
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
How many positions do you want to shift?: 1
2 1 15 14 13 12 11 10 9 8 7 6 5 4 3
How many positions do you want to shift?: 4
System.out.println("Here are the numbers:");
for (i=0; i<numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
while (x != input.nextInt()){
System.out.printf("How many positions do you want to shift?: ");
int shiftTimes=input.nextInt();
for( i = 0; i < shiftTimes; ++i)
shift.Shifter(numberArray);
for(j = 0; j < numberArray.length; j++)
System.out.printf(numberArray[j]+" ");
}
}
}
Also How Do I make it exit the program when I enter in a invalid number and how do I get get it to read a negative value and get it to shift left
Edit: heres my shifter code
public static void Shifter(int[] list)
{
int i;
if (list.length < 2) return;
int last = list[list.length - 1];
for(i = list.length - 1; i > 0; i--) {
list[i] = list[i - 1];
}
list[0] = last;
}
This should work for right shift. It should work with inputs larger then array length as well.
for (int i = shiftTimes%numberArray.length; i > 0; i--) {
System.out.print(numberArray[numberArray.length - i] + " ");
}
for (int i = 0; i < numberArray.length - shiftTimes%numberArray.length; i++) {
System.out.print(numberArray[i] + " ");
}
Reversing this logic should produce a left shift approach.
An invalid input would be the length of the array (because the result will be the same) or 0 because that doesn't do anything:
if (shiftTimes == numberArray.length || shiftTimes == 0) {
// present error to user
}
UPDATE: Putting the logic in your function. Also updated the invalid input check.
public static void Shifter(int[] list, int input)
{
for (int i = input%list.length; i > 0; i--) {
System.out.print(list[list.length - i] + " ");
}
for (int i = 0; i < list.length - input%list.length; i++) {
System.out.print(list[i] + " ");
}
}
The function call would be:
Shifter(numberArray, shiftTimes);

How to get the following formatted output?

I wrote the code to get the following formatted output, but when I enter number of rows in double digits, the output format changes. Why? How can I fix this?
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
Here is my code:
import java.util.*;
class PTri {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which " +
"triangle has to be constructed");
int numrow = sc.nextInt();
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= numrow - i; j++) {
System.out.print(" ");
}
for (int k = 1; k < i * 2; k++) {
System.out.print(Math.min(k, i * 2 - k) + " ");
}
System.out.println();
}
}
}
It's because the value in double digit will change the whole architecture.The set will shift to right one place. So you can put a condition like this. I have added one extra space between numbers to improve visibility.
import java.util.*;
class PTri {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which " +
"triangle has to be constructed");
int numrow = sc.nextInt();
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= (numrow - i); j++) {
System.out.print(" ");
}
for (int k = 1; k < i * 2; k++) {
int temp = Math.min(k, i * 2 - k);
if (temp > 9) {
System.out.print(temp + " ");
} else {
System.out.print(temp + " ");
}
}
System.out.println();
}
}
}
In this example I counted the digits, and for every digit I add an extra space.
The output of the value is formatted with leading zeros (digit-count).
public static void main(final String[] args) {
final Scanner sc = new Scanner(System.in);
System.out.println("Enter the no. of rows for which " +
"triangle has to be constructed");
final int numrow = 100;// sc.nextInt();
final int digits = (int) Math.log10(numrow) + 1;
for (int i = 1; i <= numrow; i++) {
for (int j = 1; j <= numrow - i; j++) {
System.out.print(" ");
for (int l = 0; l < digits; l++) {
System.out.print(" ");
}
}
for (int k = 1; k < i * 2; k++) {
final int value = Math.min(k, i * 2 - k);
System.out.print(String.format("%0" + digits + "d ", value));
}
System.out.println();
}
}
You can use String.format method:
"%2d" - format as a two-digit number.
"%02d" - format as a two-digit number with leading zeros.
Example:
// int n = 5;
int n = 12;
// number of digits
int digits = String.valueOf(n).length();
// format string
String format = "%" + digits + "d";
// output
System.out.println("n=" + n + ", format=" + format);
IntStream.rangeClosed(1, n)
.mapToObj(i -> IntStream.rangeClosed(-n, i)
.map(Math::abs)
.map(j -> j = i - j)
.filter(j -> j != 0)
.mapToObj(j -> j > 0 ?
String.format(format, j) : " " .repeat(digits))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
Output:
n=5, format=%1d
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
n=12, format=%2d
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 11 10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 11 12 11 10 9 8 7 6 5 4 3 2 1
See also: Print the sum of the row and column in a 2d array after each row

Categories

Resources