-3

How can I use 'System.out.printf' to make my code look need. I want my calculations to look like this:

this is how I want my code to look alike
not like this:

I dont want it to look like this

I have to use the printf function.

public static void main(String[] args) {
    //Maken van een scanner met de naam input
    Scanner input = new Scanner(System.in);

    System.out.print("Welke tafel wilt u printen? ");
    int tafelGetal = input.nextInt();

    int nummer = 0;
    int maxGetal = 10;

    System.out.println("De tafel van " + tafelGetal + ":");

    do {
        int nummer2;
        nummer2 = ++nummer;
        nummer = nummer2;
        int berekening = tafelGetal * nummer;

        if (nummer >= 5) {

            System.out.print("\t" + berekening + "\t");

        }
        if (nummer == 5) {

            System.out.println(" ");
        }
        if (nummer < 5) {

            System.out.print("\t" + berekening + "\t");

        }

    } while (nummer != maxGetal);
    System.out.println(""); 
    
}
6

2 Answers 2

0

reusing some of your var names

    int tafelGetal = 3;
    int maxGetal = 10;        
    int numberPerLine = 5;
    int columnWidth = 4;
    for (int i = 1; i <= maxGetal; i += numberPerLine) { //iterate over output lines
        for (int j = 0; j < numberPerLine && i + j <= maxGetal; j++) { //iterate over columns
            int berekening = (i + j) * tafelGetal;
            System.out.printf("%" + columnWidth + "d", berekening);//format as number with specified width
        }
        System.out.println();
    }

For further details regarding available formats just go here : https://docs.oracle.com/javase/9/docs/api/java/util/Formatter.html

-1

You can also use String.format() to achieve that:

Example:

for(int i=3; i<=15; i+=3)
    System.out.print( p(i, 4) );
System.out.println();
for(int i=18; i<=30; i+=3)
    System.out.print( p(i, 4) );

//for padding the string
public static String p(int val, int spaces) {
     return String.format("%1$" + spaces + "s", val);  
}

OUTPUT:

   3   6   9  12  15
  18  21  24  27  30
3
  • This solution is terrible. Just use printf formatting.
    – DwB
    Oct 5, 2017 at 20:11
  • @DwB The solution is only 1 line. The rest are for printing a sample output so OP knows how it works. Oct 5, 2017 at 20:23
  • @Stefan Basically, my answer is as simple as String.format("%1$4s", i), where i is your value. Oct 5, 2017 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.