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.
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 having a problem trying to understand how I can loop through a keyboard input line of text the user will give ex:
Anika 14 Dan 16
I want to read each token and assign to String name, Int, age, String name, int age. in that order.
This is easy however, if the user enters
Anika Anika Anika Anika 13 13 13 Dan 16
Then I want the program to:
Anika,
Integer needed got String,
Integer needed got String,
Integer needed got String,
13,
String needed got Integer,
String needed got Integer,
Dan,
16
So first one will always be a string which is a word EDIT: "word", second an int and thrid string which is a "word" and fourth int.
However, I can not simulate this.
Scanner scan = new Scanner(System.in);
String name = null;
int age = 0;
String name2= null;
int age2= 0;
if(scan.hasNext() == true)
name = scan.next();
age = scan.nextInt();
name2= scan.next();
age2= scan.nextInt();
I know if I do the top I get the right order, but it is the extra inputs that I would like to ignore but write a statement expression why it's wrong and then continue to search for the next int, or third string and so on.
boolean isstring = false;
boolean isnumber = false;
do {
if (scan.hasNext())
{
name = scan.next();
isstring = true;
}
else {
System.out.println("Need String got Integer");
isstring = false;
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt())
{
age = scan.nextInt();
isnumber=true;
}
else {
System.out.println("Need Integer got String");
isnumber=false;
scan.nextInt();
}
} while (!isnumber);
do {
if (scan.hasNext())
{
name2 = scan.next();
isstring = true;
}
else {
System.out.println("Need String got Integer");
isstring = false;
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt())
{
age2 = scan.nextInt();
isnumber = true;
}
else {
System.out.println("Need Integer got String");
isnumber=false;
scan.nextInt();
}
} while (!isnumber);
}
I tried to use do while with ifs and It didnt work. My logic is wrong somewhere, and I think it might be the has.next() method.
Any help will be appreciated!!
If the input is a word while waiting for an Integer, it will throw InputMismatchException. nextInt() first read the value as a String an then parse it as a Integer, so if you ignore the value using nextInt, if the value is a word, it will trow the aforementioned Exception.
Using the same logic of your program
The changes should be:
Ignore the input with scan.next()
Check if a String can be or not an Integer (using scan.hasNextInt()), not if is a String, because any Integer can be expressed as a String.
boolean isstring = false;
boolean isnumber = false;
do {
if (!scan.hasNextInt()) {
isstring = true;
name = scan.next();
} else {
isstring = false;
System.out.println("Need String got Integer");
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt()) {
isnumber = true;
age = scan.nextInt();
} else {
isnumber = false;
System.out.println("Need Integer got String");
scan.next();
}
} while (!isnumber);
do {
if (!scan.hasNextInt()) {
isstring = true;
name2 = scan.next();
} else {
isstring = false;
System.out.println("Need String got Integer");
scan.next();
}
} while (!isstring);
do {
if (scan.hasNextInt()) {
isnumber = true;
age2 = scan.nextInt();
} else {
isnumber = false;
System.out.println("Need Integer got String");
scan.next();
}
} while (!isnumber);
Using try/catch and one loop
A naive solution using try/catch can be the following
public static void main (String[]args)
{
String name = null;
String name2 = null;
Integer age = null;
Integer age2 = null;
Scanner scan = new Scanner(System.in);
while (scan.hasNext())
{
try
{
if (name == null)
{
System.out.println("Please provide name: ");
name = getNameOrFail(scan);
System.out.println("Name set: " + name);
}
if (age == null)
{
System.out.println("Please provide age: ");
age = getAgeOrFail(scan);
System.out.println("Age set: " + age);
}
if (name2 == null)
{
System.out.println("Please provide name2: ");
name2 = getNameOrFail(scan);
System.out.println("Name2 set: " + name2);
}
if (age2 == null)
{
System.out.println ("Please provide age2: ");
age2 = getAgeOrFail (scan);
System.out.println ("Age2 set: " + age2);
}
}
catch (Exception e)
{
System.out.println(e.getMessage ()); // Print the message put int Exception(message) constructor
scan.nextLine(); // Flush the Scanner cache
}
}
}
public static String getNameOrFail(Scanner scan) throws Exception
{
if (scan.hasNextInt())
throw new Exception("Need String got Integer");
return scan.next();
}
public static Integer getAgeOrFail(Scanner scan) throws Exception
{
if (!scan.hasNextInt())
throw new Exception("Need Integer got String");
return scan.nextInt();
}
Pay attention to the scan.newLine() in the catch clause, this is needed because the Scanner use a cache with the last input, so if is not re-read you enter in a infinite loop condition.
Good luck!
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.
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 ?
package test5555;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class Test5555 {
private static int[] randomInteger;
public static void main(String[] args) {
boolean validInput = false;
randomInteger = new int[100];
Random rand = new Random();
for (int i = 0; i < randomInteger.length; i++)
randomInteger[i] = rand.nextInt();
int indexPosition = 0;
Scanner input = new Scanner(System.in); {
System.out.println("Please enter an integer for the array index position: ");
while(!validInput)
{
try
{
indexPosition = input.nextInt();
validInput = true;
System.out.println(randomInteger[indexPosition]);
} catch ( InputMismatchException | IndexOutOfBoundsException ex) {
System.out.print("Please enter a valid integer between 0 and 100 or type quit to exit: ");
String s = input.next();
if(s.equals("quit")){
System.exit(0);
System.out.println(randomInteger[indexPosition]);
}
}
}
}
}
}
The code runs perfectly except for two minor hiccups that I cannot solve. When you run it you get Please enter an integer for the array index position:If you type a number above 100 or a string such as bob then you get Please enter a valid integer between 0 and 100 or type quit to exit:which is perfect. But if you type quit then you get Please enter a valid integer between 0 and 100 or type quit to exit: BUILD SUCCESSFUL (total time: 2 minutes 2 seconds) so it quits it but it repeats the exception statement which I do not want.
When you type a number above 100 and receive the Please enter a valid integer between 0 and 100 or type quit to exit: if you then type a correct integer the program will just turn off and it will say BUILD SUCCESSFUL instead of retrieving the number for you from the array
Replace your while loop code with below,
String s = null;
while(!validInput)
{
try
{
if(s != null){
indexPosition = Integer.parseInt(s);
}
else{
indexPosition = input.nextInt();
}
System.out.println(randomInteger[indexPosition]);
validInput = true;
} catch ( InputMismatchException | NumberFormatException | IndexOutOfBoundsException ex ) {
System.out.println("Please enter a valid integer between 0 and 100 or type quit to exit: ");
input.nextLine();
s = input.next();
if(s.equals("quit")){
System.exit(0);
}
}
}
Please read this to get more idea on Scanner.
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
In your case the problem is (As per doc)
When a scanner throws an InputMismatchException, the scanner will not
pass the token that caused the exception, so that it may be retrieved
or skipped via some other method.
The behavior you describe in point 1 us not correct. If you type in a number and then quit it works "as expected"
If you type in a string such as "bob" your nextInt() fails with an InputMissmatchException which means your "input.next()" call in the catch clause will read "bob" and see it's not equal to "quit" and just go back to the loop and block and wait for an "int".
In point 2. You type an int and you get an exception...but you've set validInput to true already so you'll exit the loop. You need to set validInput after you print.
If I got your question correctly, I would implement little differently. Please check if it fulfills your requirement.
import java.util.Random;
import java.util.Scanner;
public class Test5555 {
private static int[] randomInteger;
public static void main(String[] args) {
randomInteger = new int[100];
Random rand = new Random();
int indexPosition;
for (int i = 0; i < randomInteger.length; i++)
randomInteger[i] = rand.nextInt();
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer for the array index position: ");
while(true) {
String strIndex = input.next();
if(strIndex.equals("quit")) break;
indexPosition = getIntVal(strIndex);
if(indexPosition < 0 || indexPosition >= randomInteger.length) {
System.out.print("Please enter a valid integer between 0 and "
+ randomInteger.length + " or type quit to exit: ");
continue;
}
System.out.println(randomInteger[indexPosition]);
break;
}
input.close();
}
protected static int getIntVal(String inputStr) {
int result = -1;
try {
result = Integer.parseInt(inputStr);
} catch(NumberFormatException e) {}
return result;
}
}
This part of your code is wrong
try
{
indexPosition = input.nextInt();
validInput = true;
System.out.println(randomInteger[indexPosition]);
} catch ( InputMismatchException | IndexOutOfBoundsException ex) {
You are saying that your indexPosition is right before to check it, the line
validInput = true;
Should be later of check if the array have that position.
Right code:
...
indexPosition = input.nextInt();
System.out.println(randomInteger[indexPosition]);
validInput = true;
....