For my class, we have to make a program that takes user input and prints that many numbers of the fibonacci sequence. I managed to do that, but my professor wants it in a field width of 15 and justified to the left. For some reason I'm not understanding, it just will not give me the correct output. Here's what I have:
boolean valid = false;
while (valid == false) {
System.out.println("Please enter a valid number (between: 1 - 50):");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
if (n < 1) {
System.out.println("The number entered " + n + " is not valid");
}
else if (n > 50) {
System.out.println("The number entered " + n + " is not valid");
}
else if (n >= 1 || n <= 50) {
valid = true;
//System.out.printf("%15s", "1 ");
int a = 0;
int b = 1;
for (int i = 1; i <= n; i++) {
int nextNumber = a + b;
if (i%5 != 0) {
System.out.printf("%15s", nextNumber + " ");
}
else {
System.out.printf("%15s", nextNumber + " " + "\n");
}
a = b;
b = nextNumber;
The output is right justified, but when I make it "%-15s", the values do not all line up correctly and it's still right justified. Also, that commented out line is because I can't get the sequence to print out the first one.