how to print " * " n number of times using while loop? - java

public class Hello {
public static void pattern() {
int s1 = 3;
while(s1 >= 1) {
System.out.println("*");
s1--;
}
}
public static void main(String [] args){
pattern();
}
}
Actual output:
*
*
*
Expected output:
* * *
* *
*
I would like to print " * " (like the above-expected output) using while loop. I made a while loop controlling the number of columns. I'm not able to make a while loop to control the rows to output "*" in the same line 3 times (next line 2 times and so on).

With just you one loop and some String.repeat() you can draw your pattern
Repeat the leading space, starting and 0, and one more each round
Repeat the pattern depending ong s1, 3 times, then 2 then 1
public static void pattern() {
int s1 = 3;
int s2 = 0; // space counter
while(s1 >= 1) {
System.out.print(" ".repeat(s2));
System.out.println("* ".repeat(s1).trim()); // trim to remove last space
s1--;
s2++;
}
}

int lines = 0, asterisks = 3;
String whiteSpace = "";
while (lines++ < 3) {
System.out.print(whiteSpace);
for (int i = 0; i < 3; i++) {
if (i <= (asterisks - lines)) {
System.out.print("* ");
}
}
whiteSpace += " ";
System.out.println();
}

Related

Drawing an X shape with using only asteriks and recursion

Consider this code.
public static void patternMaker(int start, int max, int direction) {
if (start == 0) {
return;
}
for (int i = 0; i < start; i++) {
System.out.print("*");
}
System.out.println();
if (start == max) {
direction = -1;
}
patternMaker(start +direction, max, direction);
The output looks like this.
Where I need it to look like this
So I basically need the same thing but from the other side,and I need to move one space to the right and every new line.I am not sure how to produce that,I've tried duplicating the direction to get the other part of the X but that did not work out.Also not sure how to move one space to the right every line,I'd assume id need to adjust the direction on every iteration but missing a good idea.Thanks!
When using recursion is required, here is a solution based on your provided code example:
I outsourced the printing-part into a separate method.
public static void patternMaker(int max) {
patternMaker(1, max, 1);
}
public static void patternMaker(int numOfStars, int max, int direction) {
if (numOfStars == 0) {
return;
}
if (numOfStars == max) {
//print the maximum number of stars also before the middle
printPatternLine(numOfStars, max, false);
//print middle part twice
printPatternLine(numOfStars, max, true);
printPatternLine(numOfStars, max, true);
direction = -1;
}
printPatternLine(numOfStars, max, false);
patternMaker(numOfStars + direction, max, direction);
}
private static void printPatternLine(int numOfStars, int max, boolean middle) {
int spacesBefore;
int spacesBetween;
if(middle) {
spacesBefore = numOfStars;
spacesBetween = 0;
} else {
spacesBefore = numOfStars -1;
if(numOfStars == max) {
spacesBetween = 2;
} else {
spacesBetween = (max - numOfStars) * 4 + 2;
}
}
//print the spaces before the stars
for (int i = 0; i < spacesBefore; i++) {
System.out.print(" ");
}
//print first part of stars
for (int i = 0; i < numOfStars; i++) {
System.out.print("*");
}
//print spaces between the stars
for (int i = 0; i < spacesBetween; i++) {
System.out.print(" ");
}
//print second part of stars
for (int i = 0; i < numOfStars; i++) {
System.out.print("*");
}
//linebreak
System.out.println();
}
In the middle section of the X-drawing, the printPatternLine is called multiple times, to print this amount of stars a total of four times for this call of the patternMaker method.
A short explanation of the printPatternLine method:
The spaces before printing the stars and the spaces between the stars are calulated before
The case for the middle section should be self-explaining (no spaces between, spaces before equal to the number of stars)
For the non-middle part
The number of spaces before the stars relates to the position of the first stars for this line (for 1 * no space is printed, for 2 stars 1 space is printed, ...)
The number of spaces between the stars is 2 for the line which is one above the middle (1 space more on each side, 1 star more on each side). For every line that is one line farther away from the middle, the spaces in the middle increases by 4.
If you execute the patternMaker method with only one parameter by calling
patternMaker(3);
it will print this pattern:
* *
** **
*** ***
******
******
*** ***
** **
* *
If you need spaces between the stars, multiply the number of spaces by 2 in front of the for loops and add one space to the star-output like this:
private static void printPatternLine(int numOfStars, int max, boolean middle) {
//...
spacesBefore *= 2;
spacesBetween *= 2;
//...
for (int i = 0; i < numOfStars; i++) {
System.out.print("* ");
}
//...
for (int i = 0; i < numOfStars; i++) {
System.out.print("* ");
}
//...
}
Here is an example-output of patternMaker(3); with spaces:
* *
* * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * *
* *
Edit: An adaption, if the middle part should contain more stars than the line before and after it, is easily possible.

Finding Consecutive Duplicate integers in an array

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 )

toString method letter counter class

So I have this method to count the letters in a sentence and put them into an int array of size 26:
public void countLetters()
{
String upper = sentence.toUpperCase();
int ascii;
for (int k = 0; k <upper.length(); k++)
{
char ch = upper.charAt(k);
if (Character.isLetter(ch))
{
ascii = (int) ch;
ascii -= 65;
count[ascii] += 1;
}
}
}
The count variable is my array and I have the ASCII values and stuff...
What I don't know how to write is the toString method
These are the Javadocs:
/**
* Returns a String containing the letters in the sentence
* and how many times they occurred.
* #return returns a formatted string with only the letters
* that occurred in the string, each on a separate line.
*/
public String toString()
{
StringBuffer a = new StringBuffer();
for (Integer i : count)
{
a.append(i + " ");
}
return a.toString();
//This is what I have so far, but I need to print them out in a format that looks like this:
I sure hope this WORKS!!!
e's = 2
h's = 2
i's = 2
k's = 1
o's = 2
p's = 1
r's = 2
s's = 3
t's = 1
u's = 1
w's = 1
}
He doesn't want us printing out characters that don't appear in the string. The string in his driver program looks like "Aa678 ,.. zZ"; and in my tester it just prints out 0 0 0... 26 times whereas it should print out A's = 2 and Z's = 2.
the tester program looks like
public class LetterCounterDriver
{
public static void main(String[] args)
{
String s = "Aa678 ,.. zZ";
LetterCounter lc = new LetterCounter(s);
System.out.println(lc);
if (lc.toString().equals("a's = 2\nz's = 2\n"))
System.out.println("Works");
else if (strip(lc.toString()).equals(strip("a's = 2\nz's = 2\n")))
System.out.println("Close to working. Check you spacing and capitalization!");
else
System.out.println("Needs some more work");
}
/**
* Removes:
* space -> 32
* (\t) tab -> 9
* (\n) line feed -> 10
* (\f) form feed -> 12
* (\r) return -> 13
*/
private static String strip(String s)
{
String remove = " \t\n\f\r";
String x = "";
for (int k = 0; k < s.length(); k++)
if (remove.indexOf(s.charAt(k)) == -1)
x += s.charAt(k);
return x.toLowerCase();
}
}
The output says
A's = 2 Z's = 2
Needs some more work
Whereas it should say
Works
UPDATE: Here is the full class. Note that I wrote all of this.
import java.util.Arrays;
public class LetterCounter
{
private String sentence;
private int[] count;
/**
* Creates a LetterCounter object
*/
public LetterCounter(String s)
{
count = new int[26];
sentence = s;
}
/**
* Sets all locations in the letter count array to zero
* #postcondition sets all locations in the letter count array to zero
*/
public void zeroArray()
{
for (int k = 0; k < count.length; k++)
count[k] = 0;
}
/**
* Computes the array containing a count for each letter
* in the sentence
* #postcondition computes the counter array for letters a - z
*/
private void countLetters()
{
String upper = sentence.toUpperCase();
int ascii;
for (int k = 0; k <upper.length(); k++)
{
char ch = upper.charAt(k);
if (Character.isLetter(ch))
{
ascii = (int) ch;
ascii -= 65;
count[ascii] += 1;
}
}
}
/**
* Returns a String containing the letters in the sentence
* and how many times they occurred.
* #return returns a formatted string with only the letters
* that occurred in the string, each on a separate line.
*/
public String toString()
{
countLetters();
StringBuffer a = new StringBuffer();
for (int i = 0; i < count.length; i++)
{
int c = count[i];
if (c > 0)
{
char letter = (char) (i + 'a');
a.append(letter).append("'s = ").append(c).append("\n");
}
}
return a.toString();
}
}
//The output is
//a's = 2
//z's = 2
//Needs more work
I hope this will help you.
String upper = "Aa678 ,.. zZ.qammar".toUpperCase();
//your method then following toString
public String toString(){
StringBuffer a = new StringBuffer();
for (int i = 0; i < count.length; i++)
{
int v = count[i];
if(v > 0){
a.append( (char)(i + 65) + "'s = " + v + ", ");
}
}
return a.toString();
}
Output:
A's = 4, M's = 2, Q's = 1, R's = 1, Z's = 2,
Here this should work for you:
public String toString() {
StringBuffer a = new StringBuffer();
for (int i = 0; i < count.length; i++) {
int c = count[i];
if (c > 0) {
char letter = (char) (i + 'a');
a.append(letter).append("'s = ").append(c).append("\n");
}
}
return a.toString();
}
Here are the things that had to change compared to your original code:
We need to iterate using the index because we need the index to get the letter
The current letter is the value of the index + the value of a since we want lower-case letters
The 's = part and a line break at the end were missing
A check whether the current count is larger than 0 was missing
Hope this helps you.

How to print the result in descending order in java?

I managed to get the result if I enter the base and exponent, but the output should be
For example: the output should look like this
>>base:5 exponent: 2
5^2 = 25
5^1 = 5
I need help to put something somewhere to make this happen...
import java.util.Scanner;
public class recursion {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int base = 0;
int expo = 0;
System.out.print("Enter number for base ");
for (int i = 0; i < 1; i++)
base = scanner.nextInt();
System.out.print("Enter number for exponent ");
for (int j = 0; j < 1; j++)
expo = scanner.nextInt();
System.out.println(base + "^" +expo +" = " + pow(base,expo));
}
public static int pow(int x, int p) {
System.out.println(x + "^" +p +" = " );
if (p == 0)
return 1;
if (p % 2 == 0) {
int a = pow(x, (p / 2));
return a * a; // This line
} else {
int a = pow(x, ((p - 1) / 2));
return x * a * a; // This line
}
}
}
Firstly, the following code snippets demands a review:
{
for (int i = 0; i < 1; i++)
/*
* This for loop is unnecessary.
* It asserts that the following clause is run only once,
* which is true for any statements anyway.
*/
// ...
}
return a * a;
} /* if (p % 2 == 0) */ else {
/*
* Statements are unnecessarily nested within else clause.
* The corresponding then clause does not complete normally.
* Moving the following code snippet out of an else block
* would have the same effect, but simplifies the control
* statements.
*/
int a = pow(x, ((p - 1) / 2));
return x * a * a;
}
Within your pow() method, you have a System.out.println() method. You're calling it for debugging, but it's unnecessary as the process returns normally. As you're looking for printing the operations for exponent as "from user-specified exponent -> 1" ("in descending order"), use a loop to print your System.out.println(base + "^" + expo + " = " + TestClass.pow(base, expo));:
do // New!
System.out.println(base + "^" + expo + " = " + TestClass.pow(base, expo));
while (expo-- > 1); // New!
} /* main( args ) */
and you can remove the debugging line in pow().
Example: (>> denotes STDIN)
Enter number for base >> 5
Enter number for exponent >> 2
5^2 = 25
5^1 = 5
Enter number for base >> 4
Enter number for exponent >> 5
4^5 = 1024
4^4 = 256
4^3 = 64
4^2 = 16
4^1 = 4
View a live code demo.
void power(int base, int exp){
//Use for loop to iterate through each exp down to 0
for(int i=exp; i>=0; i--){
int result= exponent(base,i);
System.out.println(base + "^" + i + "=" + result)//Will display result as 5^2=25
}
//Recursively computes the result of b^e.
int exponent(int b, int e){
if(e==0){//Base case occurs when e=0.
return (1);
}
return (b * exponent(b,e-1));
}

How to find sub string of a binary string in java

String s="101010101010";
String sub=""; //substring
int k=2;
package coreJava;
import java.util.Scanner;
public class substring {
public static void main(String args[])
{
String string, sub;
int k, c, i;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to print it's all substrings");
string = in.nextLine();
i = string.length();
System.out.println("Substrings of \""+string+"\" are :-");
for( c = 0 ; c < i ; c++ )
{
for( k = 1 ; k <= i - c ; k++ )
{
sub = string.substring(c, c+k);
System.out.println(sub);
}
}
}
}
take a binary string s="1010011010"; //etc
take one variable k=2;
take another variable i; //which is the length of the sub string(i>k)
now i want to find sub string of the above string, in such a way that if k=2,the number of 1's in sub string must be 2,if k=3,the number of 1's in substring must be 3 and so on...
Output should be like this:
string s="1010011010"
Enter value of k=2;
Enter length of substring i=3;
substring= 101 110 101 011
Create a "window" the length of your desired substrings which you move along the string, maintaining a count of the number of 1s in your current window. Each iteration you move the window along one, testing the next character outside the current window, the first character in the current window and updating the count accordingly. During each iteration, if your count is equal to the desired length, print the substring from the current window.
public class Substring {
public static void main(String[] args) {
String str = "1010011010";
int k = 2;
int i = 3;
printAllSubstrings(str, i, k);
}
private static void printAllSubstrings(String str, int substringLength, int numberOfOnes) {
// start index of the current window
int startIndex = 0;
// count of 1s in current window
int count = 0;
// count 1s in the first i characters
for (int a = 0; a < substringLength; a++) {
if (str.charAt(a) == '1') {
count++;
}
}
while (startIndex < str.length() - substringLength + 1) {
if (count == numberOfOnes) {
System.out.print(str.substring(startIndex, startIndex + substringLength));
System.out.print(" ");
}
// Test next bit, which will be inside the window next iteration
if (str.length() > startIndex + substringLength && str.charAt(startIndex + substringLength) == '1') {
count ++;
}
// Test the starting bit, which will be outside the window next iteration
if (str.charAt(startIndex) == '1') {
count --;
}
startIndex++;
}
}
}
This outputs:
101 011 110 101
Iterate over the characters and count the number of one's. If the counter reaches the desired number, stop iterating and take the substring from index zero to where you got.
String str = "010101001010";
int count = 0;
int k = 2;
int i = 0;
for (; i < str.length() && count < k; ++i)
{
if (str.charAt(i) == '1') count++;
}
You could use regular expressions:
public class BinaryString {
public static void main(String[] args) {
String binary = "11000001101110";
int count = 3;
String regEx = "1{" + count + "}";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(binary);
if (m.find()) {
int startIndex = m.start();
System.out.println("MATCH (#index " + startIndex + "): "+ m.group());
} else {
System.out.println("NO MATCH!");
}
}
}
OUTPUT
MATCH (#index 10): 111

Categories