Reputation: 13
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();
}
Upvotes: 1
Views: 2272
Reputation: 78
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
Upvotes: 0
Reputation: 1527
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");
}
}
Upvotes: 1