简体   繁体   English

Java建议(Line Jump)

[英]Suggestion with Java(Line Jump)

I need some help with my java project. 我的java项目需要一些帮助。 What I want to do is to let the user put in a number and my program will then print that number starter from 1. I have also added field width to 5. What I want to do now is to make line jumps: For example the first line will have 1 character, the next will have 2, then next will have 3 and so on. 我想要做的是让用户输入一个数字然后我的程序将从1打印该数字启动器。我还将字段宽度添加到5.我现在要做的是跳线:例如第一行将有1个字符,下一个将有2个,然后接下来将有3个,依此类推。 The field width from the start will also increase on every line. 从一开始的字段宽度也会在每一行上增加。 Here is my code: 这是我的代码:

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();

        }

    }
}

How output should be: 输出应该如何:

http://imgur.com/2QLTRlA http://imgur.com/2QLTRlA

Try this: 尝试这个:

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++;
}

I do not understand what you want to do. 我不明白你想做什么。 But from what I understand this is what you want: 但据我所知,这就是你想要的:

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();

    }

}
}

FINAL EDIT: This works but their is a more efficient way to do this: 最终编辑:这是有效的,但它们是一种更有效的方法:

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM