hourglass example for java beginners - java

I'm a java beginner and only learned about the scanner class, JOptionPane, loops, and if statements.
I have to create a java program that prints an hour glass shape based on the number the user inputs. The user will also give a character symbol which is what the hourglass shape will consist of. For example if the user enters "4" for shape and "7" for character then it will look this:
8 number "7" on first now. 6 number "7" on second row. 4 number "7" on third row. 2 number "7" on fourth row. 4 number "7" on fifth row. 6 number "7" on seventh row. 8 number "7" on eight row.
Below is a visual representation of this.
77777777
777777
7777
77
7777
777777
77777777
The only instructions I was given was:
To read a character use the following code where scanner is Scanner object:
char symbol = scanner.next().charAt(0);
I would appreciate it if someone could point in the general direction of what code to use.

Here is my solution using your specification and relating the comments to your example.
import java.util.Scanner;
class Hourglass
{
public static void main(String[] args)
{
// construct scanner
Scanner scanner = new Scanner(System.in);
// get the values for the character and the size of the hourglass from the user
System.out.print("Enter a symbol: ");
char symbol = scanner.next().charAt(0);
System.out.print("Enter the size: ");
int size = scanner.nextInt();
// call method to output the hourglass with the user's input
hourGlass(symbol, size);
}
static void hourGlass(char symbol, int size)
{
for (int i = 0; i < size; i++) // loops size times to get the first half + the middle
{
// needs to loop 8,6,4,and 2 times; decreases by 2, hence the 2* and -i from outer loop;
// I used 0 for the outer loop so 2*(size - 0) = 2 * size to start the top line;
for (int j = 1; j <= 2 * (size - i); j++)
{
System.out.print(symbol);
}
System.out.println();
}
for (int i = 0; i < size - 1; i++) // loops 1 less than size times to get the bottom
{
// loop for 4,6,and 8 times; increases by 2 so 2 * i will control this; starts at size so size + (2 * i) = size + (2 * 0) = size
for (int j = 1; j <= size + (2 * i); j++)
{
System.out.print(symbol);
}
System.out.println();
}
}
}

Related

why does displayed number goes above the input number in java?

Currently, I am doing an assignment on displaying all odd numbers up to a user inputted specific odd number. The requirement is to include the input number, however, I don't understand why does the code always goes to the next Odd number compared to what user inputted. Please help.
import java.util.Scanner;
public class OddNumbers {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pls enter an odd number you want to finish to: ");
int capp_number = input.nextInt();
int startingNumber = 1;
for(int i = 0; i < capp_number; i+= 2){
startingNumber += 2;
System.out.println(startingNumber);
}
This is because i starts at 0 (It is even), and you are checking to see if it is less than capp_number (which should be odd), and then adding two to i. startingNumber starts at 1, so it is odd. So if the user enters 5 it will go like:
Iteration 1:
i (0) < 5 ? Yes:
print startingNumber+2
output: 3
i == 2
Iteration 2:
i (2) < 5 ? Yes:
print startingNumber +2
output: 5
i == 4
Iteration 3:
i (4) < 5 ? Yes:
print startingNumber +2
output: 7
i == 6
Iteration 4
i (6) < 5 No:
end loop
To fix this, start i at one:
for(int i = 1; i < capp_number; i+= 2)
Sorry, but why did you write this ?
while(startingNumber < capp_number);
i agree with a previous answer and think that there is no reason for this line. And also you should correct your loop as it was also mentioned in previous answer:for(int i = 0; i < capp_number; i+= 2)
Try this. You needed to initialise i to 1 within the for-loop. 1 is an odd number so instead of starting with an even number (0), you look for every odd number.
For example, if you start at 1: 1+2=3, 3+2=5, 5+2=7.... and so on.
For example, if you start at 0: 0+2=2, 2+2=4, 4+2=6.... and so on.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Pls enter an odd number you want to finish to: ");
int capp_number = input.nextInt();
int startingNumber = 1;
for(int i = 1; i < capp_number; i += 2){
startingNumber += 2;
System.out.println(startingNumber);
}

Print a variable a n number of times in java

My project is to show lines with cardinals, from an initial number and
then varying this number to another number entered.
It starts by asking for a initial number of cardinals (the output must be "###" the number of times asked) and then ask for the final number of cardinals to add. So case, click here 5 initial cardinals and add 3, the program must show a line with 5, another with 6, another with 7 and another with 8 cardinals.
How do I add the cardinals? With if-else?
import java.util.Scanner;
public class P02Cardinais {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter the number inicial of cardinals: ");
int numCardinais = keyboard.nextInt();
System.out.println("Enter the number of cardinals to add: ");
int numCardinaisAdd = keyboard.nextInt();
int i;
for (i = 0; i < numCardinais; i++) {
System.out.print("#");
} System.out.print(" - " + numCardinais);
keyboard.close();
}
}
Example of the output
(number inicial - 2 ; number to add - 3)
## - 2
### - 3
#### - 4
##### - 5
You need 2 loops
one for the number of lines from initial to initial+add
one for the number of # which has to be the index of first loop (limo of j is i)
for (int i = numCardinais; i <= numCardinais+numCardinaisAdd; i++) {
for (int j = 0; j<i; j++) {
System.out.print("#");
}
System.out.println(" - " + i); // new line and index
}

In Java, how can I print a blank line for every 5th row? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
It's basic programming but i'm still not entirely sure how to create a blank line every 5th row. Please help! Thank you!
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("please enter an integer for the length");
int theLength = input.nextInt();
System.out.println("Please enter an integer for the height");
int theHeight = input.nextInt();
System.out.println("Please enter a character");
String character1 = input.next();
// int character = Integer.toString(character1);
for (int i = 0; i < theHeight; i++) { //the outer loop controls the row
for (int j = 0; j < theLength; j++) {// inner loop control
if (j % 6 != 0) { //creates a space for ever 5 character
System.out.print(character1 + " ");
} else System.out.print(" ");
}
System.out.println();
}
}
If I understand your question, you could change your else from a print(" ") to a println; like
if(j%6!=0){ //creates a space for ever 5 character
System.out.print(character1 + " ");
} else {
System.out.println();
}
Your loop is zero based, so the row 0 is divisible by 5 too: if that meet your condition then modify the for loop as follows:
for (int i = 0; i < theHeight; i++) { // the outer loop controls the row
for (int j = 0; j < theLength; j++) {// inner loop control
if (i % 5 != 0) { // creates a space for ever 5 character
System.out.print(character1 + " ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
println("...") method prints the string and moves cursor to a new line, but The print("...") method instead prints just the string, but doesn't move cursor to a new line.
Hope it helps!
how can I print a blank line for every 5th row?
According to your codes, it seems to me you want to create a blank line after every n characters and not after n rows..
Be it you want to print a space or a newline after n rows or columns, you only need a single loop.
Print a newline every 5 characters:
int height = 3, length = 5;
String myChar = "A";
for(int x=0; x<height * length; x++){
System.out.print(myChar + " ");
if( (x+1) % length == 0) // (x+1) so the it won't print newline on first iteration
System.out.println();
}
height * length to get total number of characters to be printed
(x+1), because your x starts from 0, and 0 % 0 = 0.
Output:
A A A A A
A A A A A
A A A A A

My logical program is not giving the correct output?

Question:
The Utopian tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian tree sapling is planted at the onset of the spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles?
Input Format
The first line contains an integer, T, the number of test cases.
T lines follow. Each line contains an integer, N, that denotes the number of cycles for that test case.
Constraints
1 <= T <= 10
0 <= N <= 60
Output Format
For each test case, print the height of the Utopian tree after N cycles.
//FINALLY, HOPE so .. WHAT QUESTION IS SAYING..
INITIALLY VALUE IS 1 .. IF SPRING OCCURS.. IT'S VALUE WILL BE DOUBLED.. THAT MEANS .. IT WILL BE MULTIPLIED BY 2.. BUT IF SUMMER OCCUR IT'S VALUE WILL BE ADDED BY 1...
If i give input:
2 //here 2 is the number of question..
0
1
So, Output must be:
1
2
Another example,
sample of output:
2
3
4
So, Sample of input will be:
6
7
HOPE SO.. YOU UNDERSTAND WHAT QUESTION IS ASKING, HERE NOW WE HAVE TO MAKE A PROGRAM INTO JAVA....
Okay as further i made a program for this..
package com.logical03;
import java.util.Scanner;
public class MainProgram{
public static void main(String[] args){
int num=1;
int[] array=new int[100];
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements=in.nextInt();
System.out.println("Enter the values now: ");
for(int i=1; i<=n_Elements; i++){
array[i]=in.nextInt();
}
for(int i=1; i<=n_Elements; i++){
if(array[i]==0){
System.out.println("\n1");
}
else{
for(int j=1; j<=array[i]; j++){
if(j%2!=0){
num=num*2;
}
else{
num=num+1;
}
}
System.out.println(num);
}
}
}
}
As i run into here .. it adds the second number of question into my output.. Suppose..
If i give input as:
2
3
4
So, output must suppose to be:
6
7
Which is correct!!
But My program gives the output as:
6
27 //which is incorrect..becoz it adds the sum of above number :(
Mistake - int num = 1; should be declared in inside parent loop to refresh it's value.
public static void main(String[] args) {
int[] array = new int[100];
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements = in.nextInt();
System.out.println("Enter the values now: ");
for (int i = 1 ; i <= n_Elements ; i++) {
array[i] = in.nextInt();
}
for (int i = 1 ; i <= n_Elements ; i++) {
int num = 1;
if (array[i] == 0) {
System.out.println("\n1");
} else {
for (int j = 1 ; j <= array[i] ; j++) {
if (j % 2 != 0) {
num = num * 2;
} else {
num = num + 1;
}
}
System.out.println(num);
}
}
}
Output
Enter the number of Questions:
2
Enter the values now:
3
4
6
7
My approach is to take on account that first cycle (2 * height) occurs on odds indexes, and second cicle (1 + height) occurs on even indexes, from 1 to n (inclusive), starting index 0 is always 1.
return IntStream.rangeClosed(1, n)
.reduce(1, (acc, idx) -> idx % 2 != 0 ? acc * 2 : acc + 1);
This is my first contribution, only learning to code and solve algorithms, I had to find a workable solution with simple to follow code credit to http://www.javainterview.net/HackerRank/utopian-tree
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
//receive input
Scanner in = new Scanner(System.in);
//no of test cases
int T=in.nextInt();
//no of cycles
int[] N = new int[T];
for(int i=0;i<T;i++){
N[i]=in.nextInt();
}
int height=1;
for(int i=0;i<N.length;i++){
height=1;
for(int j=1;j<=N[i];j++){
if((j%2) ==1)
height=height*2;
else
height++;
}
System.out.println(height);
}
}
}//this the end of the class

pascal triangle proper formatting java

so I'm currently working on an assignment that I just can't seem to finish. Well I have everything finished but would like the extra credit. I've been looking around the web and can't really seem to find exactly what I'm looking for.
public class PascalTester
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("Welcome to the Pascal's Triangle program!");
System.out.println("Please enter the size of the triangle you want");
int size = kb.nextInt();
int[][] myArray = new int[size][size];
myArray = fillArray(myArray);
//myArray = calculateArray(myArray);
printArray(myArray); //prints the array
}
private static int[][] fillArray(int[][] array)
{
array[0][1] = 1;
for (int i = 1; i < array.length; i++)
{
for (int j = 1; j < array[i].length; j++)
{
array[i][j] = array[i-1][j-1] + array[i-1][j];
}
}
return array;
}
private static void printArray(int[][] array)
{
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
{
if(array[i][j] != 0)
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
}
The only issue that I'm having now is to properly format the output to look like an actual triangle. Any suggestions would be very helpful at this point in time. Thanks in advance
One approach to this, is, assuming you have all numbers formatted to the same width, is to treat the problem as that of centering the lines.
Java Coding left as exercise to reader but essentially:
for lineText : triange lines
leadingSpacesCount = (80/2) - lineText.length();
print " " x leadingSpacesCount + lineText
Try to use the technique at http://www.kodejava.org/examples/16.html to make an array with array.length - i - 1 spaces (need to add the number spaces between numbers.. and 2 number of 2 digit numbers if any..).
Print this array at the start of the outer for loop.
The challenge here is that you want to start printing at the top of the triangle, but you don't know where to center each row until you get to the last (and widest) row of the triangle. The trick is to not print anything until you know how wide the last row is. One way to do this is to generate all the rows as String (or StringBuilder) objects and compute the maximum width. Then, from the top, center each line by first printing an appropriate number of spaces. The correct number of spaces will be
(maxLineLength - currentLine.length()) / 2
Alternatively, you can simply assume a maximum line length and center all lines in that width. If the longer lines exceed the maximum width, then the triangle will be distorted below a certain row. (Just be sure to not try printing a negative number of spaces!)
If anyone is looking for the actual code to do this take a look at my implementation in Java, it's similar to what Craig Taylor mentioned (numbers formatted to the same width) plus it uses an algorithm to compute the elements without memory (or factorials).
The code has comments explaining each step (calculation and printing):
/**
* This method will print the first # levels of the Pascal's triangle. It
* uses the method described in:
*
* https://en.wikipedia.org/wiki/Pascal%27s_triangle#Calculating_a_row_or_diagonal_by_itself
*
* It basically computes the Combinations of the current row and col
* multiplied by the previous one (which will always be 1 at the beginning
* of each pascal triangle row). It will print each tree element to the output
* stream, aligning the numbers with spaces to form a perfect triangle.
*
* #param num
* # of levels to print
*/
public static void printPascalTriangle(int num) {
// Create a pad (# of spaces) to display between numbers to keep things
// in order. This should be bigger than the # of digits of the highest
// expected number and it should be an odd number (to have the same
// number of spaces to the left and to the right between numbers)
int pad = 7;
// Calculate the # of spaces to the left of each number plus itself
// (this is the width of the steps of the triangle)
int stepsWidth = pad / 2 + 1;
// Now calculate the maximum # of spaces from the left side of the
// screen to the first triangle's level (we will have num-1 steps in the
// triangle)
int spaces = (num - 1) * stepsWidth;
for (int n = 0; n < num; n++) {
// Print the left spaces of the current level, deduct the size of a
// number in each row
if (spaces > 0) {
System.out.printf("%" + spaces + "s", "");
spaces -= stepsWidth;
}
// This will represent the previous combination C(n k-1)
int prevCombination = 1;
for (int k = 1; k <= n + 1; k++) {
System.out.print(prevCombination);
// Calculate how many digits this number has and deduct that to
// the pad between numbers to keep everything aligned
int digits = (int) Math.log10(prevCombination);
if (digits < pad) {
System.out.printf("%" + (pad - digits) + "s", "");
}
// Formula from Wikipedia (we can remove that "+1" if we start
// the row loop at n=1)
prevCombination = prevCombination * (n + 1 - k) / k;
}
// Row separator
System.out.println();
}
}
Hope it helps someone!

Categories