Reputation: 11
I am currently studying Java all by myself and I really want to learn a lot. I asked my programmer friend to give me some tasks and he gave me this.
How do I display the asterisks according to the number I input?
EXAMPLE
Enter Number:7
*
**
***
*
I have written a code but I still can't get it. Please some examples , please?
import java.util.Scanner;
public class Diamond {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
/*promt for input*/
System.out.println( "Enter number: " );
int how_many = input.nextInt();
for(int i = 1; i <= how_many; i++ ) {
for(int j = 1; j <= i; j++ ) {
System.out.print( "*" );
}
System.out.println("");
}
input.close();
}
}
Any help or suggestion would be much appreciated.
Upvotes: 0
Views: 3248
Reputation: 1
import java.util.Scanner; //program uses class Scanner
public class Print{
public static void main(String[] args){
//declare variables
int num;
int x; //outer counter
int y; //inner counter
//use Scanner to obtain input
Scanner input = new Scanner(System.in);
System.out.print("Enter number: ");
num = input.nextInt();
//use for loop to generate the size of bar chart
for(x = 0; x < num; x++)
{
for(y = 0; y < num; y++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
Upvotes: 0
Reputation: 21
class Print{
public static void main(String argas []){
Scanner in=new Scanner(System.in);
System.out.println( "Enter number: " );
int how_many = in.nextInt();
int count=0;
for(int i = 1; i <= how_many; i++ )
{
for(int j = 1; j <= i; j++ )
{ **if(count==how_many)
return;**
System.out.print( "*" );
count++;
}
System.out.println("");
}
}
}
Add the condition to check whether the number of * are less than the input.
Upvotes: 1
Reputation: 4129
Your code is fine. You are just missing the variable declarations. Probably you come from a JavaScript
background. Declare int
before each one of the variables (how_many, i, and j) and try to compile & execute it again.
System.out.println( "Enter number: " );
int how_many = input.nextInt();
for(int i = 1; i <= how_many; i++ ) {
for(int j = 1; j <= i; j++ ) {
System.out.print( "*" );
}
System.out.println("");
}
Also. I am assuming you have the Scanner
object declared before everything
import java.util.*;
// etc, etc
Scanner input = new Scanner(System.in);
I think I understood what you were asking:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println( "Enter number: " );
int how_many = input.nextInt();
outer:
for(int i = 1, count = 0; i <= how_many; i++ ) {
for(int j = 1; j <= i; j++ ) {
if(count >= how_many)
break outer;
System.out.print( "*" );
}
System.out.println("");
}
input.close();
}
Upvotes: 1