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;
}
}
Related
Currently I have a code that looks like this
import java.util.*;
public class Main
{
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String[] status={"f","f","f","f"};
System.out.println("Enter index to change: ");
int userInput = input.nextInt();
status[verify(status,userInput)] = "changed";
System.out.println(Arrays.toString(status));
}
private static int verify(String statusList[],int userIndex){
while(userIndex > (statusList.length-1) || userIndex < 0){
System.out.println("Invalid Index,enter correct Index ");
userIndex = input.nextInt();
}
return userIndex;
}
}
The "verify" method is used to check whether the user enters an index which is out of Bounds.
I am wanting to extend the "verify" method to check if the user enters a string but am not sure how to do that. I want a message to be displayed saying that the user has entered a string and want to keep getting the user input until a correct array index is entered.
Is there any way to check whether a string is entered, in the same method?
Actually, nextInt method on Scanner class will throw you an InputMismatchException if the user inputs something that's not Integer. Take a look at nextInt method signature. If you want, you can catch that exception and log message that you want into the console.
Take a look at the following code. Hope it works for you.
Java
import java.util.Arrays;
import java.util.Scanner;
public class Scan {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String[] status={"f","f","f","f"};
System.out.println("Enter index to change: ");
int userInput = verify(status, input);
status[userInput] = "changed";
System.out.println(Arrays.toString(status));
}
private static int verify(String statusList[], Scanner input){
do {
int userIndex=-1;
String line = input.next();
try {
userIndex = Integer.parseInt(line);
}catch(NumberFormatException e) {
System.out.println("Please enter a number.");
continue;
}
if(userIndex > (statusList.length-1) || userIndex < 0){
System.out.println("Invalid Index,enter correct Index ");
continue;
}else {
return userIndex;
}
}while(true);
}
}
I am trying to achieve a certain result or output before terminating the loop.
Here is my code:
import java.util.Scanner;
public class learnjava {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("How old are you?");
int age = scanner.nextInt();
scanner.nextLine();
System.out.println("Do you prefer cats or dogs?");
String animal = scanner.nextLine();
if (age > 10 || animal.equals("cats"))
{System.out.println("welcome!");}
else {System.out.println("No access");}
scanner.close();
}
}
Ideally I want to create a loop that makes my code run until system prints out welcome, so that I can avoid restarting the program. I want to provide the user another chance at inputting right answers once the first input fails without running again, hence the console should ask again "how old are you?"
You can use a do while loop for this use case. The actual validation logic can be put within the loop and the loop will be terminated only if the condition is invalid.
So in you case, the loop will check the condition age < 10 || !animal.equals("cat"). So the loop will run till the age exceeds 10 or the animal is "cat". As this is an exit check loop, it will exit only after printing "Welcome" to the console.
The code is as follows,
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String animal;
int age;
do{
System.out.println("How old are you?");
age = scanner.nextInt();
scanner.nextLine();
System.out.println("Do you prefer cats or dogs?");
animal = scanner.nextLine();
if (age > 10 || animal.equals("cats"))
{
System.out.println("welcome!");
}
else {
System.out.println("No access");
}
}while(age < 10 || !animal.equals("cat"));
scanner.close();
}
}
You use loops in java for repeated task. while loop is one of them
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
if (askUser(scanner)) {
System.out.println("welcome!");
break;
} else {
System.out.println("No access");
}
}
scanner.close();
}
private static boolean askUser(Scanner scanner) {
System.out.println("How old are you?");
int age = scanner.nextInt();
scanner.nextLine();
System.out.println("Do you prefer cats or dogs?");
String animal = scanner.nextLine();
return (age > 10 || animal.equals("cats"));
}
How about wrapping the logic in a while loop with a boolean variable to indicate the isFinished status:
import java.util.Scanner;
public class learnjava {
private static final String WELCOME = "welcome!";
private static final String ACCESS_DENIED_TRY_AGAIN = "No access";
public static void main(String[] args) {
boolean isFinished = false;
Scanner scanner = new Scanner(System.in);
while (!isFinished) {
System.out.println("How old are you?");
int age = scanner.nextInt();
System.out.println("Do you prefer cats or dogs?");
String animal = scanner.nextLine();
if (age > 10 || animal.equals("cats")) {
System.out.println(WELCOME);
isFinished = true;
} else {
System.out.println(ACCESS_DENIED_TRY_AGAIN);
}
}
scanner.close();
}
}
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.
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
}
What I'm assigned to do is create an object-oriented validator. The user is prompted to input an integer, and the application validates it. The end result will display on the console as follows (first 3 inputs being invalid, 4th being valid):
Welcome to the Validation Tester application
Int Test
Enter an integer between -100 and 100: X
Error! Invalid integer value. Try again.
Enter an integer between -100 and 100: -101
Error! Number must be greater than -101
Enter an integer between -100 and 100: 101
Error! Number must be less than 101
Enter an integer between -100 and 100: 100
I've been assigned to create a validation class before but never in the way I'm being asked to now. Before, I've been able to pass the sc and the prompt to the Validation class and have the methods process them accordingly. For example:
//MAIN
Scanner sc = new Scanner(System.in);
int x = Validator.getInt(sc, "Enter an integer: ", 0, 1000);
//VALIDATION CLASS
public class Validator{
public static int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextInt())
{
i = sc.nextInt();
isValid = true;
}
else
{
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public static int getInt(Scanner sc, String prompt,
int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println(
"Error! Number must be greater than " + min + ".");
else if (i >= max)
System.out.println(
"Error! Number must be less than " + max + ".");
else
isValid = true;
}
return i;
}
Done as above, I understand what is happening.
However now I'm assigned get the same results using similar methods but this time the sc has its own constructor.
public class OOValidator
{
public OOValidator(Scanner sc){}
public int getInt(String prompt){}
public int getIntWithinRange(String prompt, int min, int max){}
}
I'm not asking anyone to do the assignment for me in its entirety, but I'm at a loss as to how I can both prompt the user and pass the user's input using a class that has the sc and prompt separated.
I've tried several to code it several difference ways, non of which compile.
Just create an instance of your class
//MAIN
Scanner sc = new Scanner(System.in);
OOValidator val = new OOValidator(sc);
int x = val.getInt("Enter an integer: ");
// ...
int y = val.getIntWithinRange("Enter an integer: ", 0, 1000);
//VALIDATION CLASS
public class OOValidator {
private Scanner sc;
private static final String ERROR = "Error! Invalid integer value."
+ "Try again.";
public OOValidator(Scanner sc) {
this.sc = sc;
}
public int getInt(String prompt) {
while (true) {
System.out.print(prompt);
if (sc.hasNextInt()) {
i = sc.nextInt();
sc.nextLine(); // discard any other data entered on the line
break;
} else {
System.out.println(ERROR);
sc.nextLine(); // discard any other data entered on the line
}
}
return i;
}
public int getIntWithinRange(String prompt, int min, int max) {
// same logic - use directly sc which is an instance field
}
}