Exiting a while loop on java - java

I am trying to create a program where I use the getInt method to make sure that the user enters a positive number. I have this so far
public class Binary {
public static void main(String [ ] args) {
Scanner CONSOLE = new Scanner(System.in);
int decimal=getInt(CONSOLE, "Enter a positive integer: ");
}
public static int getInt(Scanner CONSOLE, String prompt) {
System.out.print(prompt);
while (!CONSOLE.hasNextInt()) {
CONSOLE.next();
System.out.println("Not an integer; try again.");
System.out.println(prompt);
}
int posInt=CONSOLE.nextInt();
while (posInt <= 0) {
System.out.println("Not a positive integer; try again.");
CONSOLE.next();
System.out.println(prompt);
}
return CONSOLE.nextInt();
}
}
The issue occurs that when the user does enter a positive number it still disregards the input and asks the user to enter a positive integer again. I guess I'm just not exiting the loop correctly but I'm not sure how.

Your problem is return CONSOLE.nextInt();
At the end of your method, you are calling CONSOLE.nextInt() which asks for input once more.
Return posInt, and you'll be fine.
Best of luck, HTH

Like the others said you can return posInt and you should be fine.
But i have some recommendations for your getInt method:
public static int getInt(Scanner CONSOLE, String prompt) {
//initialize vars
boolean valid = false;
int posInt = 0;
//while the input is not valid, loop over the evaluation
while(!valid){
System.out.print(prompt);
if (!CONSOLE.hasNextInt()) {
CONSOLE.next();
System.out.println("Not an integer; try again.");
//"continue" stops the loop here and starts it from the beginning
continue;
}
posInt=CONSOLE.nextInt();
if (posInt > 0) {
//valid = true will get us out of the loop
valid = true;
}else {
System.out.println("Not a positive integer; try again.");
}
}
return posInt;
}
This code will reevaluate the input from the beginning if the input before was invalid.
In your code if you enter a negative int you will be prompted to reenter a number.
But since you are already in the while (posInt <= 0) loop, it does not recheck if you actually enter a valid input.
The code i provided reevaluates the next input from the beginning until it is found valid.

Related

Validate User Input, check if input is positive number and not string of characters

I'm trying to write a program that can validate user's input before going to the next section, but i'm currently stuck with this. Whenever i enter a negative value first, it will bypass the condition or crashes.
If i input "A" , it will show "Please enter a valid number"
If i input "-1", it will show "Please enter a positive number"
But soon after i enter -1, if I input another negative value, it by pass the condition and accept the negative value, while input character will crashed the program.
What i want to achieve here to have a program that can
Check whether Input is number and not letter or string, and check if it's positive number
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Users = 0;
boolean isNumber;
System.out.print("Enter the number of Users ");
do {
if (input.hasNextInt()) {
Users = input.nextInt();
isNumber = true;
if (Users < 0) {
System.out.print("Please enter a positive number ");
Users = input.nextInt();
}
} else {
System.out.print("Please enter a valid number ");
isNumber = false;
input.next();
}
} while (!(isNumber));
}
You're not setting isNumber to False if it's less than 0. This means that, if you ever enter a negative value (and you haven't entered a string before), your program will ask you for another number again and it won't check if it's negative as isNumber will be True, meaning that the while loop will no longer run.
To fix this, add isNumber = False; to the end of the if (Users<0){ code block.
I see three problems with your code. The first one is that isNumber is being set to true even if the input is a negative number, so I would recommend only setting it to true after you've verified that it's not negative.
The second problem is that in your if (Users < ) { ... } block, you're getting input.nextInt(). You should really just go to the next iteration of the do-while loop and get the next input on the next iteration.
Third, you should initialize isNumber to false;
Try this code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Users = 0;
boolean isNumber = false;
System.out.print("Enter the number of Users ");
do {
if (input.hasNextInt()) {
Users = input.nextInt();
if (Users < 0) {
System.out.print("Please enter a positive number ");
// Remove this line:
// Users = input.nextInt();
} else {
// Moved this to an else block:
isNumber = true;
}
} else {
System.out.print("Please enter a valid number ");
// remove this because it's already initialized to false:
// isNumber = false;
input.next();
}
} while (!(isNumber));
}

Unexpected return value from recursive function

I wrote a short piece of code with the purpose of setting an integer value. However, it does not seem to return the correct value. For example, for the following inputs I would expect it to work like so.
Please enter a positive integer value
-458
Please enter a positive valid integer
58
58
However, the actual output is the following.
Please enter a positive integer value
-458
Please enter a positive valid integer
58
-458
In this example why does it return -458 instead of 58?
import java.util.InputMismatchException;
import java.util.Scanner;
public class IncorectValueReturned {
public void run() {
System.out.println("Please enter a positive integer value");
System.out.println(setInt());
}
private int setInt() {
int i = -1;
Scanner sc = new Scanner(System.in);
try {
i = sc.nextInt();
if(i < 0) {
System.out.println("Please enter a positive valid integer");
setInt();
}
} catch(InputMismatchException iME) {
System.out.println("Please enter a positive valid integer");
setInt();
}
sc.close();
return i;
}
public static void main(String[] args) {
IncorectValueReturned iVR = new IncorectValueReturned();
iVR.run();
}
}
You never change the first i that was invalid, you need to recover the value of the recursive calls
i = setInt();
And of course, you should not redeclare this Scanner over and over.
Use a Instance variable instead.
Scanner sc = new Scanner(System.in);
private int setInt() {
int i = -1;
try {
i = sc.nextInt();
if(i < 0) {
System.out.println("Please enter a positive valid integer");
i = setInt();
}
} catch(InputMismatchException iME) {
//Clear the scanner of this value
sc.next();
System.out.println("Please enter a positive valid integer");
i = setInt();
}
return i;
}
And close the scanner when you are done with it.
Careful, a value that throws an exception will remain in the input, you need to read it, I used Scanner.next() to remove a bad input like a a value bigger than Integer.MAX_VALUE.
You didn't assign i the new value from SetInt().
if(i < 0) {
System.out.println("Please enter a positive valid integer");
i = setInt(); // <- HERE
}

How would i do input validation?

Tells the user if the number entered is even or even. I need help with the input validation. The validation i need do is that the user cannot entered anything but a number. Trying to do the validation without the try and catch method.
import java.util.Scanner;
public class oddoreven {
public static void main (String [] args) {
Scanner input = new Scanner (System.in);
//declaractions
int num;
//while loop
do{
System.out.println("PLease enter a number to see whether it is even or odd. To end tyype in -99.");
num = input.nextInt();
// input valid
}while(num != -99); // loop ends
// begins the method
public static void is_odd_or_even_number(int number){
int rem = number%2;
\
You can call Scanner.hasNextInt() to determine if the next input is an int (and consume anything else). Also, you might make an infinite loop and break when the input is -99 (or 99, your code tests for 99 but your prompt says -99). Finally, you should call your method. Something like,
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num;
do {
System.out.println("Please enter a number to see whether it is "
+ "even or odd. To end type in -99.");
if (input.hasNextInt()) {
num = input.nextInt();
if (num != -99) { // <-- directions say -99.
is_odd_or_even_number(num);
} else {
break;
}
} else {
System.out.printf("%s is not a valid int.%n", input.nextLine());
}
} while (true);
}
You can use Scanner.nextLine() to get a string input. Then loop through the characters to make sure they are all digits. (assuming non-negative integers only)
string rawInput = input.nextLine();
boolean validInput = true;
for (char c : rawInput) {
if (!Character.isDigit(c)) {
validInput = false;
break;
}
}
if (validInput) {
int num == Integer.parseInt(rawInput);
// proceed as normal
}
else {
// invalid input, print out error message
}
You can use regex to check whether all the characters of string entered by user are digits or not,
num.matches("[0-9]+") // return true if all characters are digits
or
num.matches("^[0-9]*$") // return true if all characters are digits
but before that change your num = input.nextint() to num = nextLine() and make num as String. if you dont do this there is no need of validating user input as you are requiring.

User Input Error, no throwing Exceptions or using try{}catch{}

I'm trying to create a method that uses a while loop that includes a look ahead method to handle wrong user input: input out of 1-10 range or input a string. I am trying to do this with out throwing exceptions or using try{}catch{}; if possible. I haven't found a post that does not use these and all my attempts have failed so far. A basic idea will work.
will not stop if input is correct
import java.util.*;
public class UserErrors{
public static Scanner console = new Scanner(System.in);
public static void main(String[]args){
String s = "Enter a integer between 1-10: ";
get(s);
}
public static int get(String prompt){
System.out.print(prompt);
while(console.hasNext()){
while(!console.hasNextInt()){
console.next();
System.out.println("Invalid data type");
System.out.print(prompt);
}
if(console.nextInt() > 10 || console.nextInt() <1){
System.out.println("not in range");
System.out.print(prompt);
}
}
return console.nextInt();
}
}
requires the right answer to be imputed 3 times before it stops
import java.util.*;
public class UserErrors{
public static Scanner console = new Scanner(System.in);
public static void main(String[]args){
String s = "Enter a integer between 1-10: ";
get(s);
}
public static int get(String prompt){
System.out.print(prompt);
boolean b = false;
while(!b){
if(!console.hasNextInt()){
console.next();
System.out.println("Invalid data type");
System.out.print(prompt);
console.nextInt();
}
else if(console.nextInt() < 10 && console.nextInt() >1){
b = true;
}
else{
System.out.println("not in range");
System.out.print(prompt);
console.nextInt();
}
}
return console.nextInt();
}
}
I deleted some other failed attempts too. What do I need to fix (basic idea will do)?
There's an error:
if(console.nextInt() > 10 || console.nextInt() <1){ ... }
change this line to:
int i = console.nextInt();
if(i > 10 || i <1){ ... }
You can not reuse console.next...() just like that :)
Each nextInt call is a blocking call and it waits for user input.
For your code when you write below line:
if(console.nextInt() < 10 && console.nextInt() >1)
Essentially the console waits for first user input, checks it against 10 and then waits for next input which could be any (which you type second), not necessarily the same, waits for that and then finally enters the if condition.
The console input should always be taken upfront and assigned to our local variable and then it needs to be checked for your conditions like below:
int userInput = console.nextInt();
then the checking goes below with the userInput variable:
if(userInput < 10 && userInput >1)
The method nextInt() of the Scanner class read the standard exit
import java.util.*;
public class UserErrors{
public static Scanner console = new Scanner(System.in);
public static void main(String[]args){
String s = "Enter a integer between 1-10: ";
get(s);
}
public static int get(String prompt){
boolean b = false;
int number;
while(!b){
System.out.print(prompt);
if(!console.hasNextInt()){
console.next();
System.out.println("Invalid data type");
System.out.print(prompt);
console.nextInt();
}else {
number = console.nextInt();
if(nb<1 || nb>10){
System.out.println("not in range");
}else{
b=true;
}
}
}
return nb;
}
}

Java scanner adding variable conditions

I'd like to ask how do i exactly condition what my program does if my user types in a character or a string if i want him to type an integer instead? I tried to do it how i showed here in quotes and also tried with "equals". The second method didn't work the first seems to be behaving strangely the IF part works but ELSE is completely ignored.
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter first integer: ");
int number1 = input.nextInt();// prompt
if (number1 == (char)number1){
System.out.println("Ok.");
}
else{
System.out.println("You were supposed to type in an int..");
System.exit(1);
}
System.out.print("Enter second integer: ");
int number2 = input.nextInt();// prompt
int sum =(number1 + number2);
System.out.printf("Your sum is: %d%n", sum);
}
I suggest you to use the regular expression in the hasNext() function as follows to have a finer control, for example use the following pattern if you look for the numbers,
sc.hasNext("[0-9]+")
Here is the documentation for the hasNext(String pattern) function,
public boolean hasNext(Pattern pattern)
Returns true if the next complete token matches the specified pattern. A complete token is prefixed and postfixed by input that matches the delimiter pattern. This method may block while waiting for input. The scanner does not advance past any input.
Here is the simple code to perform the check,
Scanner sc=new Scanner(System.in);
int input = 0;
while(true) {
System.out.println("enter a number");
if(sc.hasNext("[0-9]+")) {
input = sc.nextInt();
break;
} else {
System.out.println("not a number, try again");
sc.next(); // just consume, but ignore as its not a number
}
}
System.out.println("Entered number is : "+input);
You can use a user defined function as shown below and call it
public static boolean isNum(String input)
{
try
{
int d = Integer.parseInt(input);
}
catch(NumberFormatException e)
{
return false;
}
return true;
}
Then you can call this method from your main function.
if(isNum(number1))
I am not sure if I understand your question, but I see this as follows:
Users will always type a sequence of characters from the input, then your program has to check if that String can be converted to Int, if it can not be converted it should prompt back to the user telling the typed data is not an int. In that case your nextInt will throw an InputMismatchException.
Probably a much more elegant solution is to use hasNextInt(10):
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter first integer: ");
if (input.hasNextInt(10)){
System.out.println("Ok. Typed number: " + input.nextInt());
}else{
System.out.println("You were supposed to type in an int..");
System.exit(1);
}
[...]
}
Try this,
try {
int number1 = sc.nextInt();// prompt
System.out.println("Ok.");
} catch (InputMismatchException ex) {
System.out.println("You were supposed to type in an int..");
System.exit(1);
}
Scanner.nextInt(); Scans the next token of the input as an int.
Program won't execute beyond this line if input is not int.
So it will never enter else part. Don't do any int validation.
I would suggest always use try/catch block to handle incorrect input and show useful message. Also don't forget to close Scanner object.

Categories

Resources