简体   繁体   English

Java 乘法表格式

[英]Java Multiplication Table Formatting

I'm making a multiplication and here is a screenshot of what I'm trying to make:我正在做一个乘法,这是我想要做的截图:

Final Product完成品

However, I cannot get the lines to format correctly.但是,我无法正确格式化这些行。 I think I have the correct code to perform the expressions... just need help formatting the table.我想我有正确的代码来执行表达式......只需要帮助格式化表格。 Is there something easy I'm missing, or do I need to restructure something?有什么简单的我错过了,还是我需要重组一些东西?

Here is my code and below that is a screenshot of the output:这是我的代码,下面是 output 的屏幕截图:

case 4:
                    System.out.print("    |");
                    for(int q=1;q<=MAX_VALUE;q++) {
                        System.out.printf("%4d",q);
                    }
                    
                    System.out.println(" ");
                    System.out.print("----+");
                    for (int u=0; u<MAX_VALUE; u++) {
                        System.out.print("----");
                    }
                    
                    System.out.println(" ");
                    
                    for(int q=1; q<=MAX_VALUE; q++) {
                        System.out.printf("%3d |",q);
                        
                        for (int m=1; m<=MAX_VALUE; m++) {
                           System.out.printf(q*m + "   ");
                           
                            
                        }
                    }    
                    System.out.println();
                break;

Not quite there不完全在那里

You need that System.out.println() inside the 3rd for loop.Like so你需要System.out.println()在第三个 for 循环中。像这样

               for(int q=1; q<=MAX_VALUE; q++) {
                    System.out.printf("%3d |",q);
                    
                    for (int m=1; m<=MAX_VALUE; m++) {
                       System.out.printf(q*m + "   ");      
                    }
                    System.out.println();
                }
            break;

You will still need formatting as you're not using 4 spaces for the output.您仍然需要格式化,因为 output 没有使用 4 个空格。 I have added a minor width in output so try this -我在 output 中添加了一个较小的宽度,所以试试这个 -

System.out.print("    |");
    for(int q = 1; q <= MAX_VALUE; q++) {
        System.out.printf("%4d", q);
    }

    System.out.println(" ");
    System.out.print("----+");
    for (int u=0; u<MAX_VALUE; u++) {
        System.out.print("----");
    }

    System.out.println(" ");

    for(int q=1; q<=MAX_VALUE; q++) {
        System.out.printf("%3d |", q);

        for (int m=1; m<=MAX_VALUE; m++) {
            //System.out.printf(q*m + "   ");
            System.out.printf("%4d", q*m);
        }
        System.out.println();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM