How to limit the user to enter 4 digit pin in java - java

I want to take input of pin from the user and I want to limit the user to take 4 digit pin. I tried with [But when I enter 0001 it's not working it again ask to enter 4 digit pin then please solve it
void pin1()
{
//int pin;
for(int i=1;i<=1000;i++)
{
try
{
pin=obj.nextInt();
if(pin<=9999 && pin>=1000)
{
}
else
{
System.out.println("Pin must be four digit");
pin1();
}
break;
}
catch(InputMismatchException e)
{
obj.next();
System.out.println("Error use numbers not alphabets or characters");
}
}
}

You have chosen the wrong type for a pin. As int values, 0001 and 1 are the same values, but the latter is an invalid pin, while the former is valid.
You should use a String to store the pin. This means you should call nextLine instead of nextInt:
String pin = obj.nextLine();
To check if this pin contains 4 digits, we can use the regex \d{4}.
Matcher m = Pattern.compile("\\d{4}").matcher(pin);
if (m.matches()) {
System.out.println("You have entered a 4-digit pin");
} else {
System.out.println("You have not entered a 4-digit pin");
}
Alternatively, you can check with a for loop:
if (pin.length() != 4) {
System.out.println("You have not entered a 4-digit pin");
} else {
boolean allDigits = true;
for (int i = 0 ; i < 4 ; i++) {
if (!Character.isDigit(pin.charAt(i))) {
allDigits = false;
break;
}
}
if (allDigits) {
// pin is valid
} else {
System.out.println("Error use numbers not alphabets or characters");
}
}

Try this
do {
System.out.print("Please enter a 4 digit pin:");
input = reader.nextLine();
if(input.length()==4){
//allow
}
}while( input.length()!=4);

The problem with your code is
`if(pin<=9999 && pin>=1000)`
allows numbers between 1000 and 9999 but 0001 or 0300 is still a valid 4 digit number
The code allows only numeric and does not allow alpha numeric
import java.util.Scanner;
public class Post7 {
public static void main(String[] args) {
String regex = "\\d+";
Scanner sc = new Scanner(System.in);
System.out.println("please input a valid 4 digit pin");
while(true) {
String ln = sc.nextLine();
if(ln.length() == 4 && ln.matches(regex)) {
System.out.println("valid input "+ln);
break;
}else {
System.out.println("please input a valid 4 digit pin");
}
}
sc.close();
}
}

You are reading 0001 as integer which becomes 1 which does not satisfies the condition pin>=1000. One thing you can do is first check the length of the string and if it is not 4 then return an error. Then if it is correct trying to convert to an integer: if there is an error maybe the user did not inserted 4 digits.

Try this.
public static void main(String[] args) {
Scanner s = new Scanner (System.in);
int pin;
int attempt = 0;
while(attempt < 3) {
System.out.print("Enter PIN: ");
pin = s.nextInt();
System.out.println("");
s.nextLine(); //spacing for 2nd and 3rd attempts
if(pin >= 1000 && pin <= 9999) break;
else System.out.println("Please try again.");
System.out.println("");
attempt ++;
}
if(attempt < 3) System.out.println("You have successfully logged in!");
else System.out.println("Your card has been locked.");
}

Related

how to allow integer only AND not allowing more than 9 digits

System.out.println("Enter your phone number: ");
while(in.hasNextLong()) {
long phone = in.nextLong();
if(in.hasNextLong()) {
if(phone < 1000000000) {
System.out.println("Phone number: "+phone);
}
} else if(!in.hasNextInt()) {
System.out.println("Please enter a valid phone number: ");
} else if (phone < 1000000000) {
System.out.println("Please enter a valid phone number: ");
}
tried another way
boolean valid;
long phone;
do {
System.out.println("Enter your phone number: ");
if(!in.hasNextLong()) {
phone =in.nextLong();
if(phone > 1000000000) {
System.out.println("Please enter a valid phone number");
in.nextLong();
valid=false;
}
}
}while(valid=false);
System.out.println("Phone: " + phone);
as you can see it doesnt work at all especially if you input a non integer and it ask for input twice im sorry its a mess
edit: ok so is there a way without using regex? my lecturer hasnt taught it yet so im not sure im allowed to use regex
you need to use regex. take a look to
https://www.w3schools.com/java/java_regex.asp
and try something along the lines...
...
final boolean isValid = inputValue.match(^[0-9]{1,9}?) // 1 to 9 digits
if (isValid) {
...
}
...
I would recommend doing it this way:
System.out.println("Enter your phone number: ");
int phone;
for (;;) { // forever loop
String line = in.nextLine();
if (line.matches("[0-9]{1,9}")) {
phone = Integer.parseInt(line);
break;
}
System.out.println("Please enter a valid phone number: ");
}
System.out.println("Phone number: "+phone);
That's my approach without using regex
System.out.println("Enter your phone number: ");
int phone;
int index = 0;
while(true) {
String line = in.nextLine();
if (valid(line)){
phone = Integer.parseInt(line);
break;
}
System.out.println("Please enter a valid phone number: ");
}
System.out.println("Phone number: " + phone);
And the valid() method
boolean valid(String line){
if(line.length() > 9) return false;
for(int i = 0; i < line.length(); i++){
boolean isValid = false;
for(int asciiCode = 48; asciiCode <= 57 && !isValid; asciiCode++){
//48 is the numerical representation of the character 0
// ...
//57 is the numerical representation of the character 9
//see ASCII table
if((int)line.charAt(i) == asciiCode){
isValid = true;
}
}
if(!isValid) return false;
}
return true;
}

Q : Not understanding loop process? or possible if statements?

I am working on a project that involves creating a rental car calculator.
What I am trying to do is make it to where when asked: "What vehicle would you like to rent??". If a number that is not between 1-3 is entered when the user is prompted this, then I want the program to loop back to the point of being asked vehicle type again.
Similarly, when prompted for 'Please enter the number of days rented. (Example; 3) : ' I want to only allow the user to input whole positive numbers. for instance, not allowing input of 3.1, 2.35, 0.35 -2 and, etc...
here is what I have written and my attempt at these questions :
package inter;
import java.util.Scanner;
public class Inter {
public static void main(String []args){
int count=0;
int days;
double DailyFee=0, NontaxTotal, CarType, Total,FullTotal=0;
Scanner in=new Scanner(System.in);
System.out.println("If there are any customer press 1 else press 0");
int cus=in.nextInt();
while(cus!=0){
count++;
System.out.print("What vehical would you like to rent?\n");
System.out.println("Enter 1 for an economy car\n");
System.out.println("Enter 2 for a sedan car\n");
System.out.println("Enter 3 for an SUV");
CarType = in.nextInt();
if (CarType == 1) {
DailyFee=31.76;
}
else if(CarType == 2) {
DailyFee=40.32;
}
else if(CarType == 3) {
DailyFee=47.56;
}
else if(CarType <= 0) {
System.out.println("input is not a positive Integer ");
System.out.println("Please enter a positive integer value: ");
cus = 0; }
else if(CarType > 4) {
System.out.println("input is not a positive Integer ");
System.out.println("Please enter a positive integer value: ");
cus = 0; }
System.out.print("Please enter the number of days rented. (Example; 3) : ");
days = Integer.valueOf(in.nextLine());
double x=days;
NontaxTotal = (DailyFee * x);
Total = (NontaxTotal * 1.06);
FullTotal+=Total;
System.out.printf("The total amount due is $ %.2f \n",Total);
System.out.println("If there are any customer press 1 else press 0");
cus=in.nextInt();
}
System.out.println("Count of customers : "+count);
System.out.printf("Total of the Day : $ %.2f",FullTotal);
}
}
Let me help you with this,
I made this code for you, i tried it and it worked
this will check if both answers were whole numbers (integers) and more than zero and will also check if the answer was numeric in the first place so that if the user answered with letters he will be prompted to try again
This is my suggestion:
basically i used the try-catch block with InputMismatchException to detect if the answer was not an integer (whole number ) or was not numeric at all, every time a mistake is detected i flip a boolean to false and keep looping as long as this boolean is false (i flip the boolean back to true before checking otherwise once the user gives a wrong answer he will always be prompted to answer even if he gave a correct answer after)
int vehicleType;
int numberOfDays;
double dailyFee;
boolean validAnswer1 = false;
boolean validAnswer2 = false;
Scanner scan = new Scanner(System.in);
while (validAnswer1 == false) {
validAnswer1 = true;
System.out.println("Choose Vehicle Type");
try {
vehicleType = scan.nextInt();
if (vehicleType <= 0) {
System.out.println("Number must be more than zero");
validAnswer1 = false;
} else if (vehicleType >= 4) {
System.out.println("Number should be from 1 to 3");
validAnswer1 = false;
} else {
if (vehicleType == 1) {
dailyFee=31.76;
} else if(vehicleType == 2) {
dailyFee=40.32;
}else if(vehicleType == 3) {
dailyFee=47.56;
}
while (validAnswer2 == false) {
validAnswer2 = true;
try {
System.out.println("Enter number of days rented ?");
numberOfDays = scan.nextInt();
if (numberOfDays <= 0) {
System.out.println("Number of days must be more than zero");
validAnswer2 = false;
} else {
// calculate your rent total here
}
} catch(InputMismatchException ex) {
System.out.println("Answer must be an Integer");
validAnswer2 = false;
scan.next();
}
}
}
} catch (InputMismatchException ex) {
validAnswer1 = false;
System.out.println("Answer must be an Integer");
scan.next();
}
}
Hope this was useful, do let me know if you still need help

Two checks in while loop with Scanner - java

im trying to do two checks with a while loop:
1) To show "error" if the user inputs something other than an int
2) Once the user entered an int, if it is one digit, show "two digits only" and keep the loop on until a two digit int has been entered (so an IF should be used as well)
Currently I only have the first part done:
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number");
while (!scan.hasNextInt()) {
System.out.println("error");
scan.next();
}
However, if possible, I would like to have both checks in one while loop.
And that's where I'm stuck...
Since you already have two answers. This seems a cleaner way to do it.
Scanner scan = new Scanner(System.in);
String number = null;
do {
//this if statement will only run after the first run.
//no real need for this if statement though.
if (number != null) {
System.out.println("Must be 2 digits");
}
System.out.print("Enter a 2 digit number: ");
number = scan.nextLine();
//to allow for "00", "01".
} while (!number.matches("[0-9]{2}"));
System.out.println("You entered " + number);
As said above you should always take the input in as string and then try
and parse it for an int
package stackManca;
import java.util.Scanner;
public class KarmaKing {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = null;
int inputNumber = 0;
while (scan.hasNextLine()) {
input = scan.next();
try {
inputNumber = Integer.parseInt(input);
} catch (Exception e) {
System.out.println("Please enter a number");
continue;
}
if (input.length() != 2) {
System.out.println("Please Enter a 2 digit number");
} else {
System.out.println("You entered: " + input);
}
}
}
}
First take the input as a String. If it is convertible to Int then you do your checks, else say 2 digit numbers are acceptable. If it is not convertible to a number throw an error. All this can be done in one while loop. And you would like to have a "Do you want to continue? " kind of a prompt and check if the answer is "yes" / "No." Break from the while loop accordingly.
To have it as one loop, it's a bit messier than two loops
int i = 0;
while(true)
{
if(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
continue;
}
i = scan.nextInt();
if(i < 10 || >= 100)
{
System.out.println("two digits only");
continue;
}
break;
}
//do stuff with your two digit number, i
vs with two loops
int i = 0;
boolean firstRun = true;
while(i < 10 || i >= 100)
{
if(firstRun)
firstRun = false;
else
System.out.println("two digits only");
while(!scan.hasNextInt())
{
System.out.println("error");
scan.next();
}
i = scan.nextInt();
}
//do stuff with your two digit number, i

if a user inputs a letter instead of a number tell them it's not a number

I'm making a guessing game, all the code works fine except for that I want them to make a number to guess between, I can't seem to figure out how to make it so that if the user inputs a letter like "d" instead of a number like "15" it will tell them they can't do that.
Code:
import java.util.Scanner;
import java.util.Random;
public class GuessingGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Random rand = new Random();
while (true) {
System.out.print("Pick a number: ");
int number = input.nextInt();
if (number != int) {
System.out.println("That's not a number");
} else if (number == int) {
int random = rand.nextInt(number);
break;
}
}
System.out.println("You have 5 attempts to guess the number or else you fail. Goodluck!");
System.out.println("");
System.out.println("Type 'begin' to Begin!");
System.out.print("");
String start = input.next();
if (start.equals("begin")) {
System.out.print('\f');
for(int i=1; i<6; i++) {
System.out.print("Enter a number between 1-" + number + ": ");
int number = input.nextInt();
if (number > random) {
System.out.println("Too Big");
System.out.println("");
} else if (number < random) {
System.out.println("Too Small");
System.out.println("");
} else if (number == random) {
System.out.print('\f');
System.out.println("Correct!");
break;
}
if (i == 5) {
System.out.print('\f');
System.out.println("You have failed");
System.out.println("Number Was: " + random);
}
}
} else if (start != "begin") {
System.out.print('\f');
System.out.println("Incorrect Command");
System.out.println("Please Exit Console And Retry");
}
}
}
use try catch
for example
try{
int a=sc.nextInt();
}catch(Exception e){
System.out.println("not an integer");
}
You could use nextLine() instead of nextInt() and check the out coming String if it matches() the regular expression [1-9][0-9]* and then parse the line with Integer.valueOf(str).
Like:
String str=input.nextLine();
int i=0;
if(str.matches("[1-9][0-9]*"){
i=Integer.valueOf(str);
} else {
System.out.println("This is not allowed!");
}
I hope it helps.
Do something like this:
Scanner scan = new Scanner(System.in);
while(!scan.hasNextInt()) { //repeat until a number is entered.
scan.next();
System.out.println("Enter number"); //Tell it's not a number.
}
int input = scan.nextInt(); //Get your number here

How to check if user input is String, double or long in Java

I'm a beginner in java. I want to check first if the user input is String or Double or int. If it's String, double or a minus number, the user should be prompted to enter a valid int number again. Only when the user entered a valid number should then the program jump to try. I've been thinking for hours and I come up with nothing useful.Please help, thank you!
import java.util.InputMismatchException;
import java.util.Scanner;
public class Fizz {
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
try {
Integer i = scan.nextInt();
if (i % 3 == 0 && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i + "は3と5の倍数ではありません。");
}
} catch (InputMismatchException e) {
System.out.println("");
} finally {
scan.close();
}
}
One simple fix is to read the entire line / user input as a String.
Something like this should work. (Untested code) :
String s=null;
boolean validInput=false;
do{
s= scannerInstance.nextLine();
if(s.matches("\\d+")){// checks if input only contains digits
validInput=true;
}
else{
// invalid input
}
}while(!validInput);
You can also use Integer.parseInt and then check that integer for non negativity. You can catch NumberFormatException if the input is string or a double.
Scanner scan = new Scanner(System.in);
try {
String s = scan.nextLine();
int x = Integer.parseInt(s);
}
catch(NumberFormatException ex)
{
}
Try this one. I used some conditions to indicate the input.
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
int charCount = input.length();
boolean flag = false;
for(int x=0; x<charCount; x++){
for(int y=0; y<10; y++){
if(input.charAt(x)==Integer.toString(y))
flag = true;
else{
flag = false;
break;
}
}
}
if(flag){
if(scan.hasNextDouble())
System.out.println("Input is Double");
else
System.out.println("Input is Integer");
}
else
System.out.println("Invalid Input. Please Input a number");
Try this. It will prompt for input until an int greater than 0 is entered:
System.out.println("Please enter a number");
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNext()) {
int number;
if (scan.hasNextInt()) {
number = scan.nextInt();
} else {
System.out.println("Please enter a valid number");
scan.next();
continue;
}
if (number < 0) {
System.out.println("Please enter a number > 0");
continue;
}
//At this stage, the number is an int >= 0
System.out.println("User entered: " + number);
break;
}
}
boolean valid = false;
double n = 0;
String userInput = "";
Scanner input = new Scanner(System.in);
while(!valid){
System.out.println("Enter the number: ");
userInput = input.nextLine();
try{
n = Double.parseDouble(userInput);
valid = true;
}
catch (NumberFormatException ex){
System.out.println("Enter the valid number.");
}
}

Categories