I'm trying to print this ruler horizontally in java

别来无恙 提交于 2019-11-29 12:54:38

If you're not going for a a special formula for presentation (i.e. this will likely not be scaled to an actual ruler) and just want the output to print horizontally, removing all instances of \n from your code makes it print in a line.

public static void drawOneTick(int tickLength, int tickLabel)
{
    for (int i = 0; i < tickLength; i++)
        System.out.print("|");
    if (tickLabel >= 0)
        System.out.print(" " + tickLabel);

}

Even after looking at your sample picture I wasn't sure what you wanted to print exactly so I decided to print the top part of the ruler bellow:

Considering I am European and I think the imperial system is weird and a major overkill, my ruler will measure in the metric system :) (centimeters and millimeters)

Ok, so the basic idea is to separate each row of ticks or labels as it's own String like:

String1 = | | | | | | | | | | | | | | | | | | | | | | | ...   // regular ticks
String2 = |                   |                   |     ...   // ticks to labels
String3 = 0                   1                   2           // labels

We build each string separately, then we combine them with a newline '\n' character in between them so they will print properly. You have to also make sure the number of spaces is exact so that the strings align correctly.

Here is the code:

class MyRuler {

    StringBuilder ticks = new StringBuilder();
    StringBuilder ticksToLabels = new StringBuilder();
    StringBuilder labels = new StringBuilder();

    int millimetersPerCentimeter = 10;

    String drawRuler(int centimeters) {
        // append the first tick, tick to label, and label
        ticks.append("| ");
        ticksToLabels.append("| ");
        labels.append(0);

        for(int i = 0; i < centimeters; i++) {
            for(int j = 0; j < millimetersPerCentimeter; j++) {
                if(j == millimetersPerCentimeter - 1) {
                    ticksToLabels.append("| ");
                    labels.append(" " + (i + 1));
                } else {
                    ticksToLabels.append("  ");
                    labels.append("  ");
                }
                ticks.append("| ");
            }
        }       
        ticks.append("\n" + ticksToLabels.toString() + "\n" + labels.toString());
        return ticks.toString();
    }

    public static void main(String[] args) {
        MyRuler ruler = new MyRuler();
        System.out.println(ruler.drawRuler(5));
    }
}

Output:

| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | 
|                   |                   |                   |                   |                   | 
0                   1                   2                   3                   4                   5
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!