Java表格打印代码无输出问题求助:输入行列后程序直接退出
问题排查与代码修正:Java打印指定行列表格无输出
核心问题:循环条件逻辑错误
你的for循环初始化rowCount=0, columnCount=0,但循环条件写为columnCount == column && rowCount == row——这意味着只有当输入的行数和列数都是0时,循环才会执行。正常输入行列数(比如5)时,初始的0不可能等于输入的数值,所以循环直接跳过,没有任何输出。
次要问题:列起始值与预期不符
示例中的列从1开始(如(0,1)),但你的代码里columnCount从0开始,会输出(0,0),不符合目标格式。
修正后的代码
import java.util.Scanner; public class Table { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Print the table"); System.out.print("How many rows should we create? "); int row = input.nextInt(); System.out.print("How many column should we create? "); int column = input.nextInt(); // 嵌套循环更易理解:外层控行,内层控列 for (int rowCount = 0; rowCount < row; rowCount++) { for (int columnCount = 1; columnCount <= column; columnCount++) { System.out.print("(" + rowCount + "," + columnCount + ")\t"); } // 每行结束后换行 System.out.println(); } input.close(); } }
改动说明
- 将单层循环改为嵌套循环:外层循环遍历行(从0到row-1),内层循环遍历列(从1到column,匹配示例格式)
- 内层循环逐个打印单元格,行遍历结束后执行换行,逻辑更直观
- 修正列起始值为1,完全匹配你给出的示例输出格式
测试输入5行5列时,输出结果如下:
Print the table
How many rows should we create? 5
How many column should we create? 5
(0,1) (0,2) (0,3) (0,4) (0,5)
(1,1) (1,2) (1,3) (1,4) (1,5)
(2,1) (2,2) (2,3) (2,4) (2,5)
(3,1) (3,2) (3,3) (3,4) (3,5)
(4,1) (4,2) (4,3) (4,4) (4,5)
内容的提问来源于stack exchange,提问作者Programmer Noob
相关产品推荐
相关产品推荐

