Home > OS >  how not to allow a negative number to be entered in for
how not to allow a negative number to be entered in for

Time:04-04

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();

}

CodePudding user response:

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");
  }
}

CodePudding user response:

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

  • Related