Make smaller christmas tree - java

So I'm beginning in the world of java programming language and I'm trying to print a christmas tree of X height. So far its working, but if for example the user input 4, it will print 4 rows + the christmas tree stump, wich mean 5. However, I would like it to be 4 INCLUDING the stump.So far I have this:
public class xmas {
public static void main(String[] args)
{
Scanner scan = new Scanner(in);
out.print("please enter a number: ");
int temp = scan.nextInt();
int x = (temp-1)*2 +1;
int y = x/2;
int z = 1;
for(int i=0; i<temp; i++)
{
for(int j=0; j<=y; j++)
{
out.print(" ");
}
for(int k = 0; k<z; k++)
{
out.print("*");
}
out.println();
y--;
z+=2;
}
for(int i =0; i<=x/2; i++)
{
out.print(" ");
}
out.println("*");
}
}
I don't know how to do that. Thanks!

Try using temp-- just after the input, like that:
int temp = scan.nextInt();
temp--;
Or decreasing your loop condition:
for(int i=0; i<temp-1; i++)
Output in both cases:
*
***
*****
*

If you just subtract one from the input, your christmas tree should be the right size. Here's what it would look like (using the Java style conventions):
public class ChristmasTree {
public static void main(String[] args) {
Scanner scanner = new Scanner(in);
out.print("Please enter a number: ");
int temp = scanner.nextInt() - 1; // note the `- 1`
int x = (temp - 1) * 2 + 1;
int y = x / 2;
int z = 1;
for(int i = 0; i < temp; i++) {
for(int j = 0; j <= y; j++) {
out.print(" ");
}
for(int j = 0; j < z; k++) {
out.print("*");
}
out.println();
y--;
z += 2;
}
for(int i =0; i<=x/2; i++) {
out.print(" ");
}
out.println("*");
}
}

Related

Rhombus with letters - Java

I am new to programming and started with learning c# and now java. I came across a task creating a rhombus where the user inputs the height (odd numbers only) and the char for the rhombus.
I created a for loop for the height and another loop for the characters. Here is my output:
h: 7
c: k
k
jkj
ijkji
hijkjih
ghijkjihg
But I want the output to be:
h: 7
c: k
k
jkj
ijkji
hijkjih
ijkji
jkj
k
How can I develop my logic to apply it to my code.
Here is my code:
Scanner in = new Scanner(System.in);
System.out.print("h: ");
int h = in.nextInt();
System.out.print("c: ");
char c = in.next().charAt(0);
if(h%2==0){
System.out.println("Invalid number!");
return;
}
int count = 1;
int space = 1;
for (int i = 2; i < h; i++)
{
for (int spc = h - space; spc > 0; spc--)
{
System.out.print(" ");
}
if (i < h)
{
space++;
}
else {
space--;
}
for (int j = 0; j < count; j++)
{
System.out.print(c);
if (j < count/2)
{
c++;
}
else {
c--;
}
}
if (i < h)
{
count = count + 2;
}
else {
count = count - 2;
}
System.out.println();
}
Any help is highly appreciated.
Your code contains the following flaws:
count and space variables depend on the values of i and h, which makes it very hard to keep track of and understand. You should avoid hidden dependencies in your code in general
you change the value of c all the time. It makes it very hard to keep track of. You should never change its value
your function is too big
strange values like i = 2, count/2, incrementing by 2
incorrect conditions
You have one loop which increments i. What you need is a second loop which decrements the value of i. And you should also use the same approach for printing of the characters (2 loops for both sides). Let me show you:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// load parameters
System.out.print("h: ");
int h = in.nextInt();
System.out.print("c: ");
char c = in.next().charAt(0);
// validate parameters
if (h % 2 == 0) {
System.out.println("Invalid number!");
return;
}
for(int i = 0; i <= h/2; i++) {
printSpaces((h+1) / 2 - i - 1);
printLine(c, i);
System.out.println();
}
for(int i = h/2-1; i >= 0; i--) {
printSpaces((h+1) / 2 - i - 1);
printLine(c, i);
System.out.println();
}
}
private static void printLine(char character, int sideWidth) {
for (int j = sideWidth; j >= 0; j--)
System.out.print((char) (character - j));
for (int j = 1; j <= sideWidth; j++)
System.out.print((char) (character - j));
}
private static void printSpaces(int numberOfSpaces) {
for (int i = 0; i < numberOfSpaces; i++) {
System.out.print(" ");
}
}
which gives you the desired output.
public class Rhombusstar
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter N : ");
int n=sc.nextInt();
System.out.print("Enter Symbol : ");
char c = sc.next().charAt(0);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n-i;j++)
{
System.out.print(" ");
}
for(int j=1;j<=n;j++)
{
System.out.print(c);
}
System.out.println();
}
}
}

The code below reads from a text argument and displays an m x n matrice, I want to pass another text argument and compare it with the first 1

// here is a sample text file below board.txt
/* 4 4
x t x .
. . s .
x . . .
moves.txt lru
l for left, r for right u for up and d for down.
The first text file argument is a board game file on which s represents a start position and t the target.
and the second text file argument is a moves text file. I want to pass the second argument so that I can make those moves across the board file.
*/
public class VGame {
public static void main(String[] args) {
int m = StdIn.readInt();
int n = StdIn.readInt();
String[][] board1 = new String[m][n];
for (int i = 0; i < board1.length; i++) {
// the condition becomes false then gives access back to the outer for loop
for (int j = 0; j < board1[i].length; j++) {
board1[i][j] = StdIn.readString(); //reading from a text files
}
}
// now let's print a two dimensional array in Java for
/*for (char[] a : board1)
{
for (char i : a)
{
System.out.print(i + " ");
} System.out.println("\n");
} */
StdOut.println(m + " " + n);
for (int i = 0; i < board1.length; i++)
{
for (int j = 0; j < board1[i].length; j++)
{
System.out.print(" "+ board1[i][j]);
}
System.out.println();
}
// printing 2D array using Arrays.deepToString() method
//System.out.println("another way to print 2D arrays");
//System.out.println(Arrays.deepToString(board1));
StdOut.println(args[0]);
}
}
this should read the indexes as Integer and then the String line-by-line.
public class Main {
public static void main(String[] args) {
int m = 0;
int n = 0;
Scanner s = new Scanner(System.in);
System.out.print("input m: ");
m = s.nextInt();
System.out.print("input n: ");
n = s.nextInt();
String[][] board1 = new String[m][n];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print("input string: ");
board1[i][j] = s.nextLine();
}
}
s.close();
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
System.out.println(board1[i][j]);
}
}
}
}

Inverse parallelogram

I'm trying to make the output something like this:
I know the problem is in the third loop, but I dont know what to do to make the spacing work for this.
import java.util.Scanner;
public class Tester {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int x, y;
System.out.print("Enter the number of rows: ");
x = in.nextInt();
System.out.print("Enter the number of stars: ");
y = in.nextInt();
//loop for x lines
for(int i = 0; i < x; i++){
//loop for y stars
for(int j = 0; j < y; j++){
System.out.print("* ");
}
System.out.println();
for(int l = 0; l <= i; l--){
System.out.print(" ");
}
}
}
}
You need to do a couple things.
The first is move your last nested for loop (the one that prints spaces) to the beginning of the first for loop. You will also want to remove the space you have added to the for loop that prints the asterisks.
Then, for the output you have showed us, you need to start you main for loop at the end and go backwards.
Try the following:
public static void main (String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int x = in.nextInt();
System.out.print("Enter the number of stars: ");
int y = in.nextInt();
//loop for x lines
//This starts at x and goes toward 0
for(int i = x; i > 0; i--){
//Insert spaces based on line number
//This is at the beginning now
for (int s = 0; s < i; s++)
System.out.print(" ");
//Print y stars
//Removed the space after the asterisk
for(int j = 0; j < y; j++)
System.out.print("*");
System.out.println();
}
}
Tested here and matches the output in your first image
for (int i = 0; i < x; i++){
for (int j = x-1; j > i; j--) {
System.out.print(" ");
}
for(int j = 0; j < y; j++){
System.out.print("*");
}
System.out.println();
}
You have to reorder your for loops. Please note the change in condition in the second for loop in given ode below:
for(int i = 0; i < x; i++){
for(int l = 0; l <= x-i; ++l){
System.out.print(" ");
}
//loop for y stars
for(int j = 0; j < y; j++){
System.out.print("* ");
}
System.out.println();
}
Another way:
String stars = String.format("%0" + y + "d", 0).replace('0', '*');
for (int i=x; i > 0; i--)
{
System.out.println(String.format("%0$"+i+ "s", ' ')+stars);
}
System.out.println(stars);

I have to fill a 2D array with characters and let people search for words (Java)

So I have to fill a 2D array with chars, print out the array, let people search for words, and then print out the number of instances of that word and the array with the instances of that word highlit.
here is my code so far:
import java.util.Scanner;
import java.util.*;
public class testSearchMatrix {
public static void printArray(char[][] myArray){
for(int i = 0; i < myArray.length; i++){
for(int j = 0; j < myArray.length; j++){
System.out.print(myArray[i][j] + " ");
}
System.out.println();
}
}
public static void searchArray(char[][] a){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a query to search: ");
String query = keyboard.next();
int queryNum = 0;
int w = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
if(a[i][j] == query.charAt(w)){
queryNum += 1;
}
}
}
System.out.println(queryNum);
}
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
Random random = new Random();
//Create an alphabet array so I can use this to fill in the searchBox array
char[] alphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
System.out.println("Please choose an array size: ");
int a = keyboard.nextInt();
//Create a square array
char[][] searchBox = new char[a][a];
//Fill in the array with random chars
for(int i = 0; i < searchBox.length; i++){
for(int j = 0; j < searchBox[i].length; j++){
int randNum = random.nextInt(25);
searchBox[i][j] = alphabet[randNum];
}
}
//Implement my method to print the array to the screen
System.out.println("Here is the square matrix with random letters: ");
printArray(searchBox);
System.out.println("Enter a query to search: ");
searchArray(searchBox);
}
}
This will print out my array but I can't seem to get the search to work.
Modified Your searchArray function
public static void searchArray(char[][] a){
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a query to search: ");
String query = keyboard.next();
int queryNum = 0;
String out = null;
int w = 0;
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
if(a[i][j] == query.charAt(w)){
//System.out.println(i+":"+j+a[i][j]);
//w+=1;
if(out==null)
{
out=String.valueOf(a[i][j]);
}else
out=out+a[i][j];
for(int f = 1; f < query.length(); f++){
if(j+f<5){
if(a[i][j+f] == query.charAt(w+f)){
// System.out.println(i+"Index:w+f"+w+f+query.charAt(w+f)+"query.charAt(w+f)Index"+query.indexOf(query.charAt(w+f)));
// System.out.println(i+":"+j+a[i][j+f]);
out=out+a[i][j+f];
System.out.println(out+":"+query+"here"+out.length()+query.length());
if(out.equals(query))
{
System.out.println("Seach Found ");
queryNum += 1;
out=null;
}
}
}
} if(out!=null)
if(out.equals(query))
{
System.out.println("Seach Found ");
queryNum += 1;
out=null;
}
out=null;
}
}
}
System.out.println(queryNum);
}
OuptPut

I want create a power pyramid of “*” with Java.

Input: base=2, row = 3
Output:
**
****
********
Input: base=3, row = 3
Output:
***
*********
***************************
I have tried this way, but I spaces aren't printing properly.
import java.util.Scanner;
public class loops {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter base:");
int base = s.nextInt();
System.out.println("enter height:");
int h = s.nextInt();
for (int i = 1; i <= h; i++) {
int num = (int)Math.pow(base, i);
for(int n=h-1; n>i-1; n--) {
System.out.print(" ");
}
for (int j = 0; j < num; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
import java.util.Scanner;
public class loops {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter base:");
int base = s.nextInt();
System.out.println("enter height:");
int h = s.nextInt();
int spacesNum;
int asterisksNum;
for (int i = 1; i <= h; i++) {
spacesNum = (int) ((Math.pow(base, h) - Math.pow(base, i)) / 2);
asterisksNum = (int) (Math.pow(base, i));
for (int j = 0; j < spacesNum; j++) {
System.out.print(" ");
}
for (int j = 0; j < asterisksNum; j++) {
System.out.print("*");
}
System.out.println();
}
s.close();
}
}
The width of space grows geometrically, just like the width of the rings, but in the opposite direction -- it's decaying. Probably the easiest way to code it is to think about the total width, and what you're taking away from it with each ring.
Your code with that taken into account:
public class loops {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter base:");
int base = s.nextInt();
System.out.println("enter height:");
int h = s.nextInt();
int width = (int) Math.pow(base, h); // Note the total width.
for (int i = 1; i <= h; i++) {
int num = (int) Math.pow(base, i);
// The space is half of what's left after removing the ring.
for(int j = 0; j < (width - num)/2; j++) {
System.out.print(" ");
}
for (int j = 0; j < num; j++) {
System.out.print("*");
}
System.out.println("");
}
}
}
Your code calls System.out.print method exponential times, one call per character.
Also, System.out.println is invoked in every iteration which causes the underlying stream to flush. (refer links from michaelt in the comments).
This SO answer is a good reference.
This is NOT good approach because:
h number of I/O operations are performed, which is expensive.
So many method invocations of print and println reduces the readability of the code.
Compose the strings in a separate method and use System.out.print only for printing.
Please refer the code below:
public static void main(String[] args) {
//your code here
int totalWidth = (int) Math.pow(base, h);
String output = "";
for (int i = 1; i <= h; i++) {
int numOfStars = (int) Math.pow(base, i);
int numOfSpace = (int) ((totalWidth - numOfStars) / 2);
output += composeString(' ', numOfSpace).concat(composeString('*', numOfStars ).concat("\n"));
}
System.out.println(output);
}
//Method to create String with same character repeated X number of times
public static String composeString(char character, int x) {
StringBuilder buf = new StringBuilder(x);
while (buf.length() < x) {
buf.append(character);
}
return buf.toString();
}

Categories