【发布时间】:2014-02-28 03:53:30
【问题描述】:
这是本次作业的主要步骤。创建嵌套循环以打印出
如果输入有效,则为表格格式的数字。第一个输入 i 定义数字
行数,第二个输入 j 定义列数。在循环内部,
编写代码列出从 1 到 i*j 的正数。使用
System.out.printf() 具有“%4d”和“%4s”格式的函数
整数和字符串。
我需要打印出来
设置表的大小和数据类型(输入'Q'或'q'退出): 3 4 个“数字”
- | 1 2 3 4
----------------
1 | 1 2 3 4
2 | 5 6 7 8
3 | 9 10 11 12
在我设置了列数和行数后,我只能得到内部表,而不是外部数字表或星号。 为了让它正确显示,我不得不改变它,但它应该排列整齐
Scanner scan = new Scanner(System.in);
String stringIn;
do
{
System.out.print("Set the size of table and data-type(Type Q or q to quit)");
stringIn = scan.nextLine();
int space = stringIn.indexOf(" ");
int spaceTwo = stringIn.indexOf(" ", space+1);
if(stringIn.length()>4)
{
String firstNum = stringIn.substring(0,space);
String secondNum = stringIn.substring(space+1,spaceTwo);
String dataType = stringIn.substring(spaceTwo+1);
int firstInt = Integer.parseInt(firstNum);
int secondInt = Integer.parseInt(secondNum);
if (!stringIn.equals("Q")&&!stringIn.equals("q")&&firstInt>=0&&secondInt>=0)
{
System.out.println(stringIn.substring(0,space) + " " + stringIn.substring(space+1,spaceTwo) + " " + stringIn.substring(spaceTwo+1));
}
else if(firstInt<0||secondInt<0)
{
System.out.println("Try again. The input was invalid");
}
for(int i = 1; i <firstInt+1; i++)
{
for (int j = 1; j < secondInt+1; j++)
{
System.out.printf("%4d", i*j);
System.out.printf("%4s", i*j);
}
System.out.println();
}
}
}
while(!stringIn.equals("Q")&&!stringIn.equals("q"));
这是我的第一个 Java 类,所以我的代码非常混乱。
【问题讨论】: