Java Output Formatting

Sort by

recency

|

1467 Discussions

|

  • + 0 comments

    need to start learning format :(

    import java.util.Scanner;

    public class Solution {

    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            System.out.println("================================");
            for(int i=0;i<3;i++){
                String s1=sc.next();
                int x=sc.nextInt();
    
            while (s1.length()<15) {s1=s1+" ";}
    
            if (x<10) {System.out.println(s1+"00"+x);}
            else  if (x<100) {System.out.println(s1+"0"+x);}
        else {System.out.println(s1+x);}
            }
            System.out.println("================================");
    
    }
    

    }

  • + 0 comments

    it’s amazing how widely it’s used. Its “write once, run anywhere” capability really makes it stand out for developers. bet in exchange login

  • + 0 comments

    import java.util.Scanner;

    public class Solution {

    public static void formattedOuput(String[] words, int[] numbers) {
            System.out.println("================================");
    
            for (int i = 0; i < 3; i++) {
                    System.out.printf("%-15s%03d\n", words[i], numbers[i]);
            }
    
            System.out.println("================================");
    }
    
    public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
    
            String[] words = new String[3];
            int[] numbers = new int[3];
    
            // Taking Input
            for (int i = 0; i < 3; i++) {
                    words[i] = sc.next();
                    numbers[i] = sc.nextInt();
            }
    
            // Printing Output
            formattedOuput(words, numbers);
    
            sc.close();
    }
    

    }

  • + 0 comments

    Java output formatting

    function used- printf

    %s - string formatting

    %d - integer formatting

    %15s - 15 void space from right Java______________

    %-15s - 15 void space from left _______________Java

    %03d - for 3digits =100, for 3 - 003, for 34 - 034

    so to print formatted output System.out.printf("%-15s%03d\n",s1,x);

  • + 0 comments

    This is a great exercise for learning how to control output formatting in Java. cbtfturbo 247