0

我的 java 项目需要一些帮助。我想要做的是让用户输入一个数字,然后我的程序将从 1 打印该数字起始符。我还将字段宽度添加到 5。我现在要做的是进行换行:例如第一行将有 1 个字符,下一行将有 2 个字符,然后下一行将有 3 个字符,依此类推。从一开始的字段宽度也将在每一行上增加。这是我的代码:

import java.util.Scanner;

public class ProjectB {

    public static void main(String[] args) {
        printNumbersB(0);
    }

    public static void printNumbersB(int x){

        Scanner input = new Scanner(System.in);

        System.out.print("Please put in: ");
        x = input.nextInt();

        for(int y = 1; y <= x; y++){



            System.out.printf("%5d", y);


            input.close();

        }

    }
}

输出应该如何:

http://imgur.com/2QLTRlA

4

2 回答 2

2

尝试这个:

int n = 45;
int counter = 1;
for (int i = 1; i < n; i++) {
    for (int j = i; j < counter + i; j++) {
        System.out.printf("%" + counter + "d", j);
    }
    i += counter - 1;
    System.out.println();
    counter++;
}
于 2013-10-18T13:08:13.853 回答
0

我不明白你想做什么。但据我了解,这就是你想要的:

public static void main(String[] args) {
    printNumbersB();
}

public static void printNumbersB(){

    Scanner input = new Scanner(System.in);
    System.out.print("Please put in: ");
    x = input.nextInt();
    //Should use String Builder
    String accumlationString = "";
    for(int y = 1; y <= x; y++){

        System.out.printf(accumulationString + "%5d",  y);
     accumulationString = accumulationString + "%5d";
;

        input.close();

    }

}
}

最终编辑:这可行,但他们是一种更有效的方法:

public static void printNumbersB() {
Scanner input = new Scanner(System.in);
System.out.print("Please put in: ");
int x = input.nextInt();
input.close();
//Should use String builder
String tab = "";
int lineNumber;
int num = 1;
breakfor:
for (int i = 1; i <= x; i++) {
    System.out.println();
    lineNumber = i;
    tab = tab + " ";
    for (int j = lineNumber; j > 0; j--) {
        System.out.print(tab + num);
        num = num + 1;
        if(num > x)
            break breakfor;
    }

}

}

public static void main(String[] args) {
    printNumbersB();
}
于 2013-10-18T12:47:31.807 回答