This particular case can be worked with strings. I don’t really like the floating point alternative to make a response due to the problem with floating points.
So, how to solve the problem? Well, reading a string. And working with string. And staying only in string.
Whereas the return is a class object PartesNumero
with the fields String parteInteira
and String parteDecimal
, we could make the following builder:
public PartesNumero(String numeroCompleto) {
String partes[] = numeroCompleto.split("[^0-9]");
if ("".equals(partes[0]) {
this.parteInteira = 0; // fallback para entradas como ".75"
} else {
this.parteInteira = partes[0];
}
if (partes.length > 1) {
this.parteDecimal = partes[1];
} else {
this.parteDecimal = "";
}
}
And to read a string input (not validating its type, however):
Scanner sc = new Scanner(System.in);
String entrada = sc.next();
The complete program then would be:
public class Main {
public class PartesNumero {
public final String parteInteira;
public final String parteDecimal;
public PartesNumero(String numeroCompleto) {
String partes[] = numeroCompleto.split("[^0-9]");
if ("".equals(partes[0]) {
this.parteInteira = 0; // fallback para entradas como ".75"
} else {
this.parteInteira = partes[0];
}
if (partes.length > 1) {
this.parteDecimal = partes[1];
} else {
this.parteDecimal = "";
}
}
}
public static void main(String []args) {
Scanner sc = new Scanner(System.in);
String entrada = sc.next();
PartesNumero partes = new PartesNumero(entrada);
System.out.println(partes.parteInteira);
System.out.println(partes.parteDecimal);
}
}
Very good solution, clean and simple to understand!
– Sorack
@Carlosheuberger Yes, the question is not clear. If there are always two decimal places, one can do
int x = (int) (valorEntrada * 100); int real = x / 100; int frac = x % 100;
. But the question does not make very clear the purpose.– Victor Stafusa