import java.util.Scanner;
public class Ideone
{
public static void main(String[] args)
{
int reader;
Scanner kBoard = new Scanner(System.in);
do
{
System.out.println("Insert a number of rows: ");
reader = kBoard.nextInt();
printDiamond(reader);
}while(reader != 0);
}
public static void printWORD(int n)
{
if(n >= 1)
{
System.out.print("SAMPLE");
printWORD(n - 1);
}
}
public static void printTopTriangle(int rows)
{
int x = 1;
for(int j = (rows - 1); j >= 0; j--,x +=2)
{
printSpaces(j);
printWORD(x);
System.out.print("\n");
}
}
public static void printSpaces(int n)
{
if(n >= 1)
{
System.out.print(" ");
printSpaces(n - 1);
}
}
public static void printBottomTriangle(int rows, int startSpaces)
{
int x = 1 + (2*(rows - 1));
for(int j = startSpaces; j <= (rows) && x > 0; j++,x -=2)
{
printSpaces(j);
printWORD(x);
System.out.print("\n");
}
}
public static void printBottomTriangle(int rows)
{
int x = 1 + (2*(rows - 1));
for(int j = 0; j <= (rows - 1) && x > 0; j++,x -=2)
{
printSpaces(j);
printWORD(x);
System.out.print("\n");
}
}
public static void printDiamond(int rows)
{
printTopTriangle((int)rows/2 + 1);
printBottomTriangle((int)rows/2, 1);
}
}
My program is supposed to show a Diamond Shape made out of the word "SAMPLE." But when I run it, it displays a space ship shape. How do I fix this error so it would print a perfect Diamond with the word "SAMPLE"?
Change these methods as follows:
public static void printTopTriangle(int rows)
...
printSpaces(j*6);
public static void printBottomTriangle(int rows, int startSpaces)
...
printSpaces(j*6);
Note: 6 is the length of the constant SAMPLE
Because of the size of "SAMPLE" (6 chars), you have to indent with System.out.print(" "); (ie. 6 spaces not 1).
Runnable demo: http://ideone.com/JHTU6C
NB: I didn't fix anything else (you might want to check if an int exists before asking for it with nextInt())
If you change "SAMPLE" with "*" or any other char you get a diamond shape. You get a space ship shape because you don't put enough spaces in printSpaces method. Number of spaces should be close the number of chars that you print in printWORD method. Put 5 or 6 spaces in printSpaces method and you will get something close to a diamond.
Related
I have to print prime factor of any number in this format. Ex: 32 = 2*2*2*2*2
Heres my code. It works fine for all except for 32, it gives:2*2*2*2*2*
How to avoid the last *.
Heres my code:
public class PF{
public static void pf(int n) {
for(int i = 2; i< n; i++) {
while(n%i == 0) {
System.out.print(i+ "*");
n = n/i;
}
}
if (n > 2) System.out.print(n);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int n = sc.nextInt();
pf(n);
}
Other option, you can avoid the * when n=i in your while loop
public static void pf(int n) {
for (int i = 2; i < n; i++) {
while (n % i == 0) {
System.out.print(i);
if (n != i) {
System.out.print("*");
}
n = n / i;
}
}
if (n > 2)
System.out.print(n);
}
One option is to store the values in a list and print them together like this:
public static void pf(int n) {
List<String> l = new ArrayList<>();
for (int i = 2; i < n; i++) {
while (n % i == 0) {
l.add(String.valueOf(i));
n = n / i;
}
}
System.out.print(String.join("*", l));
if (n > 2) {
System.out.print("*" + n);
}
}
I did this in two ways.
Type 1
public static void pf(int n) {
for(int i = 2; i< n; i++) {
while(n%i == 0) {
System.out.print(i+ "*");
n = n/i;
System.out.print(i>n ? "\b" : ""); //Backspase and remove unwanted character(*) after print
}
}
if (n > 2) System.out.print(n);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int n = sc.nextInt();
pf(n);
}
Type 2
public static void pf(int n) {
for(int i = 2; i< n; i++) {
while(n%i == 0) {
System.out.print(i+ ((i<n) ? "*" : "")); //Skip the unwanted character(*)
n = n/i;
}
}
if (n > 2) System.out.print(n);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number");
int n = sc.nextInt();
pf(n);
}
You have a formatting problem. It makes sense to separate it from the initial calculation; better to deal with different problems separately.
You can generate a list of prime factors and write a method to print the list in the correct format. For this general problem I tend to treat the list as a head with one item that is not preceded by the separator and a tail with all the other entries, each of which is preceded by the separator, your '*' or perhaps a comma in the more common case. Rather than suppressing the separator after the last entry in the list, think of it as suppressing the separator before the first entry. It is easier to identify the first element in a list than the last.
My code is not strict Java, but gives you the general idea.
void printSeparatedList(factorList) {
char separator = '*';
bool firstEntry = true;
for (int factor : factorList) {
if (firstEntry) {
firstEntry = false;
} else {
System.out.print(separator);
}
System.out.print(factor);
}
} // End printSeparatedList
I have a problem in which I need to ask for user input for how many times they wish to roll a die and to create and print that an array that has the rolls requested. So far I can create the array, however another part of the problem is that whenever there are consecutive duplicate rolls I must put parentheses around them. For example inputting 11, creates the array
{1 , 2 , 1 , 4 , 4, 6 , 2 , 3 , 5 , 5 , 5} would print 1 2 1 ( 4 4 ) 6 2 3 ( 5 5 5 )
So far I have written
import java.util.Scanner;
import java.util.Random;
public class HW0603 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many times would you like to roll: ");
System.out.println();
int x = input.nextInt();
run(rolls(x), x);
}
public static int[] rolls(int x) {
Random random = new Random();
int y[] = new int[x];
for (int i = 0; i < x; i++) {
int z = random.nextInt(6) + 1;
y[i] = z;
}
return y;
}
public static void run(int a[], int b) {
for (int i = 1; i < b; i++) {
System.out.print(a[i] + " ");
}
}
}
As for the parentheses I honestly don't know how to start. Using if statements didn't work for me, my if statement variations seem to give me out of bound errors since I compare a[i] to a[i+1] and a[i-1]. Could anyone give me a place to start or some tips to being extracting consecutive duplicates?
you need to compare current item with next item
if equal, print "(" then print the item
make flag paranOpened that you have opened (, so you don't reopen ( again, to avoid this: 1 (2(2(2..., then when curr!=next, based on that flag either print the item or print the item then close the ")"
at end of loop
print lat item (b-1) that was excluded from the loop ..;i < b - 1;.., and check if you have opened "("
your run() method will be like this
static boolean paranOpened = false;
public static void run(int a[], int b) {
for (int i = 0; i < b - 1; i++) {
if (a[i] == a[i + 1]) {
if (!paranOpened) {
paranOpened = true;
System.out.print(" (");
}
System.out.print(a[i] + " ");
} else {
System.out.print(a[i] + " ");
if (paranOpened) {
System.out.print(") ");
paranOpened = false;
}
}
}// for loop
// print last item in array #(b-1)
System.out.print(a[b - 1] + " ");
// check if opened ( , then close it
if (paranOpened) {
System.out.print(") ");
}
}// run()
this is a quick solution, there could be better algorithms
The first problem with you program is that the counter in your run method starts
from 1 which should be zero. Your current program does not print the first element of the array.
then you need to check each element with the next one to see if they are duplicate and if they are open the parenthesis and vice versa.
The last element does not need to be checked so print it outside the loop and close the parenthesis if needed.
By the way you do not need to pass the array size element with it. Just use the array.length method.
public static void run(int a[], int b)
{
boolean pOpen = false;//keep track if parenthesis is open
for (int i = 0; i<a.length; i++)
{
if (i < a.length-1)//prevent out of bound exception
{
if (a[i] == a[i+1] && !pOpen )// check if it is needed to `open or close the parenthesis`
{
System.out.print("(");
pOpen = true;
}
System.out.print(a[i] + " ");
if (a[i] != a[i+1] && pOpen)
{
System.out.print(")");
pOpen = false;
}
}
}
System.out.print(a[a.length-1]);//print the last element
if (pOpen)//close the parenthesis if open
{
System.out.print(")");
}
}
Iterate through your array and keep a boolean that marks if parenthesis have opened.
import java.util.*;
class Ideone
{
public static int[] rolls(int x) {
Random random = new Random();
int y[] = new int[x];
for (int i = 0; i < x; i++) {
int z = random.nextInt(6) + 1;
y[i] = z;
}
return y;
}
public static void run(int a[], int b) {
StringBuilder sb = new StringBuilder();
String out = "";
boolean parens = false;
for (int j = 0; j < a.length; j++)
{
out = "" + a[j]; //by default just add an element
//check for duplicate and build parenthesis
if (j + 1 < a.length && a[j] == a[j+1]) //duplicate found
{
if (!parens) // if no parenthesis
{
parens = true; //start parenthesis
out = "( " + a[j];
}
}
else
{
if (parens) //if parenthesis already started
{
out = a[j] + " )";
parens = false; //stop parenthesis
}
}
sb.append(" " + out);
}
// if the last element occured multiple times
if (parens) //should end parens
{
sb.append(a[a.length-1] + " )");
}
//print out the result
System.out.println(sb.toString());
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner input = new Scanner(System.in);
System.out.print("How many times would you like to roll: ");
System.out.println();
int x = input.nextInt();
run(rolls(x), x);
}
}
You need to use boolean to check whether your parenthesis is open or no.
Here I've tried to create a clean and readable example:
Sample code:
public class HelloWorld {
public static void main(String[] args) {
int arr[] = { 1, 2, 1, 4, 4, 6, 2, 3, 5, 5, 5 };
printConsecutiveInBrace(arr);
}
public static void printConsecutiveInBrace(int arr[]) {
int printFrom = 0;
for (int i = 0; i < arr.length; i++) {
if (i == arr.length - 1 || arr[i] != arr[i + 1]) {
print(arr, printFrom, i);
printFrom = i + 1;
}
}
}
public static void print(int arr[], int printFrom, int printTo) {
if (printFrom < printTo) //Here check: Consecutive Duplicate
System.out.print("( ");
for (int i = printFrom; i <= printTo; i++)
System.out.print(arr[i] + " ");
if (printFrom < printTo)
System.out.print(") ");
}
}
Output:
1 2 1 ( 4 4 ) 6 2 3 ( 5 5 5 )
This question already has an answer here:
java print a triangle
(1 answer)
Closed 6 years ago.
I have to write a program to print out a triangle using "*" via methods. I have to design it to ask the user for a number to represent the number of *'s at the base of the triangle. Then print out the triangle by passing that number to your printUpTriangle() method. The only thing I have an idea about is the actual code to make the triangle which is:
public class Triangle {
public static void triangle(int levels) {
if(levels == 0)
return;
triangle(levels - 1);
for(int y = 0; y < levels; y++) {
System.out.print("*");
}
System.out.println();
}
I have to write two methods: one to return a String containing n copies of s, concatenated in a row & another one that uses your makeRow() method. It should print a right triangle in which the base of the triangle is made of n copies of s, and the vertex of the triangle has a single copy of s on the right (both methods have an int & String as variables).
public static void main (String[] args) throws java.lang.Exception
{
makeTriangle(5);
// change the above line if you need to input the number (5) from the user
}
public static void makeTriangle(Integer base_size)
{
for(int x = 1; x < base_size + 1; x++)
{
System.out.print(makeRow(x, base_size));
System.out.println();
}
}
public static String makeRow(Integer row_num, Integer base)
{
String row = "";
for(int x = base; x >= 0; x--)
{
if (x < row_num) { row += "*"; }
else row += " ";
}
return row;
}
This makes a triangle with the "vertex of the triangle has a single copy of s on the right"
So it will print out
*
**
***
****
*****
public class Triangle {
public static void main(String[] args) {
printTriangle(10);
}
public static String makeRow(int n) {
return String.format("%1$-" + n + "s", "*").replace(" ", "*");
}
public static void printTriangle(int n) {
IntStream.rangeClosed(1, n).mapToObj(Triangle::makeRow).forEach(System.out::println);
}
}
You don't need two methods, just one toString method.
public class Triangle
{
private int width;
/**
This class describes triangle objects that can be displayed
as shapes like this:
*
**
***
*/
public class Triangle
{
private int width;
/**
Constructs a triangle.
#param aWidth the number of * in the last row of the triangle.
*/
public Triangle(int aWidth)
{
width = aWidth;
}
/**
Computes a string representing the triangle.
#return a string consisting of * and newline characters
*/
public String toString()
{
String r = "";
for (int i = 1; i <= width; i++)
{
// Make triangle row
for (int j = 1; j <= i; j++)
r = r + "*";
r = r + "\n";
}
return r;
}
}
And Tester class:
import java.util.Scanner;
/**
This program prints two triangles.
*/
public class TriangleRunner
{
public static void main(String[] args)
{
System.out.println("Please enter number");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Triangle test = new Triangle(i);
System.out.println(test);
}
}
EDIT Realized that the OP needed a RIGHT triangle. I mistakenly made an equilateral triangle. New output is shown below.
If you really have to have another method to print the triangle:
import java.util.Scanner;
public class ICanHasTriangle {
static Scanner input;
static String s = "*";
public static void main(String args[]) {
input = new Scanner(System.in);
System.out.print("How wide will your base be (Enter an integer): ");
int width = input.nextInt();
boolean valid = false;
while (!valid) {
if (width <= 0) {
System.out.println("ERROR. You must enter a positive integer!");
System.out.println();
System.out.print("Try again: ");
valid = false;
width = input.nextInt();
} else {
valid = true;
printUpTriangle(s, width);
}
}
}
public static String printUpTriangle(String s, int width) {
for (int i = 0; i <= width; i++) {
for (int j = 0; j < i + 1; j++) {
System.out.print(s);
}
System.out.println();
}
return s;
}
}
OUTPUT
How wide will your base be (Enter an integer): 0
ERROR. You must enter a positive integer!
Try again: 8
*
**
***
****
*****
******
*******
********
*********
I am trying to print a nested loop that will print two islands and scale depending on what the input is. The goal is to make Exclamation points(!) to make the left island, a line diagonally of asterisks(*), question marks to make the right island and tildas(~) to make the ocean. Any comments on my code would be helpful.
Example of what I am trying to do.
Input a size (must be larger than 1):
5
0 !!~~*
1 !!~*~
2 ~~*~~
3 ~*~??
4 *~~??
Here is my code:
import java.util.Scanner;
public class Two_Islands {
public static void main(String[] args) {
Scanner kbinput = new Scanner(System.in);
//Create Size variable
System.out.println("Input a size: ");
int n = 0; n = kbinput.nextInt();
for (int r = 0; r < n; r++) {
System.out.print(r);
for (int c = 0; c < n; c++) {
if (r+c == n-1) {
System.out.print("*");
} else if (r+c == n-2) {
System.out.print("!");
} else if (r+c == n+2) {
System.out.print("?");
} else {
System.out.print("~");
}
}
System.out.println();
}
kbinput.close();
}
}
Here is my current output.
Input a size:
5
0~~~!*
1~~!*~
2~!*~~
3!*~~?
4*~~?~
try the following:
else if(r+1 < n/2 && c+1 < n/2)
{
System.out.print("!");
}
else if(r+1 > n-n/2 && c+1 > n-n/2)
{
System.out.print("?");
}
I am working on printing a quasi-empty square that looks like the example below (10 asterisks across and 10 down for the 2 columns):
**********
* *
* *
* *
* *
* *
* *
* *
* *
**********
My code cannot dynamically generate squares as specified by the user's input for the number of rows and columns (it is working for 10 rows and 10 columns, but as soon as I change the number to 20, the number of the asterisks does not change. The following is my code:
String STAR = "*";
String star1 = "**********";
int MAX = 10;
for (int row = 0; row <= MAX; row += 1 ) {
for (int col = 0; col <= MAX ; col += 10) {
if (row == 0 && col == 0)
System.out.println(star1);
if (row >= 1 && row <= 4)
System.out.println(STAR + " " + STAR);
if (row == 10 && col == 10)
System.out.println(star1);
}
}
Any help/advice is welcomed regarding the dynamism of the code.
String star = "*";
String space = " ";
int MAX = xxx;
for (int row = 0; row < MAX; row++) {
for (int col = 0; col < MAX; col++) {
if (row == 0 || row == MAX - 1) {
System.out.println(star);
} else if (col == 0 || col == MAX - 1) {
System.out.println(star);
} else {
System.out.println(space);
}
}
}
Look at your nested loop:
for (int col = 0; col <= MAX ; col += 10) {
So when col is 10, you're really only just iterating once... you might as well not have the nested loop at all.
Additionally, both star1 and the string literal with spaces have a fixed number of characters in them, clearly related to the number of columns.
I'm assuming this is homework, so I won't give any more hints than that to start with, but hopefully that'll get you thinking along the right lines...
You should change the 3 occurrences of 10 in your two for loops by the MAX variable, so when the user define another size, your for loop will take his input instead of the 10 value.
Also take a look at your last if statement there where it says if (row == 10 && col == 10) and think about it for a second. Once you have hit 10 rows and 10 columns, you are just going to print your final horizontal line of star1 regardless of what MAX is set too.
Like mentioned above, the nested for loop is unnecessary and can be inefficient if you plan to create larger rectangles in the future (not saying you're going to have to but try to stay away from nested for loops if you can). Instead, just print star1 before your loop begins and after it exits. The body of the loop should be simple enough. Hope this helps.
class Square
{
public static void main(String[] args)
{
String tenStars="**********";
String oneStar="*";
int count=0;
System.out.println(tenStars);
count++;
while(count<=8)
{
System.out.println(oneStar+" "+oneStar);
count++;
}
System.out.print(tenStars);
}
}
this should work
public static void hallowSquare(int side)
{
int rowPos, size = side;
while (side > 0)
{
rowPos = size;
while (rowPos > 0)
{
if (size == side || side == 1 || rowPos == 1 || rowPos == size)
System.out.print("*");
else
System.out.print(" ");
rowPos--;
}
System.out.println();
side--;
}
}
you can use something like this with one user input ... this is working
public static void drawSquare(int size)
{
for(int i=1; i<size ;i++)
System.out.print("*");
System.out.println("");
for(int i=0; i<50 ;i++)
{
System.out.print("*");
for(int j =0; j<size-3; j++)
System.out.print(" ");
System.out.println("*");
}
for(int i=1; i<size ;i++)
System.out.print("*");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
drawSquare(50);
}
you should just create a class in put this inside your class and run it ... I hope this will help you ....
class Star8
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=5;j++)
{
if(i==2||i==3||i==4 )
{
System.out.print("* *");
break;
}
else
{
System.out.print("*");
}
}
System.out.println();
}
}
}
Hope this helps, simplify your thinking mate. Think about the axis x and y and work by that logic. Make a nested loop on ur for loop that passes lines, in each case loop the number of
the size of square and print a space, after the nested loop print the "*".
> for (int b=0;b<ans*2-3;b++)
This nested loop has the max value of b because:
remember that while ur printing, each "*" is distanced from the other by a space, and remember u are only counting space between the first and last column. Meaning all space
between x=0 and x=squaresize, therefore max b should be the space between these 2 coords.
which are: squaresize * 2 /the 2 is for the added spaces/ -3/* -3 because u leave out the first coord(x=0),last coord(x=squaresize), AND 1 space added from the former loop.
import java.util.Scanner;
public class AsteriksSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input= new Scanner(System.in);
int ans;
System.out.print("Enter the size of the side of the square: ");
ans=input.nextInt();
String ast="*";
if (ans>0 && ans<21){
for(int i=0;i<=ans-1;i++){
System.out.print("* ");
}
System.out.println("");
for(int i=1;i<=ans-2;i++){
System.out.print("*");
for (int b=0;b<ans*2-3;b++){
System.out.print(" ");
}
System.out.println("*");
}
for(int i=1;i<=ans;i++){
System.out.print("* ");
}
}
}
}
class square1
{
public static void main(String[] args)
{
String star = "*";
String space = " ";
int MAX = 5;
for (int row = 0; row < MAX; row++)
{
for (int col = 0; col < MAX; col++)
{
if (row == 0 || row == MAX - 1)
{
System.out.print(star);
} else if (col == 0 || col == MAX - 1)
{
System.out.print(star);
} else {
System.out.print(space);
}
}
System.out.println();
}
}
}
This code should do the trick.
package javaPackage;
public class Square {
public static void main(String [] args)
{
for (int i=0;i<=10;i++)
{
for (int j=0;j<=10;j++)
{
if(i==0||i==10){
System.out.print("x");
}
else if(j==0||j==10){
System.out.print("x");
}
else{
System.out.print(" ");
}
}
System.out.println();
}
}
}
If the interpreter sees that you're on the first and last line(i=0 and i=10), it will fill the row with x. Else, it will only print a x at the beginning and the end of the row.
you can use below two methods.
1) One with minimal line of code.
for (int i = 0; i <= 9; i++) {
if (i == 0 || i == 9) {
System.out.println("* * * *");
} else {
System.out.println("* *");
}
}
OR
2) With the help of two for loops
for (int i = 0; i <= 9; i++) {
for (int j = 0; j <= 9; j++) {
if (i == 0 || i == 9) {
System.out.print("*");
} else {
if (j == 0 || j == 9) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
}
System.out.println();
}
Thanks,
Stuti
Here's another solution, a more versatile one. It lets you create a hollow rectangle of height "h" and width "w"
private static void hallowSquare(int h, int w)
{
for(int i=1; i<=h; i++)
{
for(int j=1; j<=w; j++)
{
if (j==1|| j==w || i==1 || i==h )
System.out.print("X");
else
System.out.print(" ");
}
System.out.println();
}
}
import java.util.Scanner;
class Star
{
public static void main(String...args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the row : ");
int row=sc.nextInt();
System.out.print("Enter the column : ");
int column=sc.nextInt();
for(int i=1;i<=column;i++)
{
System.out.print("*");
}
for(int i=row-2;i>=1;i--)
{
System.out.println();
System.out.print("*");
for(int k=1;k<=column-2;k++)
{
if(i<1)
{
break;
}
System.out.print(" ");
}
System.out.print("*");
}
System.out.println();
for(int i=1;i<=column;i++)
{
System.out.print("*");
}
}
}
I am hopeful the code below can help, used very simple coding and have the required result.
a=eval(input('Provide the height of the box: '))
b=eval(input('Provide the width of the box: '))
d=a-2
r=b-2
if a >= 1:
print('*'*b)
if a > 1:
for i in range(d):
print('*',end='')
for i in range(r):
print(' ',end='')
print('*')
print('*'*b,end='')
The result is: