Reputation:
I need some help with my java project. 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. 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:
https://i.sstatic.net/tIQND.jpg
Upvotes: 0
Views: 175
Reputation: 636
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();
}
Upvotes: 0
Reputation: 1493
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++;
}
Upvotes: 2