Java Output Formatting

  • + 45 comments
    public class Test {
    	public static void main(String[]args) {
    		Scanner sc=new Scanner(System.in);
            System.out.println("================================");
    
    		for(int i=0; i<3; i++) {
    			String sl=sc.next();
    			int x = sc.nextInt();
    			
    			
    			System.out.printf("%-15s%03d%n", sl, x);
    		
    		}
            System.out.println("================================");
    
    		
    		
    		
    		
    	}
    }
    

    As a begginer I dont expect other people to come up with a solution in less than 20 mins.

    As a begginer it took me around 2 hours looking at countless youtube videos about this before finnaly getting to this- https://www.youtube.com/watch?v=moQ3Kr8ouiU

    this dude has done a 12 part series all about printf statements in java! By far the there is out there! You can come here and copy/paste the code to congratulate yourself or you can look up all 12 videos of this guy and get FULL understanding of printf in JAVA!

    Do yourself a favour and watch his videos! 'printf' is much larger than you realise!

    I kept getting it wrong and 4 hours later I gave up and came to discussions only to realise my code is 99% right. One this that wasnt right was %n which is bassically new line for printf, could have saved my 1 and a half hour by being more careful myself!