我必须要求输入并显示有许多线条的钻石。我有一个代码,但它显示的行数少于我输入的数量。我对哪里出错了感到困惑?
这是我目前的代码:
import java.util.Scanner;
public class PROBLEM3 {
public static void main(String [] args){
Scanner scan = new Scanner (System.in);
System.out.println("Please input number of lines:");
int i = 0, j, k, n;
n = scan.nextInt();
for(k = 0; k <= n / 2; k++){
for (i = 0; i < n - k; i++){
System.out.print(" ");
}
for (j = 1; j < k; j++){
System.out.print("*");
}
for (j = 1; j < k - 1 ; j++){
System.out.print("*");
}
System.out.println("");
}
for (k = (n / 2); k <= n ; k++){
for (i = 0; i < k; i++){
System.out.print(" ");
}
for ( i = 1; i < n - k ; i++){
System.out.print("*");
}
for (j = 0; j < n - k - 2; j++){
System.out.print("*");
}
System.out.print("\n");
}
scan.close();
}
}
Please input number of lines:
5
*
***
*
答案 0 :(得分:0)
请尝试以下代码,
import java.util.Scanner;
public class PROBLEM3 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please input number of lines:");
int i = 0, j, k, n;
n = scan.nextInt();
for (k = 1; k <= (n + 1) / 2; k++) {
for (i = 0; i < n - k; i++) {
System.out.print(" ");
}
for (j = 0; j < k; j++) {
System.out.print("* ");
}
System.out.println("");
}
for (k = ((n + 1) / 2); k < n; k++) {
for (i = 1; i < k; i++) {
System.out.print(" ");
}
for (j = 0; j < n - k; j++) {
System.out.print(" *");
}
System.out.println("");
}
scan.close();
}
}