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:
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