Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Translating a "PrintInfo-method" from python to Java

I am working on learning myself how to code in Java on the basis of knowing python fairly well.

For the sake of learning, I’m am "translating" an old python Class "bankAccount" from python to Java. So far this is going quite OK, but I’m having trouble with a method that prints out information on the bankAccount object.

The printout method i am trying to translate from python to java is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    def print_info(self):
        first = self._first_name
        last = self._last_name
        number = self._number
        balance = self._balance

        s = f"{first} {last}, {number}, balance: {balance}"

        print(s)

This is what I have written in Java:

    public void printInfo() {
        String first = this.firstName;
        String last = this.lastName;
        double balance = this.balance;
        String s;

        s = String.format("\n%$1s %$2s %$f", first, last, "Balance: ", balance);
        System.out.println(s);
    }

The error message I’m getting is:

Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '$'
    at java.base/java.util.Formatter.checkText(Formatter.java:2732)
    at java.base/java.util.Formatter.parse(Formatter.java:2718)
    at java.base/java.util.Formatter.format(Formatter.java:2655)
    at java.base/java.util.Formatter.format(Formatter.java:2609)
    at java.base/java.lang.String.format(String.java:2897)
    at trix.uke1.BankAccount.printInfo(BankAccount.java:47)
    at trix.uke1.BankAccount.main(BankAccount.java:58)

I know how to get it working by typing:

System.out.println(this.firstName +" " + this.lastName + " " + "Balance: " + this.balance);

.. but I would like to be more fluent in using the String.format() function since I am very used to using f-strings in python.

Is there anyone who can help me solve this?
All help is welcomed and appreciated

>Solution :

I think it is just a syntax issue:

For instance:

String firstName = "Richard";
String lastName = "Yu";
double balance = 1E40;
    
String s = String.format("\n%1$s %2$s Balance: %3$f", firstName, lastName,balance);
System.out.println(s);

Output:

Richard Yu Balance: 10000000000000000000000000000000000000000.000000
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading