Creating a User-Input Asterisk Triangle using Java - java

I want to...
create an asterisk triangle, using Java, that matches the length of whatever number (Between 1-50) the user enters.
Details
The first line would always start with an asterisk.
The next line would increment by one asterisk until it matches the
user's input.
The following lines would then decrement until it is back to one
asterisk.
For instance, if the user was to enter 3, then the output would have one asterisk on the first line, two asterisks on the second line, three asterisks on the third line, and then revert back to two asterisks on the following line before ending with an asterisk on the last line.
What I've tried so far
I am required to use nested for loops. So far, I tried to test it out using this practice example I made below. I was only able to create on output of the numbers. I also have some concepts of outputting asterisk triangles. How can I apply the concept of this code to follow along the user's input number?
import java.util.Scanner;
public class Program
{
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int count, index = 0, value, number;
System.out.println("This program creates a pattern of numbers " );
System.out.println("Based on a number you enter." );
System.out.println("Please enter a positive integer. " );
count = keyboard.nextInt();
value = count;
for (index = 1; index <= count; index++)
{
for (number = value; number >= 1; number--)
{
System.out.println(number);
}
value--;
System.out.println();
}
}
}

Here's how i would proceed
write a method printAsterisks that takes an int N as parameter and writes a line of N asterisks. You wil need a for loop to do so.
call printAsterisks in a for loop that counts from 1 to COUNT
call printAsterisks in a second loop that counts down from COUNT-1 to 1
That should do the trick.
Also, as a side note, you should close your scanner. The easy way to do so is enclose ot in a try-with-resource like so :
try (Scanner keyboard = new Scanner(System.in);) {
// your code here
}
Let us know the version of the program taht works (or the question you still have) :)
HTH

Here is what you want:
public class Asterisk {
private static final String ASTERISK = "*";
private static final String SPACE = "";
private static int LENGTH;
public static void main(String[] args) {
try{
readLength();
for (int i=1; i<=LENGTH; i++) {
if (i == LENGTH) {
for (int j=LENGTH; j>=1; j--) {
drawLine(j);
}
break;
}
drawLine(i);
}
}catch (Exception e) {
System.out.println("You must enter a number between 1 and 50.");
}
}
static void readLength(){
System.out.println("Enter asterisk's length (1-50)");
LENGTH = Integer.parseInt(System.console().readLine());
if (LENGTH<=0 || LENGTH>50)
throw new NumberFormatException();
}
static void drawLine(int asterisks){
StringBuilder line = new StringBuilder();
int spacesLeft = getLeftSpaceCount(asterisks);
int spacesRight = getRightSpaceCount(asterisks);
for (int i=0; i<spacesLeft; i++) {
line.append(SPACE);
}
for (int i=0; i<asterisks; i++) {
line.append(ASTERISK);
}
for (int i=0; i<spacesRight; i++) {
line.append(SPACE);
}
System.out.println(line.toString()+"\n");
}
static int getLeftSpaceCount(int asterisks){
int spaces = LENGTH - asterisks;
int mod = spaces%2;
return spaces/2 + mod;
}
static int getRightSpaceCount(int asterisks){
int spaces = LENGTH - asterisks;
return spaces/2;
}
}
I am required to use nested for loops
Yes, the main logic lies there...
for (int i=1; i<=LENGTH; i++) {
if (i == LENGTH) {
for (int j=LENGTH; j>=1; j--) {
drawLine(j);
}
break;
}
drawLine(i);
}
The triangle using 5 as input.
*
**
***
****
*****
****
***
**
*
Tip:
There is an easier way to get input from the user usingSystem.console().readLine().

In regards to the printing part, I wanted to clean up the answers a little:
int input = 3; //just an example, you can hook in user input I'm sure!
for (int i = 1; i < (input * 2); i++) {
int amount = i > input ? i / 2 : i;
for (int a = 0; a < amount; a++)
System.out.print("*");
}
System.out.println();
}
For our loop conditions, a little explanation:
i < (input * 2): since i starts at 1 we can consider a few cases. If we have an input of 1 we need 1 row. input 2, 3 rows. 4: 5 rows. In short the relation of length to row count is row count = (length * 2) - 1, so I additionally offset by 1 by starting at 1 instead of 0.
i > input ? i / 2 : i: this is called a ternary statement, it's basically an if statement where you can get the value in the form boolean/if ? value_if_true : value_if_false. So if the row count is bigger than your requested length (more than halfway), the length gets divided by 2.
Additionally everything in that loop could be one line:
System.out.println(new String(new char[i > input ? i / 2 : i]).replace('\0', '*'));
And yeah, technically with a IntStream we could make this whole thing a one-line, though at that point I would be breaking out newlines for clarity
Keep in mind, I wouldn't call this the "beginner's solution", but hopefully it can intrigue you into learning about some other helpful little things about programming, for instance why it was I replaced \0 in my one-line example.

Related

Why does this for-loop only run once?

The goal of my code: To be able to write a program where I can enter in any number int as a command-line argument and displays how many digits in the integer number are 7s.
My problem is that I don't understand why my code only runs through the for-loop once. I inserted the system.out.println(sevens); to see how many times this loop works when I compile with a random number like 456789.
I could only think of a for-loop to use for this one and fixed some simple mistakes in the beginning. I also checked my brackets
public class TestingSevens {
public static void main(String[] args) {
int sevens = Integer.parseInt(args[0]);
int count = 0;
for (int i = 0; i < args.length; i++) {
if (sevens%10 == 7) {
count += 1;
}
sevens = sevens/10;
System.out.println(sevens);
}
System.out.println(count);
}
}
The result of inputting a number like 456789 is "45678" for the first print and the second print is "0." I know the number for some reason only runs through the loop once since it cuts off the last number before jumping out of the loop to print the count...any advice?
I presume you want to iterate over each digit of sevens. Since sevens initialized from args[0], the loop limit should match and look at args[0].length() rather than args.length.
for (int i = 0; i < args[0].length(); i++)
An alternate way to write the loop is to iterate until sevens reaches 0. That lines up better with the loop body; both use the same variable.
while (sevens > 0) {
if (sevens%10 == 7) {
count += 1;
}
sevens /= 10;
System.out.println(sevens);
}
Your code has logic errors, so to check if the iterated number is number 7 you need to turn the number into a string and check if the character is the desired character using: numberString.charAt(index)
Below is the corrected code:
public static void main(String[] args) {
int sevens = Integer.parseInt(args[0]);
String numberString = String.valueOf(sevens);
int count = 0;
for (int i = 0; i < numberString.length(); i++) {
char c = numberString.charAt(i);
if (c == '7') {
count += 1;
}
System.out.println("Input number: " + sevens);
}
System.out.println("Count of 7 numbers: " + count);
}

Assistance with a java program that counts up to a number, in binary

I've recently taken up a computer organization course in where we learn binary hex etc, I took it upon myself to attempt to create a program that will count from 0 up to an input number, however the counting is done in binary. I've run into some trouble and confused myself beyond belief, some clarification and assistance would be greatly appreciated. Specifically speaking, how can I efficiently and effectively replace the values of a string containing the previous binary number, with 0's and 1's using some sort of for-loop. I'm aware that there is some method for directly converting a string to binary, however; I wanted to do this more complicated method for practice.
package counting;
import java.util.Scanner;
public class counting
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Hello, this is a number counter, please enter the integer you would like to count to");
int number = input.nextInt();
String start = "0000000000";
// 000~etc is used as the start simply because i'm not sure how to calculate how many digit places
//the number input by the user will have
StringBuilder cont = new StringBuilder(start);
System.out.println(start);
/*What i intend to do is have the binary loop counter continue until it reaches
* the number input by the user, afterwards, working in a right to left manner, start counting from
* 0 up to the number given by the user, starting with 0. then using another loop, still using
* the right to left manner, if there is a 0, it should be replaced with a 1, and if there is a
* 1, it should be replaced with a 0, and the character before it should be replaced with a 1, if there
* is no room, continue to the left until there is a space available for a 1 and then reset all values
* after the 1 back to zero, and resume counting. the way i see it is requires a for loop to be used
* as the current position of a cursor used to determine what changes must be made
*/
for(int i = 0; i < number; i++)
{
int l = start.length();
for(int n = 0; n <= number; n++)
{
for(int w = 1; w <= l; w++)
{
if (cont.charAt(l-w) == '0')
{
cont.setCharAt((cont.length()-w), '1');
System.out.println(cont);
}
else if (cont.charAt(l-w) == '1')
{
cont.setCharAt((cont.length()-w), '0');
cont.setCharAt((cont.length()-(w+1)), '1');
System.out.println(cont);
}
}
}
System.out.println(cont);
}
}
}
Here is a little loop that will do what you are looking for. You just have to remember powers of 2 to count in binary.
public static char flip(char c){
if(c == '0')
return '1';
else
return '0';
}
public static void main(String[] args) {
String start = "0000000000";
StringBuilder cont = new StringBuilder(start);
int number = (int)Math.pow(2,10);
for(int i = 0; i < number; i++)
{
if(i != 0){
int val = (int)Math.floor(i/2);
for(int j = 0; j <= val; j++){
// Flip any bit that when modded by 2^j == 0
if(i % Math.pow(2,j) == 0){
cont.setCharAt((cont.length() - (j + 1)), flip(cont.charAt(cont.length() - (j + 1))));
}
}
}
System.out.println(cont);
}
}

Trouble printing out pattern in array

I am trying to get the number of pattern to printout from the array but under my number of pattern no pairs were printed out this is an example of what i am trying to get
(Array: 2 7 2 3 1 5 7 4 3 6
Number of patterns: 3)
but I do not know what to write from beyond number of patterns
The code:
public class FindIt {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int Sum = 0;
int[] InsertNumbers = new int[10];
System.out.println("Sample output #1:");
System.out.print("Array: ");
for(int i = 0; i < 10; i++)
{
InsertNumbers[i]=(int)(Math.random()*10)+1;
System.out.print(InsertNumbers[i] + " ");
}
System.out.println("");
System.out.print("Array: ");
for(int i = 0; i < 5; i++)
{
ComputePattern(InsertNumbers, Sum);
System.out.print(InsertNumbers[i] + " ");
}
System.out.println("");
System.out.print("Number of patterns: ");
}
public static void ComputePattern(int[] InsertNumbers, int Sum)
{
for(int i = 0; i < 2; i++)
{
InsertNumbers[i] = Sum;
Sum = Sum + Sum;
}
}
}
It is quite hard to understand your code but here is what I can tell you.
You have managed to get to ask the user input but I feel that the following would be better.
Instead, try having two arrays, one which the user can input 10 integers, and the other array with the sum of the pairs, hence an array containing 5 integers.
With the help of a For Loop and a formula, you can use it to get the 2 consecutive values. The first formula being x*2, the second being (x*2)+1.
With x being 0 in the for loop, and loop it for 5 times.
Afterwards, you get the values of the x*2 and the (x*2)+1 in the array, and sum them together.
Then with the sum, you can then use it to calculate the count of patterns.
Suggestion : Try to be consistent with your println and print. It is quite confusing and I am not quite sure as to why you have set println for certain text and print for the rest.
No patterns were printed because you have no print statements after you print Number of patterns.

it works but I still get an error message, what am I doing wrong?

My teacher wants us to take a string that was imputed and take a certain increment and pull out the characters at those increments. I have it working but I still get this error message:
java.lang.StringIndexOutOfBoundsException: String index out of range: 21
then it highlights the line of code point = base.charAt(sum):
here is my entire code so that you can see what I am doing.
import java.util.*;
public class EveryOtherCharacter {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a String: ");
String base = input.nextLine();
System.out.print("Enter an increment: ");
int index = input.nextInt();
int a = base.length();
int sum = 0;
char point;
if(index>a) {
System.out.println("Invalid increment: "+index);
}
else {
while (index<=a) {
sum+=index;
point = base.charAt(sum);
System.out.print(point);
}
System.out.println();
}
}
}
First of all, the condition of the while loop should be sum < a, not index <= a, because the last index of an array/string is length-1, and sum is the variable you are incrementing, not index.
Also, another problem is that after the last "legal" cycle, index <= a will return true, and then you are adding index to sum which will take it beyond the bounds of the string. You should implement it as such:
do {
point = base.charAt(sum);
System.out.println(point);
sum += index;
} while(sum < a)
Edit: If you don't want to use a do-while loop, you can implement it like so with a for loop:
for(sum = 0 ; sum < a ; sum += index) {
point = base.charAt(sum);
System.out.println(point);
}

Loop with incremental value based on user input

I have a task about incremental values in a loop based on user input.
The task is that the following lines are generated in the console
*
**
***
****
*****
And the amount of lines are decided by user input. I.e. if the user types in 2 it gives the following output:
*
**
My current code is:
import static javax.swing.JOptionPane.*;
public class loop1 {
public static void main(String[] args){
int current_line = 0;
String input_line = showInputDialog("type here ");
int target_line = Integer.parseInt(input_line);
while (current_line != target_line){
String sign = "*";
System.out.println(sign);
current_line ++;
}
}
}
But I can't seem to get the number of asterisks (*) to increase for every time it runs. How can I accomplish this?
You need a nested loop. Each iteration of the outer loop (which is the loop you already have) would print a single row, and each iteration of the inner loop would print a single asterisk for the current row.
You actually need two loops here, but you only have one. You have a while loop to print out the asterisks, but you also need a loop to increment the number of asterisks printed out each time.
Some pseudocode might look like:
For (int i = 1 to whatever value the user entered):
For (int j = 1 to i):
Print an asterisk
Actual code would look like:
int numLines = Integer.parseInt(showInputDialog("type here "));
for(int numAsterisks = 0; numAsterisks < numLines; numAsterisks++) {
for(int i = 0; i < numAsterisks; i++) {
System.out.print("*");
}
System.out.println(); // Start a new line
}
You can make it simpler by using nested for loops. Modify your loop to:
for (int i=0;i<target_line;i++) {
for (int j=0;j<=i;j++) {
System.out.print("*");
}
System.out.println();
}
You print everytime one '*'-sign.
You don't necessarily need two loops. You can place the sign outside of the loop and you can add an asterisk every iteration with string.concat("*"). Concatenating actually means combining two strings into one, so you actually combine the sign from the previous iteration with a new sign.
int current_line = 0;
String input_line = showInputDialog("type here ");
int target_line = Integer.parseInt(input_line);
String sign = "*";
while (current_line != target_line){
sign.concat("*");
System.out.println(sign);
current_line ++;
}

Categories