-1

I am trying to validate negative numbers but I haven't got clear how to do it, I've tried many steps but it's impossible, I think this the part of the code where I've got to validate because here is where it starts to do the rest, example if after entering name of employee it asks me to enter salary so I've got to avoid negative numbers.

for (int i = 0; i < e; i++) {
    System.out.println("Ingrese el nombre del "+(i+1)+" empleado");
    arr[i][0] = b.readLine();
    for (int j = 1; j < 4; j++) {
        System.out.println("ingrese el "+Concepto(j-1));
        arr[i][j]=String.valueOf(b.readLine());
    }
}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • boolean isNegative = (salary <0 ) ? true : false; This is ternary operator; It is short for simple if else block – Shubham Srivastava Sep 21 '20 at 10:30
  • 3
    @ShubhamSrivastava That would be a weird way to write `boolean isNegative = (salary < 0);` – khelwood Sep 21 '20 at 10:31
  • @khelwood oops yea this is way better :P – Shubham Srivastava Sep 21 '20 at 10:32
  • Hello and welcome. Your question is not very clear. Are you perhaps asking how to keep asking for a number when the format is not valid instead of going forward and asking for salary? – Federico klez Culloca Sep 21 '20 at 10:35
  • 1
    Does this answer your question? [Java - Check if input is a positive integer, negative integer, natural number and so on.](https://stackoverflow.com/questions/19766051/java-check-if-input-is-a-positive-integer-negative-integer-natural-number-an) – flaxel Sep 21 '20 at 10:37
  • @FedericoklezCulloca hi thanks, what I want it's to avoid a negative value for example when the programme is executed it asks me for number of employee right? then I enter 4 then it asks me name,salary etc so if by mistake I enter in salary I don't know -100 then I'd like to show message or just an error or the same if I enter -1 as name. cheers – Johan Sebastian Gil Lopez Sep 21 '20 at 14:52
  • @JohanSebastianGilLopez take a look [here](https://stackoverflow.com/questions/60698078/how-do-i-make-a-loop-that-commands-the-user-to-keep-inputing-a-value-until-if-co?noredirect=1&lq=1). – Federico klez Culloca Sep 21 '20 at 15:23

3 Answers3

0

Negative numbers are always less than 0.

So just add a condition : if ( value > 0 ) -- positive else -- negative

You can also use - For double and float values: Math.signum() and for Integer values: Integer.signum(int i)

0

You can use the Comparision operator. this are the comparision operator in Java:

>(greater than),
<(less than),
== (equal to),
!= (not equal),
>=,
<=

If any number is (> 0) then its positive number and if its (< 0) its negative number.

0

You can simply use the ternary operator,

int value = value > 0 ? (value : 0);

0 - Some default value if it's a negative