Reputation: 383
I have an assignment to create a program that prompts user input of an integer, then creates a multiplication table based on the user input using while loops.
The output multiplication table must include header row and column. What I'm stuck on is how to create the header row since the number that the header must count up to is dependent on the user input.
I created the header column in the while loop that formats the rows since a new row is created each time the loop gets stepped through. But the header row only prints once and therefore I cant use the while loop that formats the columns to create it.
How do I create the header row such that the user input is decremented back to 1, and all of the integer values from 1, 2, 3, ... , user input are output?
Here's what I have:
import java.util.Scanner;
public class Multiplication
{
public static void main(String[] args)
{
int number;
String yesno = "Y";
Scanner keyboard = new Scanner(System.in);
System.out.print ("This program generates a multiplication table ");
System.out.println("based on a number you enter.");
while(yesno.equalsIgnoreCase("Y"))
{
System.out.println("Please enter a number.");
number = keyboard.nextInt();
int row = 1;
int column = 1;
System.out.println(" |" + MAKETHISWORK + "\t"); //THIS IS WHERE I'M STUCK.
System.out.println("--------------------");
while(number>0)
{
row = 1;
while(row <= number)
{
System.out.print(row + "|");
column = 1;
while(column <= number)
{
System.out.print(row*column + "\t");
column ++;
} //END WHILE COLUMN <= NUMBER
System.out.println();
row ++;
} //END WHILE ROW <=NUMBER
System.out.println();
while(number>0)
{
number--;
}
} //END WHILE NUMBER >0
System.out.println("Would you like to enter another number? (Y/N) ");
yesno = keyboard.nextLine();
yesno = keyboard.nextLine();
} //END WHILE YESNO IS Y
while(yesno.equalsIgnoreCase("N"))
{
System.out.println("Thanks for participating!");
break;
}
}
}
Upvotes: 3
Views: 2293
Reputation: 5782
Why not just use another loop to build up a string to that value?
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= number; i++) {
builder.append(i).append(" ");
}
System.out.println(" |" + builder.toString() + "\t");
Note this will create a space-delimited string of the numbers up to the input one. If you want a different delimiter, just append a different value.
Upvotes: 2