The big trick is to use the module mathematical function or absolute value to print what you want. Because it is a fairly common function it is possible to find it in most programming languages in java the same is defined in Math.abs() and abs() is the acronym for absolute in English.
This way your code could use this way:
public class Main {
public static void main(String[] args) {
int i1 = -10;
//Pega o valor absoluto de i1 isto é o módulo do mesmo
int i2 = Math.abs(i1);
System.out.println(i1);
System.out.println(i2);
}
}
Another way to do this would be through regular expressions, but it would make no sense to use a regular expression and conversions just to pick up the module from a number once this operation would be very costly (although possible):
public class Main {
public static void main(String[] args) {
int i1 = -10;
String regex = "" + i1;
regex = regex.replaceAll("[^0-9]", "");
int i2 = Integer.parseInt(regex);
System.out.println(i2);
}
}
Note that it’s pretty much the same if you did it with replace:
regex = regex.replaceAll("-", "");
or
regex = regex.substring(1); //retira o primeiro caractere
Although all these methods work does not compensate to create a String object only to make a conversion when Java already provides the function in the Math Library.
Math.abs
– bfavaretto
Math.abs(number);
– Douglas Mesquita
Use good old math, just multiply by -1
int i2 = i1 * (-1)
and use aif (i1 < 0)
to check if the number is negative.– Olimon F.
@Olimonf., just do
int i2 = -i1
, nay?– Pedro Lorentz
@Pedrolorentz I’m not very experienced with java, but I think the 3 solutions posted should work, but I don’t know about the performance of each or the right way. So I posted as a comment and no reply :|
– Olimon F.
@Olimonf., in the text of the question he had already used
-i1
, hehe. As for performance, the multiplication is expected to be slower yes (but I hope the compiler can optimize and transform into the unary operator).– Pedro Lorentz
Here has an interesting solution (for C++, but should work in Java as well).
– bfavaretto
I honestly don’t understand your question. Do you want a way to convert a negative to a simpler positive than to put a negative sign in front of the variable? I think it’s impossible. Maybe what you wanted to ask was not exactly that, if that’s the case please clarify your question.
– Math
I honestly don’t understand your question. At which point it was not explicit that, I was looking for a form of conversion from positive to negative without changes of signals explicitly. As @bfavaretto said, Math.abs
– Douglas Mesquita