package book;
import java.util.Scanner;
public class Test5_19 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("enter the number of line");
int numberOfLine = in.nextInt();
for(int rows=1;rows<=numberOfLine;rows++){
for(int space=numberOfLine-rows;space>=1;space++){
System.out.print(" ");
}
for(int i=0;i<=numberOfLine-1;i++){
int a = (int)(Math.pow(2, i));
System.out.print(a+" ");
}
for(int j=numberOfLine-1;j>=0;j--){
int b = (int)(Math.pow(2, j));
System.out.print(b+" ");
}
System.out.println();
}
}
}
for(int space=numberOfLine-rows;space>=1;space++){ //初值为8,退出条件为小于1,但space一直在++,所以死循环
修改后的代码如下:
import java.util.Scanner;
public class Test5_19 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("enter the number of line");
int numberOfLine = in.nextInt();
for (int row = 0; row < numberOfLine; row++) {
for (int space = 0; space < (numberOfLine - row - 1); space++)
System.out.print(" ");
for (int column = 0; column <= row; column++)
print_val((int) Math.pow(2, column));
for (int column = row - 1; column >= 0; column--)
print_val((int) Math.pow(2, column));
System.out.println();
}
}
static void print_val(int n1) { //不同位数打印不同空格
if (n1 > 0 && n1 < 10)
System.out.print(" ");
else if (n1 > 9 && n1 < 100)
System.out.print(" ");
else
// Print 2 spaces for other values
System.out.print(" ");
System.out.print(n1);
}
}
考虑了输出格式,时间关系,没有加太多注释,您可以上机测试一下。
用心回答每个问题,如果对您有帮助,请采纳答案好吗,谢谢!
目测了一下,你不应该用空格, 而是应该用制表符(\t)
跑不了具体是什么情况
public class TestDemo {
public static void main(String[] args){
systemTrigon(8);
}
/* 随便输入你希望的值*/
private static void systemTrigon(int m){
int sum =1;
for (int i=1;i sum=sum*2;
}
int len= (sum+"").length();
int row = m;
int column=2*m-1;
int index = 1;
for (int i=0;i index = 1;
for (int j =0 ;j if (j System.out.printf(" "+getMString(len,"*")+" ");
}else if (j>(m+i-1)){
System.out.printf(" "+getMString(len,"*")+" ");
}else{
if (j<m){
System.out.printf(" "+getMString(len,index+"")+" ");
if (j<(m-1)){
index=index*2;
}
}else{
index=index/2;;
System.out.printf(" "+getMString(len,index+"")+" ");
}
}
}
System.out.println("");
}
}
/* 计算空格补位*/
private static String getMString(int len,String str){
int m = str.length();
int n = len-m;
StringBuffer stringBuffer = new StringBuffer();
for (int i=0;i<n;i++){
stringBuffer.append(" ");
}
stringBuffer.append(str);
return stringBuffer.toString();
}
}