Java validating a range of numbers from user input - java

I have been having problem with my validation, and it is stressing me out, I have done it in various ways with different loops, and the one I have as of now is this one, if I take out the IF statement if will function well for numbers, but since my program can only accept numbers from 1 to 5 I want to take the extra step into validating the number and then returning it. I try declaring the int option inside a loop but does not carry out to the return statement.
public int makeOption(){
int option;
System.out.println("Choose from the following options: ");
System.out.println("(1)Create entry || (2)Remove entry || (3)List entry || (4)List All || (5)Exit ");
while(!reader.hasNextInt()){
System.out.println("Choose a valid option.");
reader.next();
}
if(reader.nextInt()<1 || reader.nextInt()>5){
System.out.println("Choose a valid number from options.");
reader.next();
}
option = reader.nextInt();
System.out.println("You choosed: " + option);
return option;
}

Swap out your if statement for a switch statement:
int input = reader.nextInt();
switch(input)
{
case 1: // Do something
break;
// blah blah blah more cases.
default: System.out.println("Please enter a correct value.");
}
A note on your code
When you call reader.nextInt(), you're telling the stream to expect another int. You're not viewing the same value. You should store it in a variable, before using it.

Related

Ask for input again if wrong input is entered

I am new to Java programming. I want the program to ask for input again if wrong input is entered by the user. What must I do? Please help! Jump to the 'if else if' part if you want to avoid the mess... And not being rude but please don't request for closing the question if you can't answer.
case 'A': case 'a':
System.out.println("You selected NOS Tank.");
int price;
double quantity;
double variant=0;
System.out.println("Select the variant: ");
System.out.println("Enter 'D' without apostrophe for dry or 'W' for wet");
variant=xss.next().charAt(0);
if (variant=='D' || variant=='d')
{
System.out.println("The price of dry nitrous oxide system is: $600");
}
else if (variant=='w' || variant=='W')
{
System.out.println("The price of wet nitrous oxide is: $740");
}
else
{
System.out.println("Invalid input.");
}
It has been 28 days since you asked your doubt so I don't know if you have come across the answer or not but here's my solution.
To accept the correct input you need to make use of a while loop, loops are iterations in java which run for multiple number of times as per the given instructions. In this program I have incorporated a while loop whose condition is true always, so basically it is an infinite loop. If the inputted variant is correct and matches with any one of the if condition then the loop will break automatically because of the "break;" statement.
break; is a jump statement in java which allows you to terminate a loop when your requirements are met.
Given below is your required program code.
Hope this solves you query :)
case 'A': case 'a':
System.out.println("You selected NOS Tank.");
int price;
double quantity;
double variant=0;
System.out.println("Select the variant: ");
while(true)
{
System.out.println("Enter 'D' without apostrophe for dry or 'W' for wet");
variant=xss.next().charAt(0);
if (variant=='D' || variant=='d')
{
System.out.println("The price of dry nitrous oxide system is: $600");
break;
}
else if (variant=='w' || variant=='W')
{
System.out.println("The price of wet nitrous oxide is: $740");
break;
}
else
{
System.out.println("Invalid input.");
System.out.println("Please enter the variant again:");
}
}

Creating a basic menu, why can't I get this right? -Java

I'm taking an Intro to Java class, and I haven't been having any trouble until now. I don't know if I'm just being a fool and the answer is simple but here goes.
I need to create a simple menu. I prompt the user, and then they enter an integer to choose one option. But there also needs to be an option to type "X" and exit the program.
Scanner in = new Scanner(System.in);
System.out.println("Welcome to the Math Study Guide!");
System.out.println("Which arithmetic table would you like to use?");
System.out.println("1) Addition");
System.out.println("2) Subtraction");
System.out.println("3) Multiplication");
System.out.println("4) Division");
System.out.println("X) Exit the program");
int input = in.nextInt();
if (input <= 5 )
{if (input == 1){System.out.println("Addition");}
{if (input == 2){System.out.println("Subtraction");}
{if (input == 3){System.out.println("Multiplication");}
{if (input == 4){System.out.println("Division");}
else {System.out.println("You have exited");}
Testing it, whenever I type "X" it shuts down everything and doesn't tell me I've exited. Is there a general input I can use where you can enter either an int or a String?
As already stated in some comments, your probleme is the data-type. If someone enters 'X' in the program, it is expected to be an integer value, which it is not.
To get your Program working you need to alter your datatype from int to String
String input = in.next();
this will get you the input.
Now make a switch/case instead of your if-statements
switch (input) {
case "1" : System.out.println("Addition");
break;
case "2" : System.out.println("Subtraction");
break;
deafult: System.out.println("You have exited the program");
break;
}
If you are not familiar with the switch/case statement: case "1" checks if input equals "1". If true it prints out "Addition", after that it is important to make a break; otherwise it would go on checking if input equals "2" and so on.
the default branch is activated if nothing else matches. So your program would also write "You have exited the program" if your input was e.g. "r". If you don't want that, just add another case "x" and write your thing.

"hasNextInt" does not detect subsequent input; where to put "nextLine"?

I am brand new at Java and this one is throwing me. Using the below code it loops through for the first question until I enter anything but an integer but after finishing that loop it does not stop for the remaining question.
Through a bit of research and reading I have found that I need to use the in.nextLine() to eat the newline character after the input. However no matter where I place the nextLine() it doesn't work? I thought it would be after the first int input = in.nextInt(); line but that did not work. Any help on where it would go and why?
System.out.print("How many CUs per course are remaining in your degree program? Enter any letter to quit: ");
while (in.hasNextInt()) { // Verify input is an integer
int input = in.nextInt();
if (input <= 0) // Verify that input is not negative or zero
{
System.out.println("Please enter a positive number or any letter to quit");
System.out.print("Add another course or any letter to quit: ");
} else {
courseCuList.add(input);
System.out.print("Add another course or any letter to quit: ");
}
}
System.out.print("How many CUs do you plan to take per term?");
while (in.hasNextInt()) {
int input = in.nextInt();
// in.nextLine(); This line consumes the \n
if (input <= 0) {
System.out.println("Please enter a whole positive number.");
System.out.println("How many CUs do you plan to take per term?");
} else {
cuPerTerm = in.nextInt();
}
}
Your problem is that in while (in.hasNextInt()) each call of hasNextInt needs to wait for user input, and then test if it is integer or not.
So each time user give integer, condition will be evaluated to ture, loop will execute and condition will need to be checked again, and if it is integer loop will execute again. This will go again and again until hasNextInt will be able to return false, for instance when user will give non-integer - like letter. But in this case condition in next loop will also return false because this non-integer value was not consumed after first loop. To let second loop work you would need to invoke nextLine two times
to consume line separator after previously put correct integer
to consume actual non-integer value
But this may also fail if user will not put any integer before non-integer value because there will be no line separator to consume.
So consider changing your logic to something similar to
boolean iterateAgain = true;
System.out.print("give me positive number: ");
while (iterateAgain) {
// this inner loop will move on only after getting integer
while (!in.hasNextInt()) {//here program waits for user input
in.nextLine();// consume non-integer values
System.out.print("that wasn't positive number, try again: ");
}
int number = in.nextInt();// now there must be number here
in.nextLine();// consume line separator
if (number > 0) {
System.out.println("you gave " + number);
// do what you want with this number
iterateAgain = false;// we can leave loop
} else
System.out.print("that wasn't positive number, try again: ");
}
If you want to execute next loop then all you need is reset iterateAgain value to true.
You need to read twice.
The exit condition on your while loop is hasNextInt() - checking to see if the next token is an integer doesn't actually clear that token, which means that the next nextLine() is going to read the token, and the subsequent nextLine() will read the newline character.
To demonstrate this, place the following between the loops:
System.out.println(in.nextLine() + " | " + in.nextLine());
For the input 4, 4, A, you will see the output:
How many CUs per course are remaining in your degree program? Enter any letter to quit: 4
Add another course or any letter to quit: 4
Add another course or any letter to quit: A
| A
How many CUs do you plan to take per term?
There are two tokens that need to be cleared from the buffer, and neither of them are integers. Because of this, no matter where you put nextLine(), it will fail - you need to insert it twice. If you only insert it once, the next token won't be an integer, and hasNextInt() will fail when the program tries to enter the second loop.
In order to get your program to work, simply insert:
in.nextLine(); in.nextLine();
before the second loop. (Note that you shouldn't put both this and the print-out in, as this will read four times.)

JAVA: Menu Infinite-loop

This is a follow up to a question I have asked previously that did get answers that should have fixed my problem, but unfortunately did not. My program reads in a text file and organises data before giving the user a number of options. When the program gets to this point I want to user to be able to select an option, that performs an operations, but then returns the user back to the start point to be able to perform more operations. This is the answer I liked best (thanks to Octopus) and am currently trying to implement.
//set choiceentry to -1, this will make it to enter while loop
int choiceentry = -1
while(choiceentry < 1 || choiceentry > 3){
System.out.println("Enter \"1\", \"2\" or \"3\"");
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
switch(choiceentry){
case 1:
//do logic
break;
case 2:
//do logic
break;
case 3:
//do logic
break;
}
}
As I see it, the program should enter the loop initially, allow the user to input a selection, then return back to "enter a value". However, the program does not return, and terminates after one operation. How can I prevent this to continue the program running infinitely?
Thanks in advance!
The current while loop is there to get valid input -- don't change it.
You need to wrap this code in another while loop that loops til a sentinal value is entered.
while (!isSentinalValue) {
while (inputNotValid) {
// get valid input
}
}
Edit
More specifically in pseudocode:
while (!isSentinalValue) {
input = invalidValue
while (inputNotValid) {
getInput
}
use input to do menu things
}
So I would not have the switch block inside of the inner loop, since that loop concerns itself only with making sure that the input entered is valid. Do the switch block outside of the inner loop, and be sure to set the sentintal value that allows the user to escape the outerloop when appropriate.
Your while(choiceentry < 1 || choiceentry > 3) condition is wrong. If you want it to loop , then you have to make it between 1 and 3 .
So this also means that you will have to change your choiceentry initialization value. This will work.
int choiceentry = 1
while(choiceentry >=1 && choiceentry <= 3){
System.out.println("Enter \"1\", \"2\" or \"3\"");
if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
....
}
your loop only runs while choiceentry is less than 1 or greater than 3. As soon as the user enters one of those values, the loop exits.
Learn to use a debugger.
place the following code after switch
if(choiceentry == 4){
break;
}
Now when you will input 4 then it will be terminated, you can use any value other then 4
Use break only when user wants to quit(Say when choiceentry=0). You can use "continue" to make loop infinite. Sample code is given for reference
int choiceentry = 1; // can set any int value except 0 (exit code is 0 for this example)
Scanner scanchoice = null;
while (choiceentry != 0) {
System.out.println("Enter \"1\", \"2\" or \"3\" ..Press 0 to quit");
scanchoice = new Scanner(System.in);
if (scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();
// System.out.println("choiceentry=" + choiceentry);
switch (choiceentry) {
case 0:
{
System.out.println("Bye Bye");
break;
}
case 1:
{
System.out.println("In Case 1");
continue;
}
case 2: {
System.out.println("In Case 2");
continue;
}
case 3: {
System.out.println("In Case 3");
continue;
}
}
}

How to check if an input is an int and is between two values

I created a method to see if a value that the user entered is type int and is between liminf and limsup. It returns the value so I can use it as a menu option.
The string message tells the user to enter something, and the error tells the user to use a number between limunf and limsup.
My problem is that, for example, if the user enters the number 10 and the liminf is 7 and limsup e 9, it runs like the number 10 was between limsup and liminf.
public static int readInput(String message, String error, int liminf, int limsup, Scanner rd){
int option = 0;
do {
option = rd.nextInt();
System.out.println(message);
while (!rd.hasNextInt()) {
System.out.println("Please enter the option");
rd.nextLine();
}
option = rd.nextInt();
canal.nextLine();
} while (option > limsup || option < liminf);
return option;
}
When you're checking input, you need to do two things:
Check that the value is actually an integer
Check that the value is in the range
For checking if a value is an integer, you can use one of two approaches. Use hasNextInt on your Scanner, or use Integer.parseInt and catch NumberFormatExceptions. You said in your comments you can't use the second one, so we'll use the first one.
You always have to call hasNextInt before you you call nextInt, so you can do it like this:
int option = 0;
System.out.println(message);
System.out.println("Please enter the option");
while (!rd.hasNextInt()) {
rd.nextLine(); // Clears the invalid input
System.out.println("Please enter the option");
}
option = rd.nextInt();
This will loop until the user enters an int, then it will get that int. Note that not calling hasNextInt before calling nextInt will cause an error, which will happen in your current code if you try to enter a non-number.
Next, you need to do the bounds checking. You want it to be between limsup and liminf, where limsup > liminf, if I'm not mistaken. We need to determine the condition that will allow this.
Between is achieved by using greater than the lower number and less than the higher number. In this case, that's option >= liminf && option <= limsup. We want to loop when it's not this, so we can just wrap the whole thing in !():
int option = 0;
do {
System.out.println(message);
System.out.println("Please enter the option");
while (!rd.hasNextInt()) {
rd.nextLine(); // Clears the invalid input
System.out.println("Please enter the option");
}
option = rd.nextInt();
} while (!(option >= liminf && option <= limsup));
return option;
I'll let you figure out how/where to print the error message, but this should get you started.
Worth noting:
hasNextInt, nextInt, nextLine, etc. will all wait for user input if you use Scanner rd = new Scanner(System.in);
Using nextLine is necessary to clean out the old input and force the user to enter new input
While De Morgan's laws are cool, the easiest way to invert a condition is just to wrap it in a !()
Change you condition in while like this :
while (option <= limsup && option >= liminf);
With your current condition, when you have option = 10 and limsup = 9 then your condition option > limsup will evaluate to true and as you are using || (OR opeartor ) even if the second condition evaluates to false the whole expression will evaluate to true.
Here is how you test if a string is an integer:
private static boolean isInteger( String s ){
try{
Integer.parseInt(s);
return true;
catch( Exception e ){
return false;
}
}
However, since you are using the nextInt() function this is not necessary as you will only get integer inputs this way anyways.
while ((option > limsup) || (option < liminf))
You can check that if the input is an integer or not with Integer.parseInt(input); something like :-
try {
String s = "a";
int i = Integer.parseInt(s);
return true;
}
catch(NumberFormatException nfe){return false;}
and change the condition like:-
while (option <= limsup && option >= liminf);
I beleive, its your readLine is making it to ignore the next token(10) itself as its reading the entire line while hasNextInt checks the single token. Try simple as below (use next and remove the extra rd.nextInt() as first statement in your loop):
do {
System.out.println(message);
while (!rd.hasNextInt()) {
System.out.println("Please enter the option");
rd.next();
}
//now the next token is int
option = rd.nextInt();
//flush the new line if any
rd.nextLine();
} while (option > limsup || option < liminf);
Your check in the while is wrong (option > limsup || option < liminf)
Look at option > limsup, 10 is bigger then 9 that is why you got this problem

Categories