The following program prints the multiplication table 9xN which N is given by the user. My cells are fixed to be aligned only when the product is 2 numbers long.
What can I do so the cells will be aligned with any size of numbers?
public static void main(String[] args) {
//Reading the number n.
System.out.print("Give a number: ");
int n = StdIn.readInt();
//Validating the number.
while(n<1) {
System.out.println("Please give a number greater or equal to 1");
n = StdIn.readInt();
}
/*---------------------------------
*
*Lines 27-36 -> Creating the first
*line and the first line's design.
*
----------------------------------*/
for (int i = 1; i <= n; i++) {
System.out.printf(" %-4d", i);
}
System.out.println();
System.out.print(" +");
for (int i = 1; i <= n; i++) {
System.out.print("-------+");
}
System.out.println();
/*----------------------------------
*
*Lines 45-58 -> Printing the product
*of the numbers and the design of
*the table.
*
----------------------------------*/
for (int i = 1; i <=9 ; i++) {
System.out.print(i + " | ");
for (int j = 1; j <= n; j++) {
int a = (i * j);
String b = " | ";
System.out.printf("%2d %s", a, b);
}
System.out.println();
System.out.print(" +");
for (int k = 1; k <= n; k++) {
System.out.print("-------+");
}
System.out.println();
}
}
}
What can I do so the cells will be aligned with any size of numbers?
Not Aligned Cells
Aligned Cells
Thanks in advance.
To expand #Thomas Weller's comment a little, you need to separate the table cell value calculation loop from the table printing loop because you need to know the maximum number of digits in any cell before you start printing out the table so the 2 in %2d can be that max value instead.
EDIT: You will also need to know that max value in order to create the correct cell width instead of hard coding "-------+"
Related
I was wondering how to i set a range between certain number when entering numbers in?
Thanks
I tried using a do loop but it just kept looping even when i entered numbers within the range
public static void main(String args[])
{
int row, col, i, j;
int a[][]=new int[10][10];
do{
Scanner sc=new Scanner (System.in);
System.out.println("Enter the order of a square matrix :");
row=sc.nextInt();
col=sc.nextInt();
/* checking order of matrix and then if true then enter the values
* into the matrix a[][]
*/
if(row == col)
{
System.out.println("Enter elements in the matrix:"+row*col);
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
a[i][j]=sc.nextInt();
}
}
} while(row != col);
// Display the entered value
System.out.println ("You have entered the following matrix");
for (i=0; i<row; i++)
{
for (j=0; j<col; j++)
System.out.print (a[i][j] + " ");
System.out.println ();
}
First of all you should learn to extract tasks in methods and add Javadoc to make your code easier to read.
Hope this helps you:
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int dimension;
System.out.println("Enter the dimension of a squared matrix :");
dimension = sc.nextInt();
final int col = dimension;
final int row = dimension;
int[][] matrix = fillMatrix(row, col);
displayMatrix(matrix);
}
/**
* Prints the given matrix to console
*
* #param matrix to be printed
*/
private static void displayMatrix(int[][] matrix) {
System.out.println("You have entered the following matrix");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println();
}
}
/**
* Uses users input to fill create a matrix with the given dimensions
*
* #param row matrix row dimension
* #param col matrix column dimension
*
* #return a filled matrix
*/
private static int[][] fillMatrix(final int row, final int col) {
System.out.println("Enter elements in the matrix:" + row * col);
int[][] matrix = new int[col][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int tmpNumber = 0;
while(tmpNumber<15 || tmpNumber >60){
System.out.println(String.format("Enter value for row %s, column %s between 15 and 60", i, j));
tmpNumber = sc.nextInt();
}
matrix[i][j] = tmpNumber;
}
}
return matrix;
}
Output:
Enter the dimension of a squared matrix :
2
Enter elements in the matrix:4
Enter value for row 0, column 0 between 15 and 60
2
Enter value for row 0, column 0 between 15 and 60
17
Enter value for row 0, column 1 between 15 and 60
18
Enter value for row 1, column 0 between 15 and 60
19
Enter value for row 1, column 1 between 15 and 60
20
You have entered the following matrix
17 18
19 20
First add the bounds as constant
final int LOWER_BOUND = 0;
final int UPPER_BOUND = 100;
Then check in the loop each entered value against the bounds before adding the value to the array
int temp = sc.nextInt();
if (temp >= LOWER_BOUND && temp <= UPPER_BOUND) {
a[i][j] = temp;
} else {
System.out.println("Values has to be between " + LOWER_BOUND + " and " + UPPER_BOUND);
}
The problem remaining is that you can't use you for loops as they are now since the user might need several iterations to enter the right value. One simple solution is to surround the above code in a infinite while loop that is not exited until a correct value is given.
while (true) {
int temp = sc.nextInt();
if (temp >= LOWER_BOUND && temp <= UPPER_BOUND) {
a[i][j] = temp;
break;
} else {
System.out.println("Values has to be between " + LOWER_BOUND + " and " + UPPER_BOUND);
}
}
A better solution might be to replace the innermostfor loop with a while loop where you increase j manually when a correct value has been entered
This is simple example for your cause.
public static void main(String[] args) {
int number;
String getInputLine;
Scanner sc = new Scanner(System.in);
int a[][] = new int[10][10];
// for number of rows in your array
for (int i = 0; i < a.length; i++) {
// for number of columns in your array
for (int j = 0; j < a[0].length; j++) {
// print this message on screen
System.out.print("Enter your number: ");
// get input from next line
getInputLine = sc.nextLine();
//if you haven't match one or more integers
while (!getInputLine.matches("\\d{1,}")) {
System.out.print("Error! You inputted an invalid passcode, try again: ");
getInputLine = sc.nextLine(); // Prints error, gets user to input again
}
number = Integer.parseInt(getInputLine); // parse input into an integer
a[i][j] = number; // store it to array at position i j
System.out.println("You've set number " + number + " for array[" + i + " " + j + "]"); // Prints the passcode
}
}
//print your array
System.out.println(Arrays.deepToString(a));
}
}
It sounds a lot easier than it looks. Basically I have my code finished this is my output where the leading number is whatever integer the program receives as input. In this case n = 5:
1
21
321
4321
54321
but this is what it is suppose to look like:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
How should I go about adding spaces in between my numbers while maintaining this pattern? I've tried editing here and there but it keeps coming out like this:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
My code:
import java.util.Scanner;
public class DisplayPattern {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n) {
final int MAX_ROWS = n;
for (int row = 1; row <= MAX_ROWS; row++) {
for (int space = (n - 1); space >= row; space--) {
System.out.print(" ");
}
for (int number = row; number >= 1; number--) {
System.out.print(number + " "); /*<--- Here is the edit.*/
}
System.out.println();
}
}
Edit:
#weston asked me to display what my code looks like with the second attempt. It wasn't a large change really. All i did was add a space after the print statement of the number. I'll edit the code above to reflect this. Since it seems that might be closer to my result I'll start from there and continue racking my brain about it.
I managed to get the program working, however this only caters to single digit number (i.e. up to 9).
import java.util.Scanner;
public class Play
{
public static class DisplayPattern
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
displayPattern(n);
}
public static void displayPattern(int n)
{
final int MAX_ROWS = n;
final int MAX_COLUMNS = n + (n-1);
String output = "";
for (int row = 1; row <= MAX_ROWS; row++)
{
// Reset string for next row printing
output = "";
for (int space = MAX_COLUMNS; space > (row+1); space--) {
output = output + " ";
}
for (int number = row; number >= 1; number--) {
output = output + " " + number;
}
// Prints up to n (ignore trailing spaces)
output = output.substring(output.length() - MAX_COLUMNS);
System.out.println(output);
}
}
}
}
Works for all n.
In ith row print (n-1 - i) * length(n) spaces, then print i+1 numbers, so it ends with 1 separated with length(n) spaces.
public static void printPiramide(int n) {
int N = String.valueOf(n).length();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1 - i; j++) {
for (int k = 0; k < N; k++)
System.out.print(" ");
}
for (int j = i+1; j > 0; j--) {
int M = String.valueOf(j).length();
for (int k = 0; k < (N - M)/2; k++) {
System.out.print(" ");
}
System.out.print(j);
for (int k = (N - M)/2; k < N +1; k++) {
System.out.print(" ");
}
}
System.out.println();
}
}
public class DisplayPattern{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer and I will display a pattern for you: ");
int n = input.nextInt();
List<Integer> indentList = new ArrayList<Integer>();
int maxLength= totalSpace(n) + (n-1);
for(int i = 1; i <= n; i++ ){
int eachDigitSize = totalSpace(i);
int indent = maxLength - (eachDigitSize+i-1);
indentList.add(indent);
}
for(int row = 1; row<=n; row++){
int indentation = indentList.get(row-1);
for(int space=indentation; space>=0; space--){
System.out.print(" ");
}
for(int number = row; number > 0; number--){
System.out.print(number + " ");
}
System.out.println();
}
}
private static int totalSpace(int n) {
int MAX_ROWS = n;
int count = 0;
for(int i = MAX_ROWS; i >= 1; i--){
int currNum = i;
int digit;
while(currNum > 0){
digit=currNum % 10;
if(digit>=0){
count++;
currNum = currNum/10;
}
}
}
return count;
}
}
It works properly for any number of rows(n).
java-8 solution to the problem:
IntStream.rangeClosed(1, MAX)
.forEach(i -> IntStream.range(0, MAX)
.map(j -> MAX - j)
.mapToObj(k -> k == 1 ? k + "\n" : k <= i ? k + " " : " ")
.forEach(System.out::print)
);
Output for MAX = 5:
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
For the bottom row, you have the right number of spaces. But for the next row from the bottom, you're missing one space on the left (the 4 is out of line by 1 space). In the next row up, you're missing two spaces on the left (the 3 is out of line by 2 spaces)... and so on.
You're adding a number of spaces to the beginning of each line, but you're only taking into account the number of digits you're printing. However, you also need to take into account the number of spaces you're printing in the previous lines.
Once you get that part working, you might also consider what happens when you start to reach double-digit numbers and how that impacts the number of spaces. What you really want to do is pad the strings on the left so that they are all the same length as the longest line. You might check out the String.format() method to do this.
I am trying to create a triangle pyramid of alternating "*" and "o" characters, with the number of rows being based on user input. The expected output I am trying to achieve, if the user inputs "6" for the number of rows, is:
*
*o*
*o*o*
*o*o*o*
*o*o*o*o*
*o*o*o*o*o*
The code I have written to achieve this is:
String star = "*";
String circle = "o";
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; i++){
for (int j = 0; j < rows-i; j++){
System.out.print(star);
}
for (int k = 0; k <= i; k++){
System.out.print(circle);
}
System.out.println();
}
However, the output from my code does not match the pyramid above. The output of my code, with a user input of "6", is:
******o
*****oo
****ooo
***oooo
**ooooo
*oooooo
After spending the last three hours scouring both this website and others, I have still come up lost on how to alternate the characters, how to have the correct number of characters in each row, and how to format the pyramid as the expected output is. I don't know if my code is completely wrong, or if I am only missing a part to make it work correctly, but any advice or references is greatly appreciated.
You could approach it another, far simpler, way.
In pseudo code:
create a String of n spaces
add "*" to it
loop n times, each iteration of the loop:
print it
replace " *" with "*O*"
This recognises a simple way to create the first line, and a simple way to create the next line from the previous line. Each replacement will match only the last (leading) space and the first star, replacing the space with a star, the star with an O and adding a star.
Usually the best way to solve a hard problem is to look at it in a way that makes it a simple problem (or a collection of simple problems).
A couple of ways to create a String of n spaces:
A loop that adds ' ' each iteration
new String(new char[n]).replace('\0', ' ')
How to replace certain characters of a String with other characters:
str = str.replace(" *", "*O*");
This method will work fine:
public void printPyramid (int input) {
for (int row = 1; row <= input; row++) {
for (int whitespace = input - 1; whitespace >= row; whitespace--) {
System.out.print(" ");
}
System.out.print("*");
for (int circle = 1; circle < row; circle++) {
System.out.print("o*");
}
System.out.println();
}
}
*
*o*
*o*o*
*o*o*o*
*o*o*o*o*
*o*o*o*o*o*
*o*o*o*o*o*o*
*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
Welcome to Stack Overflow!
First, the "o"s and "*"s are not alternating because the for loops execute until completion. This means the stars and circles will print out separately. For this application you only need one for loop and two if statements based on whether the "i" in the for loop is odd or even. An easy way to do this is with the modulo function :
String star = "*";
String circle = "o";
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; i++){
if ((i % 2) == 0)
{
System.out.print(circle);
}
else
{
system.out.print(star);
}
System.out.println();
}
See if that works.
Thanks!
Here is a solution, easy to understand and friendly for beginners.
(If you want to go more advanced, look at the solution from #Bohemian♦ )
String star = "*";
String circle = "o";
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; i++){
// How many "o" do we need?
int count_circle = i;
// How many * do we need?
int count_star = count_circle + 1;
// Let's create the string with o and *
String output = "";
for(int j = 0; j < (count_circle + count_star); j++){
if(j % 2 == 0) // if it is odd
output = output + star;
else // if it is even
output = output + circle;
}
// Do we need spaces at the beginning?
String spaces = "";
for(int j = 0; j < rows - i - 1; j++){
spaces = spaces + " ";
}
// Final output
output = spaces + output;
System.out.println(output);
}
Try this.
Scanner in = new Scanner(System.in);
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; ++i) {
System.out.printf("%" + (rows - i) + "s", "*");
for (int j = 0; j < i; ++j)
System.out.print("o*");
System.out.println();
}
Ex:
If rows=3
*##
**#
***
class Main{
public static void main(String x[]){
Scanner scan=new Scanner(System.in);
int rows=scan.nextInt();
for(int i=1;i<rows;i++){
for (int j=0;j<i;j++)
{
System.out.print("*");
}
for (int j=rows;j>i;j--)
{
System.out.print("#");
}
System.out.println();
}
}
}
See if that works.
Thanks!
I want to calculate the sum of all vertical elements in an triangle for example, if the triangle is
Ex : Triangle size is 5
1
2 2
5 2 2
2 0 5 8
8 7 9 4 5
Then the sum should be
Sum1 = 1+2+5+2+8 = 18 (Sum of vertical elements from the first column)
Sum2 = 2+2+0+7 = 11
Sum3 = 2+5+9 = 16
Sum4 = 8+4= 12
Sum5 = 5 = 5
Note : The triangle size will vary, also the elements will be random.
Program I wrote, but it's only calculating the first row how do i calculate and store the 2nd, 3rd and upto the last ?
public class fsdhs
{
public static void main(String args[])
{
int arr[]={1,2,2,5,2,2,2,0,5,8,8,7,9,4,5};
int x,y,count=0,size=5,sum=0;
boolean flag=false;
for(x=0;x<size;x++)
{
for(y=0;y<=x;y++)
{
if(flag==false)
{
sum=sum+arr[count];
flag=true;
}
System.out.print(arr[count]+" ");
count++;
}
System.out.print("\n");
flag=false;
}
System.out.print("\nSum1="+sum);
}
}
You can simplify your code and calculate col sums using the following formula to get index of array by index of i-th row in triangle and j-th column (j<=i, zero-based):
index = i*(i+1)/2 + j
For example, in given triangle at row i=3, column j=2 value is 5, so
index = 3*4/2 + 2 = 8, arr[8] is also 5
A more intuitive approach may be to use a multidimensional jagged array to store the triangle data. This way you can reason over the coordinates directly without needing to calculate row based offsets:
int arr[][]={{1},{2,2},{5,2,2},{2,0,5,8},{8,7,9,4,5}};
int size=5;
for(int x=0; x < size; x++)
{
int sum = 0;
for(int y=x; y < size; y++)
{
sum += arr[y][x];
}
System.out.println("Column " + x + " Sum=" + sum + "\n");
}
You just need to be wary of the uneven row sizes of the jagged array
IdeOne Demo
int SIZE = 5; // The size of your triangle
int arr[]={1,2,5,2,8,2,2,0,7,2,5,9,8,4,5}; // Array of triangle items
int[] sums = new int[SIZE];
for (int i = 0; i < arr.length; i += SIZE, SIZE--) {
for(int j = i; j < i + SIZE; j++) {
sums[sums.length - SIZE] += arr[j];
}
}
// Show items
for (int i = 0; i < sums.length; i++) {
System.out.println("item " + i + ": " + sums[i]);
}
I'm working on a code to produce a 2D array to hold user inputted values. I made a averaging function in the "print array for loop"but it messes up such as when column input (3 1 2) gives an average of output of (2 6 4). All the values of the array were set to 2 for testing. I can't figure out what is wrong with the loop. I'm new to java so I'm sorry if the answer is something obvious.
The table printed should look like this with row(3) and columns(3 1 2):
A:2.0 2.0 2.0 [3.0]
B:2.0 [2.0]
C:2.0 2.0 [2.0]
where the bracketed term holds the average and the 2.0 are the values held by the column.
The code:
// creating 2d array
System.out.print("Please enter number of rows : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
while (rows < 0 || rows >= 10) {
System.out.print("ERROR:Out of range, try again : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
}
double[][] figures = new double[rows][num];
for(int t = 0; t < rows; t++) {
rLetter = (char)((t)+'A');
System.out.print("Please enter number of positions in row " + rLetter + " : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
while((columns < 0) || (columns >= 8)) {
System.out.print("ERROR:Out of range, try again : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
}
figures[t] = new double[columns];
}
// filling the array
for(int row = 0; row < figures.length; ++row) {
for(int col = 0; col < figures[row].length; ++col) {
figures[row][col] = 2.0;
}
}
// printing the array
for(int row=0; row<figures.length; ++row) {
// printing data row
group = (char)((row)+(int)'A');
System.out.print(group+" : ");
for(int col=0; col<figures[row].length; ++col) {
sum += figures[row][col];
average = sum/figures[row].length;
System.out.print(" "+figures[row][col]);
System.out.print(" ");
}
System.out.printf("%1$5s","["+average+"]");
System.out.println();
}
}
PS: its a minor question, I'm using %1$5s to keep the bracket term 5 spaces from the printed columns, but I was wondering if there is a way to keep them all at the same length.
You need to add
sum = 0;
after
for(int row=0; row<figures.length; ++row) {
otherwise the totals are wrong when you calculate the average.
To pad out a string, there's a good answer on here already How can I pad a String in Java?. Look at the 2nd answer.
int minLen = 20;
String s = myformat(value, length);
int diff = minLen - s.length;
System.out.printf("%1$" + diff + "s", s);
Where String s is your formatted string using your above "[" + average + "]" stuff. The idea is that you have a minimum length string to work with so that your positioning is always the same.