How to print a descending/ascending number of spaces in Java? - java

I'm trying to print a figure that prints 3 spaces then a star, then the next line prints 2 spaces, / and a star, and then 1 space, // and a star and so on.
I've got the code to print all the slashes and stars, but I can't figure out how to get the spaces to print with a descending number. This is for an assignment and I have to use nested for loops. Any thoughts?
PS I don't want an exact answer (i.e. "type in this code"), I just want a suggestion to try to point me in the right direction.
What I have so far is (H is the scale):
public class Pattern { //program that prints a boxed-in design
public static final int H = 9;
public static void main(String[] args) {
line();
design();
}
public static void line() {
System.out.print("+");
for (int d=1; d <=H-2; d++) {
System.out.print("-");
}
System.out.println("+");
}
public static void design() {
top();
}
public static void top() {
for (int row = 1; row <=H-2; row++){
System.out.print("|");
for (int sp =3; sp>=1; sp--){
System.out.print(" ");
}
for (int fsl=1; fsl<=row-1; fsl++){
System.out.print("/");
}
for (int star=1; star<=1; star++){
System.out.print("*");
}
for (int bsl=1; bsl<=row-1; bsl++){
System.out.print("\\");
}
System.out.print("|");
System.out.println();
}
}
}

So if I understand correctly, your row variable goes from 1 through 4, and you want 3 spaces in row 1, 2 spaces in row 2, 1 space in row 3 and 0 spaces in row 4? I suggest you should be able to find an arithmetic expression (like you have already found row-1 for the number of slashes) to give you the correct number of spaces on each line/row. If I need to say more, feel free to add a comment to this answer.

package com.acme;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static java.util.Comparator.reverseOrder;
public class PrintIt {
public static void main(String[] args) {
printSpacesWithStar(10, Order.ASC);
printSpacesWithStar(10, Order.DESC);
}
private static void printSpacesWithStar(int numbers, Order order) {
Stream<Integer> streamOfInt = IntStream.rangeClosed(1, numbers)
.boxed();
switch (order) {
case ASC:
streamOfInt
.sorted(reverseOrder())
.forEach(Test::printingLogic);
break;
case DESC:
streamOfInt
.forEach(Test::printingLogic);
break;
}
}
private static void printingLogic(Integer currentValue) {
for (int k = 1; k < currentValue; k++) {
System.out.print(" ");
}
System.out.println("*");
}
enum Order {
ASC, DESC;
}
}

Related

Java: Printing triangles and spaces by calling methods

I'm stuck on this question:
Printing stars and spaces
Define a method called printSpaces(int number) that produces the
number of spaces specified by number. The method does not print the
line break.
You will also have to either copy the printStars method your previous
answer or reimplement it in this exercise template. Printing a
right-leaning triangle
Create a method called printTriangle(int size) that uses printSpaces
and printStars to print the correct triangle. So the method call
printTriangle(4) should print the following: Sample output
> *
> **
> ***
> ****
I cannot get the spaces thing to work on the first question, and I'm totally lost on making the recursive triangle. I see that lots of answers are using for loops, however the class I'm working in wants them done as methods. I can't comprehend how to properly translate that. I got the triangle the other way around with this:
public class Test072 {
public static void main(String[] args) {
printTriangle(4);
}
public static void printTriangle(int size) {
int numSize = 0;
while (numSize < size) {
printStars(numSize);
numSize++;
}
}
public static void printStars(int number) {
int numStar = 0;
while (numStar <= number) {
System.out.print("*");
numStar++;
}
System.out.println();
}
}
Once we started adding spaces in, I totally got lost and have no idea how to call what and when. I don't know how to properly call the space method into the triangle method as they are asking.
This should do the job.
public static void printTriangle(int size) {
int numSize = 0;
while (numSize < size) {
printSpaces(size - numSize - 1);
printStars(numSize);
numSize++;
}
}
public static void printSpaces(int number) {
int numSpaces = 0;
while (numSpaces < number) {
System.out.print(" ");
numSpaces++;
}
}
public static void printStars(int number) {
int numStar = 0;
while (numStar <= number) {
System.out.print("*");
numStar++;
}
System.out.println();
}
}
//printStars is printing "number" numbers of stars on one line with a line break
public static void printStars(int number) {
for(int i=1;i<=number;i++){
System.out.print("*");
}
System.out.println();
}
//printSpaces print "number" number of spaces on one line
public static void printSpaces(int number) {
for(int i=1;i<=number;i++){
System.out.print(" ");
}
}
public static void printTriangle(int size) {
for(int i=1;i<=size;i++){
printSpaces(size-i);
printStars(i);
}
}

Need help converting iterative process to recursive

I am trying to convert the following iterative code:
int rows = 3;
for (int i = 0; i <= rows; i++)
{
for (int j = 0; j < i; j++)
{
System.out.print("*");
}
for (int j = 0; j < rows-i; j++)
{
System.out.print("-");
}
System.out.println();
}
with the output:
---
*--
**-
***
to recursive code. This is for an assignment. I created the iterative code in hopes of being able to figure out how to directly convert it to recursive. Here's my effort of that:
public void stringY(int star, int count){
if (star > 0){
System.out.print("*");
stringY(star - 1, count);
}
}
public void stringX(int dash,int count){
if (dash == -1) {
return;
}else if (dash < count){
System.out.print("-");
stringX(dash - 1, count);
} else if (dash == count){
stringX(dash - 1, count);
}
}
public void printPattern(int n) {
if (n == -1){
return;
} else {
printPattern(n-1);
stringY(n, n);
stringX(n, n);
System.out.println();
}
}
My issue here is that while I get the output I am looking for with regard to the "*" part of the pattern, I have absolutely no clue how to get the "-" part of the pattern. Now being that this is an assignment I don't want any solutions, but any pointers in the right direction are absolutely welcome. I should note that my two requirements are: 1) I have to complete my assignment entirely without using loops and 2) I can use as many helper methods as I need, but the main calling method (printPattern) must stay public void and must continue to only accept integers. Further clarification: The other two methods in the recursive code block are helper methods I created.
First let m = number of '*' to print and let n = number of '-' to print
For each recursion, increment m by 1 and decrement n by 1.
public static void main(String[] args) {
printPattern(3);
}
public static void printPattern(int n) {
printing(n, n);
}
//Variable size basically represent the number of columns
public static void printing(int n, int size) {
//stop condition
if(n == -1)
return;
//m is the number of * to print
int m = size - n;
printAsterisk(m);
//n is the number of - to print
printHyphen(n);
System.out.println();
printing(n - 1, size);
}
public static void printAsterisk(int m) {
if(m == 0)
return;
System.out.print('*');
printAsterisk(m - 1);
}
public static void printHyphen(int n) {
if(n == 0)
return;
System.out.print('-');
printHyphen(n - 1);
}
Think of it this way, they are all just loops doing some work. All you need is theoretically one recursive function that calls itself till the passed value.
void loop(int i, int till, Worker doThis) {
if (i>=till) return;
doThis.work(i);
loop(i+1, till, doThis);
}
Worker is just an interface,
public interface Worker {
void work(int index);
}
Now we need to pass the work that needs to be done. There are three loops, hence three calls to the loop function.
final int rows = 3;
// outer loop
loop(0, rows+1, new Worker() {
public void work(int index) {
// Stars
loop(0, index, new Worker() {
public void work(int index) {
System.out.print("*");
}
});
// Dashes
loop(0, rows-index, new Worker() {
public void work(int index) {
System.out.print("-");
}
});
System.out.println();
}
});
I would start by extracting then STAR and DASH,
private static final String DASH = "-";
private static final String STAR = "*";
Next, I would write a method to repeat a String a given number of times. Also, I would use a StringBuilder (here I've done it recursively)
private static StringBuilder repeat(StringBuilder sb, String str, int n) {
if (n > 0) {
sb.append(str);
repeat(sb, str, n - 1);
}
return sb;
}
Next, a private recursive method to print the pattern based on StringBuilder
private static void printPattern(StringBuilder sb, int s) {
System.out.println(sb);
int p = sb.indexOf(DASH, s);
if (p > -1) {
sb.replace(p, p + DASH.length(), STAR);
printPattern(sb, s + STAR.length());
}
}
And finally the public method
public static void printPattern(int n) {
printPattern(repeat(new StringBuilder(), DASH, n), 0);
}

How can i show alphabets on the top of product table

public class Producttable {
public static void main(String[] args) {
int tableSize = 4;
printMultiplicationTable(tableSize);
}
public static void printMultiplicationTable(int tableSize) {
// first print the top header row
System.out.format(" ");
for(int i = 1; i<=tableSize;i++ ) {
System.out.format("%4d",i);
}
System.out.println();
System.out.println("__________________________");
for(int i = 1 ;i<=tableSize;i++) {
// print left most column first
System.out.format("%4d |",i);
for(int j=1;j<=tableSize;j++) {
System.out.format("%4d",i*j);
}
System.out.println();
}
}
Teacher gave us task to make a product table This is the product table that i am getting with this code
Everything is good here but instead of numbers on the top head of the table i want alphabets like (A B C D). can anybody help me please?
You can make the following changes:
class Producttable {
public static void main(String[] args) {
int tableSize = 4;
printMultiplicationTable(tableSize);
}
public static void printMultiplicationTable(int tableSize) {
// first print the top header row
System.out.format(" ");
for(int i = 1; i<=tableSize;i++ ) {
char c = (char)(64+i);
System.out.format("%4s",String.valueOf(c));
}
System.out.println();
System.out.println("__________________________");
for(int i = 1 ;i<=tableSize;i++) {
// print left most column first
System.out.format("%4d |",i);
for(int j=1;j<=tableSize;j++) {
System.out.format("%4d",i*j);
}
System.out.println();
}
}
}
A computer only knows how to work with numbers. When you work with letters, underneath, the computer is working with numbers. So it stands to reason that you can work with numbers and transform them into letters with the appropriate code.
Refresh your knowledge of the ASCII table, this is what the computer uses to convert numbers into characters.
You could write a loop that started at 65 and stopped at 90, and for each number you could print the character that it corresponds to in the ASCII table. See how I use the "%c" format for printf to format an integer as a character.
for(int i = 65; i <= 90; i++) {
System.out.printf("%c", i);
}
Output:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
Replace
System.out.format("%4d",i);
With
System.out.format("%4c", i + 'A' - 1);

A riddle in java - Java

My friend gave me a riddle to solve. It goes like this:
There are 100 people. Each one of them, in his turn, does the following:
The first person opens all the boxes. The second person change the
state to all the boxes whose number is divided by 2, without
remainders. For instance, if a box is open and its number is divided
by 2, it is closed. The same goes for a closed box.
The third person change the state to all the boxes whose number is
divided by 3, without remainders. The "i" person change the state to
all the boxes whose number is divided by i, without remainders.
Now, at then end of the process, I need to display all the boxes(their
numbers) who are open.
I tried to implement a solution but I think it's not efficient. Here it is:
public class BoxesExc {
public static void main(String[] args) {
Box[] boxes = new Box[100];
// Inflating the array with boxes
for(int i=0; i<boxes.length; i++) {
boxes[i] = new Box(i, false);
}
// Main part:
for(int i=1; i<=boxes.length; i++) {
for(int j=1; j<=i; j++) {
// If the number is even
if(i%2 == 0) {
if(j%i == 0) {
boxes[j].setOpen(!boxes[j].isOpen);
}
}
// If the number is odd
else {
if(j%2 != 0) {
if(j%i == 0) {
boxes[j].setOpen(!boxes[j].isOpen);
}
}
}
}
}
//Displaying the opened boxes:
for(Box box : boxes) {
if(box.isOpen)
System.out.println(box.getNum()+",");
}
}
public static class Box {
private int num;
private boolean isOpen;
public Box(int num, boolean isOpen) {
this.isOpen = isOpen;
}
public int getNum() {
return num;
}
public boolean isOpen() {
return isOpen;
}
public void setOpen(boolean isOpen) {
this.isOpen = isOpen;
}
}
}
I haven't tried that yet but I just by looking at it, it looks awful.
I need your help guys with finding a better solution.
EDIT: Alright guys I managed to solve this. Here is the solution:
public class BoxesExc {
public static void main(String[] args) {
int[] boxes = new int[101];
// Inflating the array with boxes
for(int i=1; i<boxes.length; i++) {
boxes[i] = i;
}
int counter = 0;
for(int i=1; i<boxes.length; i++) {
for(int j=1; j<=i; j++) {
if(i%j == 0)
counter++;
}
if(counter%2 != 0)
System.out.print(""+i+", ");
counter = 0;
}
}
}
it has very simple solution
the boxes which will be opened will be all the boxes which thier place is square exponentiation of a number.
for example in your question its between 1-100 so the answer will be:
1 4 9 16 25 36 49 64 81 100
also my solution is faster than yours because its order is θ(√n)
Iterate through all the boxes and modulate by your current indices. Do a switch to set the box open or closed depending on it's previous state. Then after you're done doing the 100 loop; do a secondary loop through the 100 boxes to see which ones are open and print them out.
Here is a quick implementation of what I described in the comment:
public class BoxesExc {
public static void main(String[] args) {
Box[] boxes = new Box[100];
// Inflating the array with boxes
for(int i=0; i<boxes.length; i++) {
boxes[i] = new Box(i, false);
}
// Main part:
for (int i=1; i < boxes.length; i++) {
// j+=i goes 3,6,9... for i = 3
for (int j = i; j < boxes.length; j+=i) {
boxes[j].setOpen(!boxes[j].isOpen);
}
}
//Displaying the opened boxes:
for(Box box : boxes) {
if(box.isOpen)
System.out.println(box.getNum()+",");
}
}
}
Nota: you can init the box status to open and skip the first iteration (start with i = 2)
Since you only need to print the numbers, I think following is enough:
public class BoxesExc {
public static void main(String[] args) {
int boxNum = 100;
for(int i = 1; i*i <= boxNum; i++) {
System.out.print(i*i+",");
}
}
}

Swap array element in java in accending order

I'm trying to swap an array in ascending order but somewhere I'm going wrong. I'm taking input using
int n = Integer.parse.int(args[0]);
but it isn't working. Below is the full code.
package tech;
import java.util.*;
import java.io.*;
public class Techgig {
public static int ta[]={1,12,5,111,200,1000,10,9,6,7,4};
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Amount Mark has:");
int rs=50;//Integer.parseInt(args[0]);
//int a=0;
System.out.println(rs);
// for(int k=0;k<ta.length;k++)
//System.out.print("\t"+ ta);
int min,temp;
for(int i=0;i<ta.length;i++)
{
min=i;
// System.out.print("\t"+ ta[i]);
for( int j=i+1;j<ta.length;j++)
{
if(ta[i]<ta[min])
{
temp=ta[i];
ta[i]=ta[min];
ta[min]=temp;
}
// System.out.print("\t"+ ta[i]);
}
}
for(int k=0;k<ta.length;k++)
{
System.out.print("\t"+ ta[k]);
}
}
}
You should replace variable i with j here:
if(ta[i]<ta[min])
{
temp=ta[i];
ta[i]=ta[min];
ta[min]=temp;
}
Reason is you are comparing 'i'th index with itself which you assigned to min variable and hence it will never go in your if condition to swap.
You could resolve this as below by using i and j as index and checking between the two:
for(int i=0;i<ta.length;i++)
{
// System.out.print("\t"+ ta[i]);
for( int j=i+1;j<ta.length;j++)
{
if(ta[j]<ta[i])
{
temp=ta[j];
ta[j]=ta[i];
ta[i]=temp;
}
// System.out.print("\t"+ ta[i]);
}
}
Your logic of comparison is wrong.
Refer to the below code. Instead of applying so much logic. Why not just call upon sort method like below?
public static int ta[]={1,12,5,111,200,1000,10,9,6,7,4};
// print all the elements available in array
for (int number : ta) {
System.out.println("Number = " + number);
}
// sorting array
Arrays.sort(ta);
System.out.println("The sorted int array is:");
for (int number : ta) {
System.out.println("Number = " + number);
}

Categories

Resources