我必须创建一个打印时间表的程序 1)有多种方法。 2)读取两个数字,其中一个是上限,第二个是表格的深度(基本上是行和列)。从限制正方形表开始,它只能是例如10x10或12x12。 3)有一个循环,以便用户可以使用不同的输入再次运行它。 4)使用扫描仪读取I / P. 当您为第一个数字输入3并且为第二个数字输入8时,输出应该看起来像这样:
但它是这样的:Output
import java.util.Scanner;
public class TimesTableRewrite
{
public static void main (String[] args)
{
Scanner in;
in = new Scanner (System.in);
boolean runAgain = false;
header();
String response;
do
{
printTable();
System.out.println("\nDo you want to go again? Y or N?");
response = in.next();
if ((response.charAt(0)=='Y'||response.charAt(0)=='y'))
{
runAgain = true;
}
else
{
runAgain = false;
}
}
while (runAgain);
footer();
}
public static void printTable()
{
Scanner in;
in = new Scanner (System.in);
int height;
int length;
System.out.println("Enter the first number to set up how far down you want the table to go.");
height= Integer.parseInt(in.next());
System.out.println("Enter the second number to extend the table horizontally");
length = Integer.parseInt(in.next());
for (int i = 1; i <= height; i++ )
{
for (int j = 1; j <= length; j++ ) //j is number of columns
{
if (i<height)
System.out.format("%4d", + i*j);
else
System.out.format("%4d", + i*j);
if (i==height)
{
System.out.println();
}
}
}
for (int i = 1; i <= height; i++ )
{
for (int j = 1; j <= length; j++ )
{
if (j<length)
System.out.format("%4d", + i*j);
else
System.out.format("%4d", + i*j);
if (j==length)
{
System.out.println();
}
}
}
}
public static void header()
{
System.out.println("This program will help you practice your times tables!");
System.out.print("This newer version will allow you to go beyond the 12 times tables!");
System.out.println("It will let you choose your upper limit \nand how deep the times table will go.");
System.out.println("Let's go!");
System.out.println("\nPlease enter two numbers to generate a multiplication table.");
}
public static void footer ()
{
System.out.println("That's all folks! See you next week!");
}
}
答案 0 :(得分:2)
替换它:
for (int i = 1; i <= height; i++ )
{
for (int j = 1; j <= length; j++ ) //j is number of columns
{
if (i<height)
System.out.format("%4d", + i*j);
else
System.out.format("%4d", + i*j);
if (i==height)
{
System.out.println();
}
}
}
for (int i = 1; i <= height; i++ )
{
for (int j = 1; j <= length; j++ )
{
if (j<length)
System.out.format("%4d", + i*j);
else
System.out.format("%4d", + i*j);
if (j==length)
{
System.out.println();
}
}
}
有了这个:
for (int i = 1; i <= height; i++ )
{
for (int j = 1; j <= length; j++ ) //j is number of columns
{
System.out.print(i * j);
System.out.print("\t"); //We add a tab after each number to form every column.
}
System.out.println(); //We add a berakline for each row.
}