Search code examples
javaif-statementstring-formatting

I'm having issues with leading zeros


I'm attempting to get this to recognize the leading zeros in my program, and I thought using 'String.format("%03d", code);' would take care of it but I'm still not getting the expected result.

import java.util.Scanner;  
import java.io.*;
public class Main{
    public static void main(String args[]){
        Scanner sc =new Scanner(System.in);
        System.out.println("Enter the shipment code :");
        int code = sc.nextInt();
        String.format("%03d", code);
        // fill the code
        if( code ==  111 ){
            System.out.println("All ways");
        }

        else if( code ==  110){
        System.out.println("Airway and Waterway");
        }

        else if( code ==  011){
        System.out.println("Waterway and Roadway");
        }
        else if( code ==  010){
        System.out.println("Waterway");
        }
        else if( code == 101){
        System.out.println("Airway and Roadway");
        }
        else if(code ==  001){
        System.out.println("Roadway");
        }
    }
}

Solution

  • You're discarding the formatted value. You need to store it in a variable and compare it as string:

    String formatted = String.format("%03d", code);
    if( formatted.equals("111") ){
        System.out.println("All ways");
    }
    // ...