I'm new to coding with Java and I'm having trouble writing this program.
User enters an integer from 0 to 9 and a pyramid is displayed. For ex:
User input: 5
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
This is all I have thus far (I'm truly stumped)
import static java.lang.System.*;
import java.util.Scanner'
import java.util.*;
public class pyramid
{
public pyramid()
{
Scanner scan = new Scanner(System.in);
System.out.println("enter a number between 1 and 20");
int num = scan.nextInt();
for (int i = 0; i < num + 1; i++)
{
for (int j = 0; j < num - 1; j++)
{
System.out.println(" ");
}
}
}
}
Any help is welcome and appreciated. Thanks!
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
pyramid();
}
public static void pyramid() {
Scanner scan = new Scanner(System.in);
System.out.println("enter a number between 1 and 20");
int num = scan.nextInt();
for (int i = 0; i < num + 1; i++) {
for (int j = 0; j < num - i; j++) {
System.out.print(" ");
}
for (int j = i; j > 0; --j) {
System.out.printf("%d ", j);
}
for (int j = 2; j <= i; ++j) {
System.out.printf("%d ", j);
}
System.out.println();
}
}
}
Start tabulating what you know, to find a pattern. Say you have height 3:
······_1
···_2 _1 _2
_3 _2 _1 _2 _3
Where · is a space for alignment purposes, _ a space reserved for the second digit.
Row 0 1 2
Spaces in front 6 3 0 (3 * (num - i - 1))
So you want to loop j to print that number of spaces, then make another loop (not inside j, but after it) to print the descending numbers to 1, then another loop to print ascending numbers back to i+1. Using System.out.printf with format %2d will print the _ space on single-digit numbers.
Related
An example of integers entered would be: 5 9 2 2 1 4 5 5 -1 and my code's output is "5 0". In this example array, I only need it to display "5 ". Try it yourself with any combination of integer input, ending your input with a -1 and you'll get the most frequent integer with a zero. Any ideas why my code does this?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int[] b = new int[21];
for (int i = 0; i < b.length; ++i) { //integer input from user
b[i] = scnr.nextInt();
if (b[i] == -1) { //array input stops when input is -1
break;
}
}
int maxcount = 0;
int element_having_max_freq;
for (int i = 0; i < b.length; ++i) {
int count = 0;
for (int j = 0; j < b.length; ++j) {
if (b[i] == b[j]) {
count = count + 1;
}
}
if (count > maxcount) {
maxcount = count;
element_having_max_freq = b[i];
System.out.println(element_having_max_freq+ " ");
}
}
}
}
Your array is of size 21 and initialized as all zeros. All numbers you don't overwrite with the user input will remain zeros, which means that in the case of your test input 5 9 2 2 1 4 5 5 -1, you get another 12 zeros.
Try placing a breakpoint after the part of the code that parses the user input and have a look at b.
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 want to create a matrix of size N by N where N is a constant value defined globally, for now I just want to create a matrix where N=6. Where I fall short is I want to make it diagonally, like so:
0 1 2 3 4 5
1 0 1 2 3 4
2 1 0 1 2 3
3 2 1 0 1 2
4 3 2 1 0 1
5 4 3 2 1 0
Currently I have this method:
public static void drawMatrix(){
for (int line = 0; line < N; line++){
for (int j = 0; j < N; j++){
System.out.print(j + " ");
}
System.out.println();
}
}
Unfortunately it's only able to print 0 1 2 3 4 5 in every line, so I suppose I need another nested for-loop, however I'm not sure how to set it up.
j is the column number, so it will be the same for all rows. What you need to do is to add or subtract j from the line number, depending on the line number, in order to make a "shift". Since the result could become negative, you will need to add N and mod by N:
if (j > line) {
System.out.print((N-line+j)%N + " ");
} else {
System.out.print((line-j+N)%N + " ");
}
Demo.
You can also rewrite it without an if using a conditional expression:
int sign = j > line ? -1 : 1;
System.out.print((N+sign*(line-j))%N + " ");
Demo.
A little change in your code works
public static void drawMatrix() {
for(int line = 0; line < N; line++) {
for(int j = 0; j < N; j++) {
System.out.print(Math.abs(line - j) + " ");
}
System.out.println();
}
}
I would do something like :
int n=6;
for(int row=0;row<n;row++)
{
for(int col = 0;col<n;col++)
{
System.out.print(abs(col-row) +" ");
}
System.out.println();
}
assuming you can use abs().
I hoped that help your purpose.
This also works :
public static void main(String[] args) {
int N = 6;
int column = 0;
for (int row = 0; row < N; row++) {
for (column = row; column >= 0; column--) //prints till row number reaches 0
System.out.print(column + " ");
for (column = 1; column < N - row; column++)//from 1 to N-row
System.out.print(column + " ");
System.out.println();
}
}
Here is the series :
12345
22345
33345
44445
I tried to solve this but it is not coming correct...
Here is the code :
class q14
{
public static void main ( )
{
int i,j,k;
for (i=1;i<=5;i++)
{
for (j=i;j<=5;j++)
{
for (k=1;k<=i;k++)
{
System.out.print (i + " ");
}
System.out.print (j + " ");
}
System.out.println();
}
}
}
The following block should generate the series as you described it.
int numberOfLines = 4;
int numberOfDigitsPerLine = 5;
for (int i=1; i<numberOfLines+1; i++){
for(int j=1; j<=numberOfDigitsPerLine; j++) {
if(j>=i) {
System.out.print(j);
} else {
System.out.print(i);
}
}
System.out.println();
}
Change numberOfLines and numberOfDigitsPerLine as necessary.
Elaboration:
First you must analyze the series, by the looks of it the first number starts with 1 and goes onward for 5 digits, the second line goes along 5 digits as well up to 5 as previously but it replaces the first digit with 2.
Moving down the numbers we can see a pattern of which the N-th number will have N amount of N digits followed by consecutive digits up to the number 5.
So in my code above I chose max N to be 4 as you described it, and the numbers go up to 5, these are represented by the variables numberOfLines and numberOfDigitsPerLine respectively.
The block itself checks what is N at that point (in my block it is represented by i) and then proceeds to go towards the max number 5, this is done within the j for loop. If j is larger or equal to N then we print j, otherwise we haven't finished printing all of the N's yet so we print N instead.
Here it is:
for (int i = 1; i <= 5; i++)
{
for(int k = 1; k <= i;k++)
System.out.print(i);
for (int j = i + 1; j <= 5; j++)
System.out.print(j);
System.out.print("\n");
}
You dont need a third loop for your series
for (int j=1;j<=5;j++) {
for (int k=1;k<=5;k++){
if(k<=j)
System.out.print (j + " ");
else
System.out.print (k + " ");
}
System.out.println();
}
output
1 2 3 4 5
2 2 3 4 5
3 3 3 4 5
4 4 4 4 5
5 5 5 5 5
Demo
Try this:
for(int i=1;i<=4;i++)
{
for(int j = 1; j<=5;j++)
{
if(i>j)
{
for(int x= 1 ; x<=i;x++)
{
System.out.print(i);
j++;
}
}
System.out.print(j);
}
System.out.println("\n");
}
So close to having this program working but I'm stuck.
What I want it to do is simply print out the numbers that have actual occurrences,
so if the user inputs : 1, 2, 3, 2, 6
It needs to display
1 - 1 times
2 - 2 times
3 - 1 times
6 - 1 times
What I'm actually getting with the same input is something like:
1 - 1 times
2 - 2 times
3 - 1 times
4 - 0 times
5 - 0 times
6 - 1 times
I need to remove the case where there are no occurrences.
import java.util.Arrays;
import java.util.Scanner;
public class CountOccurrences
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
//Create Array for numbers
int numbers[] = new int[100];
//Prompt user input
System.out.println("Enter integers between 1 and 100: ");
//For loop to continue input
for (int i = 0; i < numbers.length; i++) {
int next = input.nextInt();
//Breaks loop if 0 is inputted
if (next==0)
{
break;
}
numbers[i] = next;
}
//Calls on countInts method
int[] count = countInts(numbers);
//Calls on display counts
displayIntCount(count);
}
//Counts each instance of a integer
public static int[] countInts(int[] ints)
{
int[] counts = new int[100];
for(int i = 1; i <=counts.length; i++)
for(int j=0;j<ints.length;j++)
if(ints[j] == i)
counts[i-1]++;
return counts;
}
//Displays counts of each integer
public static void displayIntCount(int[] counts)
{
for (int i = 0; i < counts.length; i++)
System.out.println((i+1) +" - " +counts[i] +" Times");
}
}
Just use a simple if statement to check if counts[i] is not 0, like this:
public static void displayIntCount(int[] counts)
{
for (int i = 0; i < counts.length; i++) {
if (counts[i] != 0) {
System.out.println((i+1) +" - " +counts[i] + " Times");
}
}
}