How to verify that input is a positive integer in Java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to create an input that will Verify the input is an Integer, and that it is positive. Right now i have this. How should i check if the integer is positive
EDIT: Also i need it to keep asking until you enter a positive integer
/**
* pre: none
* post: returns a positive integer as entered by the user
*/
public static int getInput(){
int a;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Desired Quantity.");
while (!scan.hasNextInt()){ //Checks if input is Integer
System.out.println("Enter A Positive Integer");
scan.next();
}
a = scan.nextInt(); //Assigns entered integer to a
return a; //replace with correct code
}

You can do this in a single loop, similar to the one that you have for skipping invalid input. However, since the loop needs to ensure two things (i.e. a number is entered, and that number is positive) you need to modify its body.
Since the input needs to be done at least once, a do/while loop is a better choice.
Start with a loop that satisfies the condition that you want, i.e. "I got a number, and that number is positive":
int num = -1;
do {
// We'll provide content of this in a moment
} while (num <= 0);
Once the loop exits, you know that num > 0, so the only task now is to write a body of the loop that takes us closer to that goal.
Inside the loop we need to check that the user entered a number. If he did, we harvest that number; otherwise, we tell the user to try again:
System.out.print("Please enter a positive integer number: ");
if (scan.hasNextInt()) {
num = scan.nextInt();
} else {
System.out.println("I need an int, please try again.");
scan.nextLine();
}
That's it - now you have a loop body that reads the value for you, and a loop condition that ensures that the value is positive on exit. Combine the loop with the loop body, and try it out. It should do the trick.

Simple:
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = input.nextInt();
if( number == 0)
{ System.out.println("Number is zero"); }
else if (number > 0)
{ System.out.println("Number is positive"); }
else
{ System.out.println("Number is negative"); }
On a side note:
Check Math.signum()
Returns the signum function of the argument; zero if the argument is
zero, 1.0 if the argument is greater than zero, -1.0 if the argument
is less than zero.

You can try this:
public static int getInput(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter Desired Quantity.");
int a = scan.nextInt();
while (a < 0){ //Checks if input is Integer
System.out.println("Enter A Positive Integer");
a = scan.nextInt();
}
return a;
}

Related

Java: show different results depending on User Console Input without try...catch statement

I try to write a programm in Java that gets user input using Scanner Class. The user has to enter any positive integer number. Depending on user actions, the results should be as follows:
The user has entered not an integer number -> the programm prints the message
Oops! You entered something different, but not an integer number, try again
The user has entered not a positive integer number -> the programm prints the message
You entered not a positive integer number, try again
The user has entered a positive integer number -> the programm prints the number
User's positive integer number - ...
I have written some code using loop and Scanner class
public static void main(String[] args) {
int userIntNum;
boolean isUserInputCorrect;
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
userIntNum = 0;
System.out.println("Please, enter a positive integer number");
isUserInputCorrect = (sc.hasNextInt() && (userIntNum > 0));
// double console input for correct integer number
while (isUserInputCorrect == false) {
if (!sc.hasNextInt()) {
System.out.println("Oops! You entered something different, but not an integer number, try again");
sc.nextLine();
} else if (sc.nextInt() <= 0) {
System.out.println("You entered not a positive integer number, try again");
sc.nextLine();
} else {
break;
}
}
userIntNum = sc.nextInt();
System.out.println("User's positive integer number - " + userIntNum);
When I put in the console a positive integer number (the correct input), the programm, for some reason, asks me to enter this number twice.
Moreover, if I put first an integer number and then any non-positive number separated by space, it will print this incorrect number. And if I put first an integer number and then not an integer number separated by space, it will throw an exception.
Why does it happen and how can I fix these errors?
First, I would eliminate isUserInputCorrect. You are trying to do too much with it, instead I would loop while userIntNum is less than or equal to zero. Also, try and limit variable scope. Something like,
Scanner sc = new Scanner(System.in);
int userIntNum = -1;
System.out.println("Please, enter a positive integer number");
// double console input for correct integer number
while (userIntNum <= 0) {
if (sc.hasNextInt()) {
userIntNum = sc.nextInt();
} else {
System.out.println("Oops! You entered something different, "
+ "but not an integer number, try again");
sc.nextLine();
}
if (userIntNum <= 0) {
System.out.println("You entered not a positive integer number, try again");
}
}
System.out.println("User's positive integer number - " + userIntNum);
Expanding on Elliott's answer above, I wanted to provide an alternative solution that addresses your following point:
Moreover, if I put first an integer number and then any non-positive
number separated by space, it will print this incorrect number. And if
I put first an integer number and then not an integer number separated
by space, it will throw an exception.
The Scanner class will read tokens individually in a temporal fashion. If you look at the nextInt() function you will see it that throws InputMismatchException which you can explicitly catch.
Additionally, take a look at the Java modulus operator. Since you are explicitly looking for even values, the modulus operator is extremely valuable here.
public static void main(String[] args) {
int userIntNum = 0;
boolean isUserInputCorrect = false;
#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please, enter a positive integer number");
try {
userIntNum = sc.nextInt();
isUserInputCorrect = (userIntNum > 0 && userIntNum % 2 == 0);
} catch (InputMismatchException ex) {
System.out.println("Invalid input: please enter an integer value");
sc.next();
}
} while(!isUserInputCorrect);
System.out.println("User's positive integer number - " + userIntNum);
}

How can I input an if statement inside a while loop?

import java.util.Scanner;
public class ex11
{
static Scanner type=new Scanner(System.in);
public static void main(String args[])
{
int fact=1;
System.out.println("Enter a natural number ");
int num=type.nextInt();
int i=1;
while(i<=num)
{
fact*=i;
i++;
}
System.out.println("Factorial of number " + num + " is " + fact);
}
}
I'm trying to place a conditional statement inside the while loop. The condition is to test for would be that of, if num is a negative number, S.O.P.("You entered a negative #"); in other words,
if(num<0)
S.O.P.("You entered a negative #");
However it doesn't print it properly.
If you check inside the loop then it will not work it will still multiply the fact. You need to make sure that the num is not negative before you start the while loop.
int num = 0;
do {
if (num<0){
System.out.println("You printed out a negative number");
}
System.out.println("Enter a natural number ");
int num=type.nextInt();
} while (num<0);
Also on a side note you should probably close your scanners when you are done using them.
The question is hard to understand but from what i read it appears you want a loop to run until a value is entered that meets your pre-condition of being positive
System.out.println("Enter a non negative number :: ");
int num = type.nextInt();
while(num < 0){
System.out.println("The number you entered was negative!");
System.out.println("Enter a non negative number :: ");
num = type.nextInt();
}
Loops like this are crucial to making sure the data that you are using is within the pre-condition of your operation which could cause DivideByZero errors or other problems. This loop should be placed before you ever use the value of num so you can make sure it is within context of your program.
The problem is that if the num is negative, it won't go inside the while loop that is because before the while loop you have initialize i=1, since any negative number is lesser than 1 the condition for while loop become false. If you want to check whether num is negative insert the if condition before the while loop as follows
import java.util.Scanner;
public class ex11
{
static Scanner type=new Scanner(System.in);
public static void main(String args[])
{
int fact=1;
System.out.println("Enter a natural number ");
int num=type.nextInt();
int i=1;
if(num < 0) {
System.out.println("You entered a negative #");
}
else{
while(i<=num)
{
fact*=i;
i++;
}
System.out.println("Factorial of number " + num + " is " + fact);
}
}
}
To answer your question .... like this:
int i = 1; // HERE
while (i <= num) {
if (num < 0) {
System.out.println("You entered a negative #");
}
fact *= i;
i++;
}
However that is not going to work.
Suppose that "num" that you read is less than zero.
At the statement labeled "HERE", we set "i" to one.
In the next statement, we test "i < num".
Since "num" is less than zero, that test gives "false" and we skip over the entire loop!
That means that your conditional statement in the loop body would not be executed ... if "num" is less than zero.
Since this is obviously homework, I will leave it to you to figure out what you should be doing here. But (HINT!) it is not putting the conditional inside the loop.
(Please note: I have corrected a number of style errors in your code. Compare your original version with mine. This is how you should write Java code.)
You basically have to check whether the number is less than 0. This is to be done while taking the input. You can just take the input inside a while loop in this manner:
System.out.println("Enter a natural #");
while(true){ //loop runs until broken
num = type.nextInt();
if(num>=0)
break;
System.out.println("Wrong input. Please enter a positive number");
}
The program control breaks out of the loop if num>=0, i.e., positive, else, it continues to the next part of the loop and displays the error message and takes the input again.
Please note that natural numbers are the ones >= 1. In your program, you are actually trying to input a whole number which is >= 0.

How can you check user input validation in Java?

I'm making a simple program that asks the user to input five numbers between 0-19. I would like to add something (like an if statement) after every number to make sure it's within that range. If not, the program should say "please read instructions again" and will then System.exit(0). This is the piece of the code that is relevant:
System.out.println("Please enter 5 numbers between 0 and 19");
System.out.print("1st Number: ");
userNum1 = scan.nextInt();
System.out.print("2nd Number: ");
userNum2 = scan.nextInt();
System.out.print("3rd Number: ");
userNum3 = scan.nextInt();
System.out.print("4th Number: ");
userNum4 = scan.nextInt();
System.out.print("5th Number: ");
userNum5 = scan.nextInt();
Any help would be greatly appreciated.
You can put this after each of your inputs, but you might want to think about putting this logic into its own method, then you can reuse the code and just call it with something like validateInput(userNum1);.
Replace val with your actual variable names.
if (val < 0 || val > 19) {
System.out.println("please read the instructions again");
System.exit(0);
}
First of all, I would create a for-loop that iterates N times, with N being the number of numbers you want to ask for (in your case, 5). Imagine your example with 50 numbers; it would be very repetitive.
Then, when you get each number with scan.nextInt() within your for-loop, you can validate however you want:
if (userNum < 0 || userNum > 19) {
// print error message, and quit here
}
Also, instead of just exiting when they input a number outside the range, you could have your logic inside a while loop so that it re-prompts them for the numbers. This way the user doesn't have to restart the application. Something like:
boolean runApplication = true;
while(runApplication) {
// do your for-loop with user input scanning
}
Then set the runApplication flag as needed based on whether or not the user put in valid numbers.
This code will do the trick for you, i added some securities :
public static void main(String[] args) {
int count = 1;
Scanner scan = new Scanner(System.in);
List<Integer> myNumbers = new ArrayList<Integer>();
System.out.println("Please enter 5 numbers between 0 and 19");
do {
System.out.println("Enter Number "+count+" ");
if(scan.hasNextInt()){
int input = scan.nextInt();
if(input >= 0 && input <= 19){
myNumbers.add(input);
count++;
}else{
System.out.println("Please read instructions again");
System.exit(0);
}
}else{
scan.nextLine();
System.out.println("Enter a valid Integer value");
}
}while(count < 6);
/* NUMBERS */
System.out.println("\n/** MY NUMBERS **/\n");
for (Integer myNumber : myNumbers) {
System.out.println(myNumber);
}
}
Hope it helps
Since you already know how many numbers you want the user to input, I suggest you use a for loop. It makes your code more elegant and you can add as many more entries as you want by changing the end condition of the loop. The only reason it looks long is because number 1, 2, 3 all end in a different format i.e firST secoND thiRD, but the rest of the numbers all end with TH. This is why I had to implement some if else statements inside the loop.
To explain the code, every time it loops it first tells the user the count of the number he/she is entering. Then numEntry is updated every time the loop loops, therefore you do not need to assign multiple inputs to multiple variables. It is more efficient to update the same variable as you go on. If the input the user inputs is less than 0 OR it is more than 19, the system exits after an error message.
System.out.println("Please enter a number between 0 and 19");
Scanner scan = new Scanner(System.in);
for(int i = 1; i <=5; i++){
if(i == 1)
System.out.println("1st Number");
else if(i == 2)
System.out.println("2nd Number");
else if(i == 3)
System.out.println("3rd Number");
else
System.out.println(i + "th Number");
int numEntry = scan.nextInt();
if(numEntry < 0 || numEntry > 19){
System.out.println("Please read instructions again.");
System.exit(1);
}

Getting all possible odd numbers in the user input

I am having difficulties with finding all possible odd numbers for my program. I am required to use a while loop to find all the odd numbers but i am not sure how to print it out. I dont know if im doing anything wrong in this block while((num1+num2)%2==0) because that was just a guess. Outline of the program is to get the user to enter 2 numbers that is an even multiple of the other number. I am not sure how that part either. After finding 2 numbers that is an even multiple of the other number, i am supposed to display all the odd numbers between the two numbers. Thanks alot in advance.
import java.util.Scanner; //imports the java utillity scanner
public class MyPrompter{
public static void main(String[] args){
System.out.println("Odd number display");
Scanner input = new Scanner(System.in); //scans for user input and stores in "input"
int num1,num2; //declares the variables i need for the pgrm
try{ //try statement to check for user input errors
System.out.println("Please enter your first number: ");
num1 = input.nextInt(); //stores input for the first number
System.out.println("Please enter your second number: ");
num2 = input.nextInt(); //stores input for the second number
while((num1+num2)%2==0){ //while loop to find all the odd numbers between the 2 numbers
System.out.println();
}
}
catch(java.util.InputMismatchException e){ //if the above error is met, message will be sent to the user
System.out.println("Please enter a valid ROUNDED NUMBER!");
}
}
}
How about something like this:
int num1 = 10;
int num2 = 50;
int current = num1;
while (current < num2) {
if (current % 2 != 0) {
System.out.println(current);
}
current++;
}
Set current to equal num1, continue the loop while current is less than num2. For each iteration check if current is odd and output it if it is. Increment current by one.

Java Scanner if/else and while statements [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 8 years ago.
I am trying to make a program that receives input from user, which is then used later on in the program. The problem I have is to make an exception. For example, if I only want the user to put in a number between 0 and whatever he previously put in. Here is an example:
Scanner input = new Scanner(System.in);
System.out.println("What length do you want your array to be?");
int length = input.nextInt();
int[] arr = full(length);
print(arr);
System.out.println();
System.out.println("Write a number between (0-"+length+"):");//Its here I want to add an exception.
int number = input.nextInt(); //if the user types in a greater value
check(arr,number); //of "length" or smaller value than 0
//I want the question to repeat itself
//until the criteria is met
You dont have to worry about the "check" or "print methods.
I don't believe you need an Exception, just a loop. Like a do-while loop such as
int number;
do {
System.out.println("Write a number between (0-" + length + "):");
number = input.nextInt();
if (number < 0) {
System.out.printf("%d is too low%n", number);
} else if (number > length) {
System.out.printf("%d is too high%n", number);
}
} while (number < 0 || number > length);
check(arr, number);
You do not need an exception, just add a do-while loop that checks whether it was a valid entry.
// ...
do
{
System.out.println("Write a number between (0-"+length+"):");
int number = input.nextInt();
} while( number < 0 || number >= length );
Note: I changed the condition to not include length since it appeared you were going to use that as an index to the array, and length is not a valid index in an array of length length.

Categories

Resources