Search code examples
javastringoutputprintfisbn

ISBN Format couldn't write the output


I want to make the Output like this: 9-562-32458-4, 0-321-57351-X

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);


        System.out.print("Enter 9 digit number:  ");

        String num = input.next();
        int sum = 0;
        for (int i = 1; i <= num.length(); ++i) {
            sum += (i * num.charAt(i - 1) - '0');
        }

        int d10 = (sum % 11);
        if (d10 == 0) {
            System.out.println("Formatted ISBN: "+ num + "X");
        } else {            
            System.out.println("Formatted ISBN: "+ num + d10);

       }
      }
    }

I tried with printf but couldnt make it.


Solution

  • Using System.out.printf() and String.substring():

    if (d10 == 0) {
        System.out.printf("%c-%s-%s-X", num.charAt(0), num.substring(1, 4), num.substring(4));
    }
    else {
        System.out.printf("%c-%s-%s-%d", num.charAt(0), num.substring(1, 4), num.substring(4), d10);
    }
    

    Or, to avoid repeated code:

    System.out.printf("%c-%s-%s-", num.charAt(0), num.substring(1, 4), num.substring(4));
    System.out.print(d10 == 0 ? "X" : d10);
    

    *You should add a check to ensure that num.length() == 9.