I wrote a program that asks the person for strings of numbers between 1-6 and returns the number of rolls it took to get the string. I want to validate the input so that the person doesn't enter a number bigger than 6 or smaller than 1 and I can't seem to figure out how to do that.
int SIDES = 6;
String userString = "null";
String answer = "null";
int length = 0;
do {
do {
System.out.print("please enter a string of 6 numbers you want to be rolled");
userString = keyboard.next();
while (length != SIDES) {
System.out.println("please enter a valid string number");
userString = keyboard.next();
}
length = userString.length();
} while ( length != SIDES); // I want to add the validation to this line
dieRoll(userString);
while (length != SIDES) {
userString = keyboard.next();
try {
int userStringNumber = Integer.parseInt(userString);
if(userStringNumber<1||userStringNumber>6)
throw new IllegalArgumentException();
} catch (NumberFormatException e) {
System.out.println("Please provide a number");
}
catch (IllegalArgumentException ex){
System.out.println("Number should be between 1 and 6");
}
}
Related
I am trying to get my code to prompt an Error Message whenever the user enters a decimal number/negative number and will continue to loop until a positive number greater than 0 is implemented.
This is what I have so far;
public static void numberFunctions()
{
System.out.println("Calculating a Factorial");
Scanner myScan= new Scanner (System.in);
System.out.println("Please enter the number you'd like to use: ");
int number = myScan.nextInt();
System.out.println(number);
if(number>0)
{
int factorial = 1;
int count;
for (count = number; count >=1; count --)
{
factorial = factorial * count;
System.out.print(count +" * ");
}
System.out.println(" = " + factorial);
}
else
{
System.out.println("ERROR! Please enter a positive number");
}
}
First you can create a method for example
public static int getInteger() {
}
In that method you can ask the user to enter an integer using a try catch block inside a while loop so that way if they enter a double or a String it will catch the Exception and ask the user to try to enter an integer again.
Once you figure that out you can call that method and check if the number returned is greater than 0.
Once you create this method you can always use it to ask for integers from the user.
Add a try/catch block while taking input.
try {
int number = myScan.nextInt();
}
catch(InputMismatchException e) {
System.out.println("Enter integer numbers only");
System.out.println(scanner.next() + " was not valid input.");
}
You are doing ok with the negative number checking part. However if the user enter an invalid string or a real number, this line of code will throw exception so we need to catch that error: int number = myScan.nextInt();
It is also a good practice to always close your Scanner after using it so we will put it in the finally part.
Here is my suggested code for you:
public static void numberFunctions()
{
System.out.println("Calculating a Factorial");
Scanner myScan= new Scanner (System.in);
System.out.println("Please enter the number you'd like to use: ");
try {
int number = myScan.nextInt();
if(number>0)
{
int factorial = 1;
int count;
for (count = number; count >=1; count --)
{
factorial = factorial * count;
System.out.print(count);
if (count != 1) {
System.out.print(" * ");
}
}
System.out.println(" = " + factorial);
}else {
System.out.println("ERROR! Please enter a positive number");
}
}catch(InputMismatchException ex) {
System.out.println("ERROR! Please enter a positive number");
}finally {
myScan.close();
}
}
How to check in this code that the entered input is integer or not if not then ignore the non-integer values and display the rest numbers.
I have done the full coding but for checking the input is integer or not and then printing the value. How should I do it?
import java.util.Scanner;
class ques2
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int i,j;
System.out.print("how many number you want to enter= ");
i=sc.nextInt();
int input[]=new int[i];
System.out.println("Numbers should be great then 3");
for(j=0;j<i;j++)
{
input[j]=sc.nextInt();
}
System.out.println("Number entered are:");
for(j=0;j < i;j++)
{
System.out.println(input[j]);
}
System.out.println("Odd numbers are:");
for(j=0;j < i;j++)
{
if(input[j] % 2 != 0)
{
System.out.println(input[j]);
}
}
System.out.println("Palindrome numbers are:");
for(j=0;j < i;j++)
{
int rev=0,n,num;
n=input[j];
while(input[j] > 0)
{
num=input[j] % 10;
rev=num+(rev*10);
input[j]=input[j]/10;
}
if(n == rev)
{
System.out.println(n);
}
}
}
}
You could take a helper function:
public static boolean checkMe(String s) {
boolean amIValid = false;
try {
Integer.parseInt(s);
// s is a valid integer!
amIValid = true;
} catch (NumberFormatException e) {
//not an integer but you could continue with the rest numbers
}
return invalid;
}
You can check it by comparing the ASCII value whether it lies between 91 to 100.
If yes then it will be an Integer.
You can try to use String in lieu of int. Then, you can go ahead with again int using Integer.parseInt(x) because it's already been verified as being valid integer after do-while
String num;
String regex = "[0-9]+"; // to check the string only is made up of digits
Scanner input = new Scanner(System.in);
do {
System.out.println("Please input an integer");
num = input.next();
} while (!num.matches(regex));
int validNumber = Integer.parseInt(num);
/* .
.
. *\
You're already using sc.nextIn() which internally perform a regex-check as in #snr's post and a Integer.parseInt as in charly1212's post.
The only thing you should add is wrap it in a
try {
int i = sc.nextInt();
} catch(InputMismatchException e) {
//skip or repeat?
}
To deal with all cases, where the input is not an int (which includes values > Integer.MAX_VALUE and < Integer.MIN_VALUE)
The solution could look like this method, encapsulating all the input reading
private static int[] readNumbers() {
Scanner sc = new Scanner(System.in);
int i = -1;
while(i < 0){
try {
System.out.print("how many number you want to enter? ");
i=sc.nextInt();
} catch (InputMismatchException e){
System.out.println(sc.next() + " is not a number, try again");
}
}
List<Integer> numbers = new ArrayList<>();
System.out.println("Numbers should be greater then 3");
for(int j = 0; j < i; j++){
try {
numbers.add(sc.nextInt());
} catch (InputMismatchException e){
System.out.println("Skipping input " + sc.next());
}
}
return numbers.stream().mapToInt(Integer::intValue).toArray();
}
...
int input[] = readNumbers();
Please not, that the exception blocks invoke sc.next() to read the current line (which is not integer) and proceed with the next line (the new input), otherwise the scanner would not proceed its position.
This question already has answers here:
Validating input using java.util.Scanner [duplicate]
(6 answers)
Closed 6 years ago.
public static void main(String[] args) {
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your name: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
int n = reader.nextInt();
System.out.println("You chose: " + n);
}
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter your email: ");
String n = reader.nextLine();
System.out.println("You chose: " + n);
}
}
If a user places anything else under Enter your age other than a number, how do I make it say that the input is not correct and ask again?
You can get the line provided by the user, then parse it using Integer.parseInt(String) in a do/while loop as next:
Scanner reader = new Scanner(System.in);
Integer i = null;
// Loop as long as i is null
do {
System.out.println("Enter your age: ");
// Get the input from the user
String n = reader.nextLine();
try {
// Parse the input if it is successful, it will set a non null value to i
i = Integer.parseInt(n);
} catch (NumberFormatException e) {
// The input value was not an integer so i remains null
System.out.println("That's not a number!");
}
} while (i == null);
System.out.println("You chose: " + i);
A better approach that avoids catching an Exception based on https://stackoverflow.com/a/3059367/1997376.
Scanner reader = new Scanner(System.in);
System.out.println("Enter your age: ");
// Iterate as long as the provided token is not a number
while (!reader.hasNextInt()) {
System.out.println("That's not a number!");
reader.next();
System.out.println("Enter your age: ");
}
// Here we know that the token is a number so we can read it without
// taking the risk to get a InputMismatchException
int i = reader.nextInt();
System.out.println("You chose: " + i);
No need to declare a variable scanner so often, simply once
care with nextLine(); for strings; presents problems with blanks, advise a .next();
use do-while
do
{
//input
}
while(condition);//if it is true the condition returns to do otherwise leaves the cycle
use blocks try{ .. }catch(Exception){..}
to catch exceptions mismatch-input-type exception is when the input is not what I expected in the example enter a letter when a number expected
Scanner reader = new Scanner(System.in);
int n=0;
do
{
System.out.println("Enter your age: ");
try {
n = reader.nextInt();
}
catch (InputMismatchException e) {
System.out.print("ERROR NOT NUMBER");
}
}
while(n<0 && n>100);//in this case if the entered value is less than 0 or greater than 100 returns to do
System.out.println("You chose: " + n);
I have tried similar codes in this site but nothing works for me. So I want the program to keep asking the user to input an integer if its not integer. If the credit card is integer then go to expiration date and if it is valid then print invoice. I tried if and while loop, also try and catch but I guess my logic is broken. Any help will be appreciated.
Scanner s = new Scanner(System.in);
System.out.println("Type 'quit' to exit payment");
System.out.println("Enter name: ");
String name = s.next();
s.nextLine();
if (name.equals("quit"))
{
return;
}
System.out.println("Enter address: ");
String address = s.nextLine();
if (address.equals("quit"))
{
return;
}
System.out.println("Type '000' to exit payment");
System.out.println("Enter card number: ");
#override
int cardNo = s.nextInt();
if (cardNo == 000)
{
return;
}
System.out.println("Enter card expiration date: (DDMMYY)");
int expirationDate = s.nextInt();
if (expirationDate == 000)
{
return;
}
//if input is ok then printing invoice
}
Try the following, I'll also note a few things afterwards about quitting your application
Scanner s = new Scanner(System.in);
String name = "", address = "";
int cardNo = 0, expirationDate = 0;
while(name == "" || address == "" || cardNo == 0 || expirationDate == 0)
{
System.out.println("Type 'quit' to exit payment");
//Get Name
System.out.print("Enter name: ");
name = s.nextLine();
if (name.equals("quit")){return;}
//Get address
System.out.print("Enter address: ");
address = s.nextLine();
if (address.equals("quit")){return;}
System.out.println("Type '-1' to exit payment");
//Get card number continually until an integer is entered
do {
System.out.print("Enter card number: ");
try {
cardNo = Integer.parseInt(s.nextLine());
break;
} catch (Exception e) {
continue;
}
} while (true);
if (cardNo == -1) {return;}
//Get card expiration date continually until an integer is entered
do {
System.out.println("Enter card expiration date: (DDMMYY)");
try {
expirationDate = Integer.parseInt(s.nextLine());
break;
} catch (Exception e) {
continue;
}
} while (true);
if (expirationDate == -1){return;}
}
You might have noticed I changed what to enter when quitting at the card number and expiration date part of the program from 000 to -1. This is because 000 converted to an int will have the value of 0, so the user would never be able to exit your application.
Remember .nextLine() gets the next element each time you call the method . so it is better to assign it to the variable before processing .
From docs ,
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the
line to skip if no line separators are present.
What I'm trying to accomplish is the following...
Asks user for number and check to see if number provided by user input is a 7 digit integer.
If it's a string, throw InputMismatchException and ask again for the number. Is there an easy way to accomplish this other than using regex and provided that the number is in the form 1234567? The other problem is if I input a value such as 12345678, it gets rounded due to int, so how do avoid this.
int number = 0;
try {
number = scan.nextInt(); // Phone Number is 7 digits long - excludes area code
} catch(InputMismatchException e) {
System.out.println("Invalid Input.");
number = validateNumber(number, scan);
} finally {
scan.nextLine(); // consumes "\n" character in buffer
}
// Method checks to see if the phone number provided is 7 digits long
// Precondition: the number provided is a positive integer
// Postcondition: returns a 7 digit positive integer
public static int validateNumber(int phoneNumber, Scanner scan) {
int number = phoneNumber;
// edited while((String.valueOf(number)).length() != 7) to account for only positive values
// Continue to ask for 7 digit number until a positive 7 digit number is provided
while(number < 1000000 || number > 9999999) {
try {
System.out.print("Number must be 7 digits long. Please provide the number again: ");
number = scan.nextInt(); // reads next integer provided
} catch(InputMismatchException e) { // outputs error message if value provided is not an integer
System.out.println("Incorrect input type.");
} finally {
scan.nextLine(); // consumes "\n" character in buffer
}
}
return number;
}
A valid telephone number is not necessarily an integer (Containing a + sign for country codes for example). So use a String instead.
Simple example with basic regex (7 digits, not validating country codes etc.):
public class Test {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String telephoneNumber = stdin.nextLine();
System.out.println(Pattern.matches("[0-9]{7}", telephoneNumber));
}
}
Here is working example along the lines of your original idea.
public int GetvalidNumber(Scanner scan) {
int number = 0;
while(true) {
try {
System.out.print("Enter a 7 digit number: ");
number = scan.nextInt();
if (number > 0 && Integer.toString(number).length() == 7)
break;
} catch(InputMismatchException e) {
scan.nextLine();
System.out.println("Invalid input: Use digits 0 to 9 only");
continue;
}
System.out.println("Invalid input: Not 7 digits long");
}
return number;
}