I am trying to write a loop that will first ask a user to input a number, then make sure the number is above zero and not negative. If it is zero or negative I want to display the message "Please enter a positive number above 0". And then ask the user to input another number.
5 Replies - 3923 Views - Last Post: 27 March 2011 - 06:04 PM
#1
A loop to allow only positive numbers above 0 as input.
Posted 27 March 2011 - 05:40 PM
Replies To: A loop to allow only positive numbers above 0 as input.
#2
Re: A loop to allow only positive numbers above 0 as input.
Posted 27 March 2011 - 05:44 PM
int value = -1;
Scanner scanner = new Scanner(System.in);
while(value < 0) {
System.out.print("Enter a value > 0: ");
value = scanner.nextInt();
if(value < 0)
System.out.println("sorry write a value > 0")'
}
#3
Re: A loop to allow only positive numbers above 0 as input.
Posted 27 March 2011 - 05:44 PM
Something like this:
The whole concept basically is: read in a number, if it meets conditions, stop, if not, re-do until the conditions get met.
The whole concept basically is: read in a number, if it meets conditions, stop, if not, re-do until the conditions get met.
Scanner sc = new Scanner(System.in);
int num = 0;
while (num <= 0) {
System.out.print("Please enter a number: ");
num = sc.nextInt();
if (num <= 0) {
System.out.println("Please enter a number above 0!");
continue;
}
}
#4
Re: A loop to allow only positive numbers above 0 as input.
Posted 27 March 2011 - 05:46 PM
pbl, on 27 March 2011 - 05:44 PM, said:
int value = -1;
Scanner scanner = new Scanner(System.in);
while(value < 0) {
System.out.print("Enter a value > 0: ");
value = scanner.nextInt();
if(value < 0)
System.out.println("sorry write a value > 0")'
}
pbl, value <= 0 or else you're allowing 0 as an input
This post has been edited by TFoSSDQ: 27 March 2011 - 05:47 PM
#5
Re: A loop to allow only positive numbers above 0 as input.
Posted 27 March 2011 - 05:48 PM
Select < or <= the choice is yours
The concept remains the same
The concept remains the same
#6
Re: A loop to allow only positive numbers above 0 as input.
Posted 27 March 2011 - 06:04 PM
Manbearpig101, on 27 March 2011 - 05:44 PM, said:
Something like this:
The whole concept basically is: read in a number, if it meets conditions, stop, if not, re-do until the conditions get met.
The whole concept basically is: read in a number, if it meets conditions, stop, if not, re-do until the conditions get met.
Scanner sc = new Scanner(System.in);
int num = 0;
while (num <= 0) {
System.out.print("Please enter a number: ");
num = sc.nextInt();
if (num <= 0) {
System.out.println("Please enter a number above 0!");
continue;
}
}
Thanks for your help! I had basically had this but I forgot to declare an initial value for num so I could not figure out why it wasn't working.
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote




|