Loop with incremental value based on user input - java

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 ++;
}

Related

Problem with logic of this pattern problem

Here is the question. I have to print this pattern eg For n = 5
For n = 5
****1
***232
**34543
*4567654
567898765
I have written logic for this problem but I am not able to solve it.
I can't make the last pattern print i.e. the decrease one 2 4,3 5,4
Here's my pattern For n = 5
****1
***232
**34544
*4567666
567898888
Can anyone help me out and tell what's wrong with my logic. How to fix it
My code down below
import java.util.Scanner;
import java.lang.*;
public class Main {
public static void main(String[] args) {
solve();
}
public static void solve(){
int n;
Scanner obj = new Scanner(System.in);
n = obj.nextInt();
for(int row =1;row<=n;row++){
int ans1 = row;
int spaces =1;
for( spaces = 1;spaces<=n-row;spaces++){
System.out.print("*");
}
for (int pattern01 = 1; pattern01<=row;pattern01++){
System.out.print(ans1);
ans1 = ans1 +1;
}
for ( int pattern2 = 1 ; pattern2<=row-1; pattern2++){
ans1= 2*row-2;
System.out.print(ans1);
ans1--;
}
System.out.println();
}
}
}
The issue you are having is that you are not decrementing 'ans1' correctly. If you are not sure how to use the debugger then observe your output through the console with print-out statements. Specifically the 3rd loop when 'ans1' is supposed to count backwards. Also, keep in mind the value of 'ans1' after you exit the second for-loop.
This is your second loop when you start to count up from row number variable.
You increment 'ans1' by 1 each iteration.
for (int pattern01 = 1; pattern01 <= row;pattern01++) {
System.out.print(ans1);
ans1 = ans1 + 1;
}
One thing to consider is that you are incrementing 'ans1' and what is the value of it before you enter your third loop to decrement? You need to do something here before you enter the loop and start printing.
Also, in your third loop you are not decrementing correctly. You should be counting backwards, or rather just decrementing by 1.
for(int pattern2 = 1;pattern2 <= row-1; pattern2++){
ans1= 2*row-2; // Your focus should be here, does this look right? Do you need it?
System.out.print(ans1); // You should decrement first and then print
ans1--; // this is correct, but in the wrong spot
}
I know you can pull it off :) You got this.

Creating a User-Input Asterisk Triangle using 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.

Rewrite code with two loops and two output statements

I am working on completing the summer assignment for my AP Computer Science A class. The base code for the next portion is this:
public class Stars {
public static void main(String[] args) {
System.out.println("*");
System.out.println("**");
System.out.println("***");
System.out.println("****");
System.out.println("*****");
}
}
RESULT:
*
**
***
****
*****
I am supposed to rewrite the code to output the same result, using two loops as well as only two output statements that I will provide below:
System.out.print(“*”);
System.out.println();
I have found one alternative means to do so:
public class StarsLoop {
public static void main(String[] args) {
for (int i = 0; i < 1; i++)
System.out.print("*\n**\n***\n****\n*****");
}
}
Of course, though, this does not include two loops and the two given output statements as is required; however, I can't really seem to think of how I would do so. So, what is a possible way to do so?
You want to print five lines in total, each line consists of the line number star characters. Loop from one to five (inclusive), and inside that loop - loop again, this time the outer number of times printing stars. After that, print a newline. Like,
for (int i = 1; i <= 5; i++) {
for (int j = 0; j < i; j++) {
System.out.print("*");
}
System.out.println();
}
Of course, you could eliminate a loop by accumulating stars in a StringBuilder - and outputing that on each iteration. Like,
StringBuilder line = new StringBuilder("*");
for (int i = 0; i < 5; i++) {
System.out.println(line);
line.append("*");
}
The following code will produce the desired result:
for (int i = 1; i <= 5; i++) // Loop over each asterisks row to be printed
for(int j = 0;j < i; j++) { // Loop over the number of stars to print for the current line. It is based on the current row number
System.out.print(“*”); // Add an asterisks to the current row
}
System.out.println(); // Move to the next line
}

Automatically fill and array with a loop without a prompt..

I was wondering if it's possible to use a loop to fill and array without prompting the user for input?
I have to design a program to fill an array of size 6 with multiples of 7. The specification doesn't say anything about prompting the user, and it says 'Use a loop to fill the array' so I can't hard code the numbers in.
Of the multiples of 7 , I need to print out which ones can be divided by 3 exactly.
Is it possible to fill the array without an input from the user?
My code is below...
import java.util.Scanner;
/**
* Created by IntelliJ IDEA.
* Date: 26/02/2015
* Time: 15:25
* UPDATE COMMENT ABOUT PROGRAM HERE
*/
public class Array7Mult
{
public static void main(String[] args)
{
int multipleSeven [] = new int[6];
final int HOWMANY=6,DIVIDE=3;
Scanner keyboard = new Scanner(System.in);
for(int count=0;count<HOWMANY;count++)
{
System.out.println("Please enter a multiple of 7 below..");
multipleSeven[count]=keyboard.nextInt();
}//for
System.out.println("The multiples of seven that can be divided by 3 are..");
for(int count=0;count<HOWMANY;count++)
{
if (multipleSeven[count] % DIVIDE == 0)
{
System.out.println(multipleSeven[count]);
}//if
}//for
}//main
}//class
Yes ofcourse. Say you want to populate an array by a variable which is incremented by one per index. Say variable i (so we use the same variable that's instantiated in the loop).
for(int i = 0; i < arr.length; i++)
arr[i] = i;
Simple as that. You may ofcourse create a global variable and add it into the array within the boundaries of the loop and manipulate its value within the loop too.
int a = 0;
for(int i = 0; i < arr.length; i++) {
arr[i] = a;
a += 10;
}
If you want to increment the value as a multiple of seven, you can simple use the first example and instead of doing arr[i] = i do arr[i] = i*7
Use
for(int count=0;count<HOWMANY;count++)
multipleSeven[i]=(i+1)*7;
Instead of
for(int count=0;count<HOWMANY;count++)
{
System.out.println("Please enter a multiple of 7 below..");
multipleSeven[count]=keyboard.nextInt();
}
To fill the array multipleSeven with values 7,14,21,28,35,42.

beginner java, showing special characters that correlate to an integer

Doing some homework in my CSC 2310 class and I can't figure out this one problem... it reads:
Write a program that will draw a right triangle of 100 lines in the
following shape: The first line, print 100 '', the second line, 99
'’... the last line, only one '*'. Name the program as
PrintTriangle.java.
My code is pretty much blank because I need to figure out how to make the code see that when i = 100 to print out one hundred asterisks, when i = 99 print ninety-nine, etc. etc. But this is all i have so far:
public class PrintTriangle {
public static void main(String[] args) {
// Print a right triangle made up of *
// starting at 100 and ending with 1
int i = 100;
while (i > 0) {
// code here that reads i's value and prints out an equal value of *
i--;
}
}
}
The rest of the assignment was way more difficult than this one which confuses me that I can't figure this out. Any help would be greatly appreciated.
You clearly need 100 lines as you know. So you need an outer loop that undertakes 100 iterations (as you have). In the body of this loop, you must print i * characters on a single line, so you just need:
for (int j = 0 ; j < i ; j++) System.out.print("*");
System.out.println(); // newline at the end
Hence you will have:
int i = 100;
while (i > 0) {
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
i--;
}
Or equivalently,
for (int i = 100 ; i > 0 ; i--) {
for (int j = 0; j < i; j++)
System.out.print("*");
System.out.println();
}
EDIT Using only while loops:
int i = 100; // this is our outer loop control variable
while (i > 0) {
int j = 0; // this is our inner loop control variable
while (j < i) {
System.out.print("*");
j++;
}
System.out.println();
i--;
}
So to break it down:
We have an outer loop that loops from i = 100 downwards to i = 1.
Inside this outer while loop, we have another loop that loops from
0 to i - 1. So, on the first iteration, this would be from 0-99
(100 total iterations), then from 0-98 (99 total iterations), then
from 0-97 (98 total iterations) etc.
Inside this inner loop, we print a * character. But we do this i
times (because it's a loop), so the first time we have 100 *s, then 99, then 98 etc. (as
you can see from the point above).
Hence, the triangle pattern emerges.
You need two loops, one to determine how many characters to print on each line, and an inner nested loop to determine how many times to print a single character.
The hint is that the inner loop doesn't always count to a fixed number, rather it counts from 1 to (100 - something).
Try this:
public class PrintTriangle {
public static void main(String[] args) {
for(int i = 100; i >= 1; i--){
System.out.print("\n");
for(int j = 0; j < i; j++){
System.out.print("*");
}
}
}
}
Explanation: The nested for loop has a variable named j. j is the amount of times * has been printed. After printing it checks if it is equal to i. i is a variable in the big for loop. i keeps track of how many times a line has been printed. \n means newline.
You could come at it side ways...
StringBuilder sb = new StringBuilder(100);
int index = 0;
while (index < 100) {
sb.append("*");
index++;
}
index = 0;
while (index < 100) {
System.out.println(sb);
sb.deleteCharAt(0);
index++;
}
But I think I prefer the loop with loop approach personally ;)
You could improve the effiency of the first loop by increasing the number of stars you add per loop and reducing the number loops accordingly...
ie, add 2 starts, need 50 loops, add 4, need 25, add 5 need 20, add 10, need 10...
For example
while (index < 10) {
sb.append("**********");
index++;
}

Categories