So basically, I need to get the user to enter a reference number; it cannot be automatically generated.
It needs to be 2 Numbers, a Letter and a Number again.
Here's my code, but I cannot for the life me get it working, I had it working via a way that automatically generates a reference number, but now we need to change it so it gets the user to manually generate one and I'm just sat staring at NetBeans like "Oh errmmmm..."
static String getReferenceNumber() {
Scanner refScanner = new Scanner(System.in);
String referNumber = null;
System.out.println("Please enter a Reference Number");
System.out.println("It must be 2 Letters and 3 Numbers and a Number");
String input = refScanner.nextLine().toUpperCase();
while (!Policy.refCheck(input)) {
System.out.println("Please enter a Reference Number");
System.out.println("It must be 2 Letters and 3 Numbers a Nuber");
if (input.length() !=5) {
referNumber = false;
} else if ((!Character.isLetter(input.charAt(0)))
||!Character.isLetter(input.charAt(1))
||!Character.isDigit(input.charAt(2))
||!Character.isDigit(input.charAt(3))
||!Character.isDigit(input.charAt(4))){
referNumber = false;
}
System.out.println("");
System.out.println(referNumber);
return referNumber;
}
You never assign the actual input to the referNumber, instead you just assign Booleans?
Therefore at the end you are returning a Boolean or null when the return value needs to be a string.
static String getReferenceNumber() {
Scanner refScanner = new Scanner(System.in);
String referNumber = "";
boolean test = false;
while (!test) {
System.out.println("Please enter a Reference Number");
System.out.println("It must be 2 Letters and 3 Numbers:");
String input = refScanner.nextLine().toUpperCase();
if (input.length() !=5) {
test = false;
System.out.println("Invalid reference");
} else if ((!Character.isLetter(input.charAt(0)))
||!Character.isLetter(input.charAt(1))
||!Character.isDigit(input.charAt(2))
||!Character.isDigit(input.charAt(3))
||!Character.isDigit(input.charAt(4))){
test = false;
System.out.println("Invalid reference");
} else {
referNumber = input;
test = true;
}
}
System.out.println(referNumber);
return referNumber;
}
I have changed the condition for the while loop and altered your if statements. I hope this helps.
Related
must create a java application that will determine and display sum of numbers as entered by the user.The summation must take place so long the user wants to.when program ends the summation must be displayed as follows
e.g say the user enters 3 numbers
10 + 12+ 3=25
and you must use a while loop
Here's a function to do just that. Just call the function whenever you need.
Ex: System.out.println(parseSum("10 + 12+ 3")) → 25
public static int parseSum(String input) {
// Removes spaces
input = input.replace(" ", "");
int total = 0;
String num = "";
int letter = 0;
// Loop through each letter of input
while (letter < input.length()) {
// Checks if letter is a number
if (input.substring(letter, letter+1).matches(".*[0-9].*")) {
// Adds that character to String
num += input.charAt(letter);
} else {
// If the character is not a number, it turns the String to an integer and adds it to the total
total += Integer.valueOf(num);
num = "";
}
letter++;
}
total += Integer.valueOf(num);
return total;
}
The while loop is essentially a for loop though. Is there a specific reason why you needed it to be a while loop?
There is a lot of ways to achieve this. Here an example of code that could be improve (for example by catching an InputMismatchException if the user doesn't enter a number).
Please for the next time, post what you have tried and where you stuck on.
public static void main (String[] args) {
boolean playAgain = true;
while(playAgain) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the first number : ");
int nb1 = sc.nextInt();
System.out.println("Ok! I got it! Please enter the second number : ");
int nb2 = sc.nextInt();
System.out.println("Great! Please enter the third and last number : ");
int nb3 = sc.nextInt();
int sum = nb1+nb2+nb3;
System.out.println("result==>"+nb1+"+"+nb2+"+"+nb3+"="+sum);
boolean validResponse = false;
while(!validResponse) {
System.out.println("Do you want to continue ? y/n");
String response = sc.next();
if(response.equals("n")) {
System.out.println("Thank you! see you next time :)");
playAgain = false;
validResponse = true;
} else if(response.equals("y")) {
playAgain = true;
validResponse = true;
} else {
System.out.println("Sorry, I didn't get it!");
}
}
}
}
I am new to JAVA and have been using IDE, to cut it short whenever I try to check if bag contains a string thats the same as the given input JAVA counts it as FALSE, even if the if statements such as "is input equal to 1" and "is 1 inside the bag" pass as true. here is an excerpt from my code, I would appreciate any help and advice.
//user input
System.out.println("Please enter a string (to exit, enter 'exit'): ");
a=sc.next();
if (a.equals("1")) {System.out.println("adpkgnosıfbgojadnofabsndofgna");}
if (ValidAnswers1.contains("1")) {System.out.println("adpkgnosıfbgojadnofabsndofgna");}
//error detection. after I learn bag it will become if bag contains string s.
if (ValidAnswers1.contains(a)) {correct_input=1;} else {correct_input=0;}
while (correct_input==0)
{
System.out.println("you entered:"+ a+".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
a = sc.next();
if (ValidAnswers1.contains(a)) {correct_input=1;} else {correct_input=0;}
}
the console prints out both the keymashes and then diverts into the while loop. I have checked to make sure the while loop is correct by testing with fixed variables, but when scanner is used it seems to have an error.
I didn't understand, what you really want, i did the test and a yet is working fine. take a look at the class, maybe is some error in the variables or something
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String a;
String ValidAnswers1 = "1";
int correct_input = 0;
//user input
System.out.println("Please enter a string (to exit, enter 'exit'): ");
a = sc.next();
if (a.equals("1")) {
System.out.println("adpkgnosıfbgojadnofabsndofgna");
}
if (ValidAnswers1.contains("1")) {
System.out.println("adpkgnosıfbgojadnofabsndofgna");
}
//error detection. after I learn bag it will become if bag contains string s.
if (ValidAnswers1.contains(a)) {
correct_input=1;
} else {
correct_input=0;
}
while (correct_input==0) {
System.out.println("you entered:"+ a+".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
a = sc.next();
if (ValidAnswers1.contains(a)) {
correct_input=1;
} else {
correct_input=0;
}
}
}
Here is the output:
Please enter a string (to exit, enter 'exit'):
a
adpkgnos?fbgojadnofabsndofgna
you entered:a.
Please enter a valid string (to exit, enter 'exit')
1
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
//Create a new Object Scan in the memmory
Scanner scan = new Scanner(System.in);
String input;
String[] validAnswers = new String[]{"1","2","3","exit"};
boolean isCorrect = false;
//The method equalsIgnoreCase means that the text can be in uppercase too;
/*The number between the tags "[]" means the number in the array since arrays
starts with number "0" */
do{
System.out.println("Please enter a string (to exit, enter 'exit'): ");
input = scan.next();
if(input.equalsIgnoreCase(validAnswers[0])){
isCorrect = true;
System.out.println("Number 1");
}else if(input.equalsIgnoreCase(validAnswers[1])){
isCorrect = true;
System.out.println("Number 2");
}else if(input.equalsIgnoreCase(validAnswers[2])){
isCorrect = true;
System.out.println("Number 3");
}else if(input.equalsIgnoreCase(validAnswers[3])){
isCorrect = true;
System.out.println("EXIT!");
//You could use the method System.exit(0) to finish the program;
//If you put "1" in the exit value means that the prgram finished with some error;
//System.exit(0);
}else{
//If the Answers is different from all of the others;
System.out.println("you entered: " + input +".");
System.out.println("Please enter a valid string (to exit, enter 'exit')");
}
}while(isCorrect != true);
//I used the method do{}while because it's the only method that will exacute at least once;
}
I'm fairly new to Java. I've done some C++ so I understand a lot of the concepts. I've been working on this code that allows me to ask for input on a tip calculator. I know some of the code is inconsistent but it's because I've been trying various methods to get it to display.
I can go through the program once asking for user input. However when I loop through it again, it just displays the same input I put in prior. I'm trying to get it to show then loop through, take new input and display that. I've been teaching myself this so it's a learning experience for me, however I'm stumped and not sure where to go from here. Any help is appreciated.
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TipApp {
public static void main(String[] args) {
calculateTips();
}
public static void calculateTips () {
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
String pattern = "$##,###,###.00;"; // Pattern string for the decimal format
DecimalFormat moneyFormat = new DecimalFormat(pattern); // Decimal Money format
NumberFormat defaultFormat = NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(1);
String choice;
double theBill;
int theTip;
int thePartySize;
boolean isBillValid = true;
boolean isTipValid = true;
boolean isPartySizeValid = true;
TipCalculator tipCalculator1 = new TipCalculator();
System.out.println("*** Tip Calculator ***");
do {
System.out.print("\nEnter the bill amount: ");
while (isBillValid) {
try {
if (input.hasNextDouble()) {
theBill = input.nextDouble();
isBillValid = false;
tipCalculator1.setBillAmount(theBill);
}
} catch (InputMismatchException e) {
System.out.println(input.next() + " is not a valid number");
}
input.nextLine();
}
System.out.print("Enter your desired tip percentage (20 equals 20%): ");
while (isTipValid) {
if (input.hasNextInt()) {
theTip = input.nextInt();
isTipValid = false;
tipCalculator1.setTipPercentage(theTip);
} else {
System.out.println("Please enter a valid tip percentage.");
isTipValid = true;
}
input.nextLine();
}
System.out.print("Enter the size of your party: ");
while (isPartySizeValid) {
if (input.hasNextInt()) {
thePartySize = input.nextInt();
isPartySizeValid = false;
tipCalculator1.setPartyAmount(thePartySize);
} else {
System.out.println("Please enter a valid party size.");
isPartySizeValid = true;
}
input.nextLine();
}
System.out.println("*** Your Bill ***");
System.out.print("\nBill Amount: ");
System.out.println(moneyFormat.format(tipCalculator1.getBillAmount()));
System.out.print("Tip Percentage: ");
System.out.println(defaultFormat.format(tipCalculator1.getTipPercentage()));
System.out.print("Party Size: ");
System.out.println(tipCalculator1.getPartyAmount());
System.out.print("\nTotal Bill (with Tip): ");
System.out.print(moneyFormat.format(tipCalculator1.getTotalAmount()));
System.out.print("\nShare for Each Individual: ");
System.out.print(moneyFormat.format(tipCalculator1.getIndividualShare()));
System.out.print("\nAnother Bill? (y/n): ");
choice = scan.nextLine();
} while (choice.equalsIgnoreCase("y")) ;
System.out.println("\nGoodbye!");
}
}
public class TipCalculator {
private double billAmount;
private int tipPercentage;
private int partyAmount;
// Constructor that holds 3 arguments
public TipCalculator() {
setBillAmount(billAmount);
setTipPercentage(tipPercentage);
setPartyAmount(partyAmount);
}
public double getBillAmount() {
return billAmount;
}
public void setBillAmount(double billAmount) {
this.billAmount = billAmount;
}
public double getTipPercentage() {
return tipPercentage / 100f;
}
public void setTipPercentage(int tipPercentage) {
this.tipPercentage = tipPercentage;
}
public int getPartyAmount() {
return partyAmount;
}
public void setPartyAmount(int partyAmount) {
this.partyAmount = partyAmount;
}
public double getIndividualShare() {
return (getTotalAmount() / partyAmount);
}
public double getTotalAmount() {
return (billAmount * getTipPercentage()) + billAmount;
}
}
[1]: https://i.stack.imgur.com/5tHIs.png
First off, use only one Scanner object, you don't need more than that. Perhaps name is userInput.
The problem you are having is because you are not resetting some key variables for the next bill to be calculated, in particular those that are used in conditions for your loops.
Take the following variables:
boolean isBillValid = true;
boolean isTipValid = true;
boolean isPartySizeValid = true;
double theBill;
int theTip;
int thePartySize;
and move them to the top of your do loop (the main outer loop) and initialize the String variable choice to hold a null string (""), for example:
do {
choice = "";
boolean isBillValid = false;
boolean isTipValid = false;
boolean isPartySizeValid = false;
double theBill = 0.0d;
int theTip = 0;
int thePartySize = 0;
System.out.print("\nEnter the bill amount: ");
while (isBillValid) {
try {
//..... The rest of your code ....
This way the conditions for your loops will not already be set from the previous bill should the User enter 'y' to process another Bill.
In my opinion, every prompt which requires User input of some kind should ensure valid input and this would include the Another Bill? (y/n): prompt, for example:
while (choice.isEmpty()) {
System.out.print("\nAnother Bill? (y/n): ");
choice = userInput.nextLine();
// Is only a 'y' or a 'n' supplied (regardless of letter case)
if (!choice.matches("(?i)[yn]")) {
// No...inform User and have him her try again.
System.out.println("Invalid input - 'y' or 'n' only! Try again...");
choice = ""; // Reset the 'choice' variable to null string.
}
}
The if statement condition in the above code utilizes the String#matches() method along with a small Regular Expression (RegEx). Within the regex string, the (?i) means 'ignore letter case' and the [yn] means: matches only the 'y' or 'n' characters. So, if the supplied choice does not match either y, Y, n, or N then the condition is true.
This sort of validation should apply to all your prompts to the User so as to ensure a trouble free experience for the User, after all, typo's do happen. Take the Tip Percentage entry for example, what is to happen if the User enters -10?. This would be okay if your were applying a discount coupon or something but not so much for a tip. I think it might be best for the User to enter a value within a specific range like 0 to 100 (or whatever you like):
while (!isTipValid) {
System.out.print("Enter your desired tip percentage (0 to 100): --> ");
try {
theTip = userInput.nextInt();
// Is the tip percentage inclusively between 0 and 100?
if (theTip < 0 || theTip > 100) {
// No...
throw new java.util.InputMismatchException();
}
isTipValid = true;
tipCalculator1.setTipPercentage(theTip);
}
catch (java.util.InputMismatchException ex) {
System.out.println("Invalid tip percentage supplied (" + theTip + ")! Try again...");
}
userInput.nextLine();
}
In the above example loop code you will most likely notice a few things done differently here.
To begin with, the condition for the while loop better represents the name of the boolean variable isTipValid. The variable name is in a sense more like a question: Is the Tip Valid?. By default you have this variable initialized to true which is basically like saying "Yes, the Tip is Valid!" when in reality that hasn't been established yet. For better clarity I think this variable (and others like it) should be initialize to boolean false and then changed to boolean true only after it is definitely determined that the value supplied is indeed valid.
Another change you may have noticed is the fact that the displayed prompt string to the Console Window is placed within the while loop rather than above it. This ensures that if an invalid situation occurs and the prompt requires further input then the User will definitely know what is requested. It's a good idea that all of your prompt mechanism be contained within the while loop that pertains to it. The prompt string has also be modified to indicate to the User that a value within the range of 0 to 100 is expected.
Another change you may have noticed is the fact that the if (input.hasNextInt()) { line has been replaced with a Try/Catch mechanism. This actually provides a more definite means to ensure proper data entry since the Scanner#hasNextInt() method (and other hasNext...() methods) is better suited for tokenized input whereas a delimited series of integer numbers may be in or combined within that input. It can of course be used in this use-case but requires additional handling to accommodate all possible invalid situations.
You will also see an additional if statement that is used to check whether or not the value supplied is within the described range of 0 to 100. If it isn't then an InputMismatchException is thrown which forces the code-flow to immediately fall into the catch clause which ultimately indicates the problem to the User ans re-prompts for another value.
Doing the above similarly to your other Prompts will produce a much better outcome and you will know that the values supplied will be valid with the exception of the Bil Amount prompt:
while (!isBillValid) {
System.out.print("Enter the bill amount: --> ");
try {
theBill = userInput.nextDouble();
if (theBill < 0) {
throw new java.util.InputMismatchException();
}
isBillValid = true;
tipCalculator1.setBillAmount(theBill);
} catch (java.util.InputMismatchException e) {
System.out.println("Invalid Bill amount supplied (" + theBill + ")! Try again...");
}
userInput.nextLine();
}
This will work well for pretty much all invalid possibilities except for this simple typo: 3e4 example. This is considered a valid double value by the Scanner#nextDouble() method. The e or E within the supplied value is considered a value in Scientific E Notation and in its drawn out state is the same as a double value of 30000.0. So, instead of the intended $34 bill the 3e4 ends up being a real healthy bill of $30,000.00. To cover this situation a slightly different approach will need to be used. In the code below you will see not just how the Bill Amount prompt code is done using this different approach but also all other prompts:
public void calculateTips() {
Scanner userInput = new Scanner(System.in);
String pattern = "$##,###,###.00;"; // Pattern string for the decimal format
java.text.DecimalFormat moneyFormat = new java.text.DecimalFormat(pattern); // Decimal Money format
java.text.NumberFormat defaultFormat = java.text.NumberFormat.getPercentInstance();
defaultFormat.setMinimumFractionDigits(1);
String choice;
TipCalculator tipCalculator1 = new TipCalculator();
System.out.println("*** Tip Calculator ***");
do {
choice = "";
boolean isBillValid = false;
boolean isTipValid = false;
boolean isPartySizeValid = false;
double theBill = 0.0d;
int theTip = 0;
int thePartySize = 0;
boolean breakAll = false;
while (!isBillValid) {
System.out.print("Enter the bill amount: --> ");
String theBillStrg = userInput.nextLine().trim();
// Is 'c' or 'C' for CANCEL entered?
if (theBillStrg.equalsIgnoreCase("c")) {
// Set breakAll to true break out of this loop.
breakAll = true;
break;
}
// If the value starts with a decimal point then
// prefix it with a 0.
if (theBillStrg.startsWith(".")) {
theBillStrg = "0" + theBillStrg;
}
// If the value ends with a decimal point then
// postfix it with a 0.
else if (theBillStrg.endsWith(".")) {
theBillStrg += "0";
}
// Is the supplied value a string representation of a
// Integer or double type value?
if (theBillStrg.matches("\\d+(\\.\\d+)?")) {
// Yes it is...
// Parse the string value to a double type
theBill = Double.parseDouble(theBillStrg);
isBillValid = true;
tipCalculator1.setBillAmount(theBill);
}
else {
System.out.println("Invalid Bill amount supplied (" + theBillStrg + ")! Try again...");
}
}
while (!isTipValid && !breakAll) {
System.out.print("Enter your desired tip percentage (0 to 100): --> ");
String theTipStrg = userInput.nextLine();
// Is 'c' or 'C' for CANCEL entered?
if (theTipStrg.equalsIgnoreCase("c")) {
// Set breakAll to true break out of this loop.
breakAll = true;
break;
}
// Is a string representation of a Integer value supplied?
if (theTipStrg.matches("\\d+")) {
// Yes...Convert the string value to Integer
theTip = Integer.parseInt(theTipStrg);
// Is the tip percentage inclusively between 0 and 100?
if (theTip < 0 || theTip > 100) {
// No...
System.out.println("Out of Range tip percentage supplied (" + theTip + ")! Try again...");
continue;
}
isTipValid = true;
tipCalculator1.setTipPercentage(theTip);
}
else {
System.out.println("Invalid tip percentage supplied (" + theTipStrg + ")! Try again...");
}
}
while (!isPartySizeValid && !breakAll) {
System.out.print("Enter the size of your party: ");
String partySizeStrg = userInput.nextLine();
// Is 'c' or 'C' for CANCEL entered?
if (partySizeStrg.equalsIgnoreCase("c")) {
// Set breakAll to true break out of this loop.
breakAll = true;
break;
}
else if (partySizeStrg.matches("\\d+")) {
thePartySize = Integer.parseInt(partySizeStrg);
isPartySizeValid = true;
tipCalculator1.setPartyAmount(thePartySize);
}
else {
System.out.println("Invalid party size supplied (" + partySizeStrg + ")! Try again...");
}
}
if (!breakAll) {
System.out.println();
System.out.println("======================================");
System.out.println("*** Your Bill ***");
System.out.println();
System.out.print("Bill Amount: ");
System.out.println(moneyFormat.format(tipCalculator1.getBillAmount()));
System.out.print("Tip Percentage: ");
System.out.println(defaultFormat.format(tipCalculator1.getTipPercentage()));
System.out.print("Party Size: ");
System.out.println(tipCalculator1.getPartyAmount());
System.out.print("\nTotal Bill (with Tip): ");
System.out.println(moneyFormat.format(tipCalculator1.getTotalAmount()));
System.out.print("\nShare for Each Individual: ");
System.out.println(moneyFormat.format(tipCalculator1.getIndividualShare()));
System.out.println("======================================");
}
while (choice.isEmpty()) {
System.out.print("\nAnother Bill? (y/n): ");
choice = userInput.nextLine();
if (!choice.matches("(?i)[yn]")) {
System.out.println("Invalid input - 'y' or 'n' only! Try again...");
choice = "";
}
}
System.out.println();
} while (choice.equalsIgnoreCase("y"));
System.out.println("\nGoodbye!");
}
I am writing a program that takes user input of an integer and of a string and performs operations on the string. I have created the program and it works fine, my issue is that I am now trying to handle the error of someone entering a non-integer value for userInput, and I am not sure how to do so. I have tried working with Try Catch statements, but I keep getting error messages for the userInput variable when I do so.
What I want to do is set the boolean inputError to true when userInput is not an integer, so that my while loop repeatedly asks the user to input an integer until they do.
public class Q3 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
boolean inputError = false;
try{
System.out.print("Please enter a number between 5 and 10, inclusively: ");
String userInput1 = in.nextLine();
int userInput = Integer.parseInt(userInput1);
}
catch(InputMismatchException e)
{
inputError = true;
}
// If userInput is not between 5 and 10, set the boolean inputError to true.
if (userInput < 5 || userInput > 10)
{
inputError = true;
}
// Repeatedly ask for user input if they do not enter a number between 5 and 10.
while(inputError)
{
System.out.print("Error. Please enter a number between 5 and 10, inclusively: ");
userInput = in.nextInt();
in.nextLine();
if (userInput >= 5 || userInput <= 10)
{
inputError = false;
}
}
// Take user's input for the string.
System.out.print("Please enter a string of length 6 characters: ");
String textToChange = in.nextLine();
int length = 6;
String printArray = "";
String wordsOdd = "";
String finalConcat ="";
String transitionString="";
// Print error if text is not 6 characters long.
while(textToChange.length() != 6)
{
System.out.println("Error! Enter a string of length 6.");
textToChange = in.nextLine();
}
The problem is that the variable "userInput" is declared inside the try-catch block which means that after the end of this block will not exist. What you should do is initialize them on the start of your main method so that they can be accessed globally from any code block inside the main method
int userInput = 1; // Set default initialisation.
String userInput1 = "";
try {
NumberFormat.getInstance().parse(userInput1);
userInput = Integer.parseInt(userInput1);
}
catch(ParseException e) {
inputError = true; //not a number
}
You need all the code that checks the validity of the input inside the loop:
Scanner in = new Scanner(System.in);
boolean inputError = true;
int userInput = 0;
while (inputError) {
try {
System.out.print("Please enter a number between 5 and 10, inclusively: ");
String userInput1 = in.nextLine();
userInput = Integer.parseInt(userInput1);
inputError = (userInput < 5 || userInput > 10);
} catch (NumberFormatException e) {
inputError = true;
}
if (inputError)
System.out.println("Wrong input");
}
System.out.print("Please enter a string of length 6 characters: ");
..................................
The above loop will never finish until a valid integer is passed as userInput.
I need to user to enter an int between 1 and 301.
I have this simple loop here to check for user input.
I just want a single number from the user, and if the user enters anything other than an int between 1 and 301, I want to display the print line and prompt the users to try again until they enter a valid input.
while (!sc.hasNextInt()) {
System.out.print("Invalid Input. Please enter a valid number between 1 and 301: ");
sc.next();
}
int numToCheck = sc.nextInt();
// do stuff with numToCheck
This checks that the input is an int, but I can't seem to find a way to give the int input a bound. I tried to assign the user input to a variable and then check the conditions input < 1 or input > 301, but I get InputMismatchException if user enters a letter. How should I store the user input? (I want to store it as an int to check the conditions, but can't do that since I don't know what the user will enter).
Perhaps there is a better design to accomplish all this. Those are welcomed too.
Thanks in advance.
You're not saving the value of the of the input. So your program is waiting on the user to enter a number each time it see "sc.nextInt()" Assign the input to a variable, and then check the condition.
EDIT: okay, I'll go the extra mile for you. See if this works.
***Accounted for the case where the user might enter a character instead of a number.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
int input;
while (true){
if (sc.hasNextInt()){
input = sc.nextInt(); // Assign the next integer to a variable
if (input <= 301 && input >= 1){ // Check if integer meets condition
break; // Condition met, break out of loop
}
}else{
sc.next();
}
System.out.println("Invalid Input. Please enter a valid number between 1 and 301: ");
}
}
}
I ran this code, to see if it would show a better performance than yours.
Scanner sc = new Scanner(System.in);
boolean valid = true;
do {
if (!valid) {
System.out.print("Invalid Input. ");
}
System.out.print("Please enter a valid number between 1 and 301: ");
String input = sc.next();
try {
int value = Integer.parseInt(input);
valid = (value >= 1 && value <= 301);
} catch (NumberFormatException nfex) {
valid = false;
}
} while (!valid);
When the conversion to integer fails, the JVM hangs a little. I believe your problem has more to do with the try / catch mecanism that Scanner performs under the hood, than with design.
Assuming you want only 1 input from the user, try following simple code, which takes input from the user until user enters a valid input.
Scanner in = new Scanner(System.in);
int flag = 0,x=0;
while(flag == 0){
x = in.nextInt();
if(x<1 || x>301){
flag = 0;
System.out.println("Invalid Input.");
}
else{
flag = 1;
}
}
And if you want user to input more than 1 inputs (i.e 3 here), than set a counter that increases with every valid input of the user, as following:
Scanner in = new Scanner(System.in);
int flag = 0,x=0,count = 1;
while(flag == 0){
x = in.nextInt();
if(x<1 || x>301){
flag = 0;
System.out.println("Invalid Input.");
}
else{
//executes when input is valid
if(count == 3){
flag = 1;
}
count++;
}
}
Edit:
If you also want to check whether the input is Integer or not, than you have to add one extra condition in above code. And as you said you want only one input from user rather than 3, you have to change exit condition. Change code as following:
Scanner in = new Scanner(System.in);
int flag = 0,count = 1,x=0,flag1 = 0;
String y;
while(flag == 0){
y = in.next();
flag1 = 0;
try{
x = Integer.parseInt(y);
}
catch(NumberFormatException e){
flag1 = 1;
System.out.println("Invalid Input.");
}
if((x<1 || x>301)&&flag1 == 0){
flag = 0;
System.out.println("Invalid Input.");
}
else if(flag1 == 0){
//executes when input is valid
if(count == 1){ // put count == 3 if you want 3 inputs from user.
flag = 1;
}
count++;
}
}
Here we are taking the input as a String and than converting the String into the Integer by using Integer.parseInt(). If the String is not Integer, than it will throw the exception and we will continue the loop till the valid input is entered by the user.
Use DO WHILE for result
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
OK ?