I should do this program in java that asks me to write a program that issues a V composed of asterisks like the following picture:
*
*
* *
* *
* *
*
This is the program that I created but it does not work:
import java.util.*;
public class Disegnav{
public static void main (String [] arg){
Scanner sc = new Scanner(System.in);
for(int i = 5; i>0; i--){
int k = 9, l=0, x=3;
for(int j = 0; j<=9 ; j++){
if(i>3 && j<k)
System.out.print(" ");
else
if(j==k || i==l || i==x)
System.out.print("*");
else
System.out.print(" ");
k--;
l++;
x--;
}
System.out.println();
}
}
}
Ok I can give you an algorithm but you will have to try it out yourself.
Observe that for the first line no of spaces is 7 and then a *
. Try printing that.
Same is for the second line but 6 spaces and a *
.
Observe that from third line there are *
on both the sides. So going by the same logic print a * then 5
spaces and a *
.The observe since there are stars on both the sides, you need to decrease the space count by 2
.And at the same time increase the space count by 1
before printing the first *
on each line. Hope you get it.
and do it iteratively until there is no space count left.
A general solution for problem.
import java.util.*;
public class Disegnav{
public static void main (String [] arg){
Scanner sc = new Scanner(System.in);
int param = sc.nextInt() - 1;
for(int i = 0; i < param; i++){
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
System.out.print("*");
for (int j = 0; j < 2 * param - 2 * i - 1; j++) {
System.out.print(" ");
}
System.out.print("*");
System.out.println();
}
for (int i = 0; i < param; i++) {
System.out.print(" ");
}
System.out.print("*");
System.out.println();
}
}
Why so complicated? Let's keep it short!
class Draw {
public static void main(String... args) {
for (int x = -2, y = 8; x <= 3; ++x) {
String before = (x >= 0) ? String.format("%" + (x+1) + "s", "*") : "";
String after = (y > 0) ? String.format("%" + (y+1) + "s", "*") : "";
System.out.println(before + after);
y -= (x >= -1) ? 2 : 1;
}
}
}
I know this might be quite cryptic at first, but I can make some briefly explanation, in case you liked this one.
Also note, that this doesn't solve general problem, there are hard-coded size constants which are solving the problem only for your case.
I'm also assuming from the question, you didn't want to find bug in your program.
I don't know task conditions but the simplest way is :
public static void main (String [] arg){
System.out.println(" *\n" +
" *\n" +
"* *\n" +
" * *\n" +
" * *\n" +
" *");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.