'how not to allow a negative number to be entered in for

I have tried Math.abs and if statement and nothing works. I am a bit confused. How can I not accept negative numbers with for loop in Java , the user can not enter negative numbers as defense programming? Take the following piece of code :

for(int i=0; i<arr.length; i++) {

    System.out.print("Νο. " + (i + 1) + ": ");
    arr[i] = input.nextDouble();

}


Solution 1:[1]

Wrap the reading of the value in a loop. Do not exit the loop until the the user enters a non-negative value. For example..

for (int i=0; i<arr.length; i++) {
  while (true) {
    System.out.print("??. " + (i + 1) + ": ");
    arr[i] = input.nextDouble();
    if (arr[i] >= 0) {
      break;
    }
    System.out.println("Value cannot be negative");
  }
}

Solution 2:[2]

I suppose you are pretty new to Java. Welcome to Java's magical world :)

Depending on what your code looks like, a more "professional" way is to throw an exception: You may Google a little bit and try to customize your code and how it will react to the exception.

On the other hand, it seems like a simple project, so something like

            Double a  = input.nextDouble();
            if(a > 0){
                System.out.println("No negative values allowed");
            }else{
                arr[i] = a;
            }

could be enough

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vsfDawg
Solution 2 geomal