I'm trying to use try and catch exceptions in case the user does not enter strings for username and integers for the pin code. but my code it's not working
this is my code:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner myuser = new Scanner(System.in);
System.out.println("Enter your username: ");
try {
String username = myuser.nextLine();
System.out.println("Your username is: " + username);
}
catch( Exception e) {
System.out.println("Incorrect username! ");
}
System.out.println("Enter your pin code: ");
int pin = myuser.nextInt();
System.out.println("Your pin code is: " + pin);
}
}
I tried to enter integers at the username to see if my try catch code works but the code doesn't recognize it as a problem.
Enter your username:
234
Your username is: 234
Enter your pin code:
As I understand it, you want to check if your inputs are valid.
For username, nextLine() reads the given input as String, therefore, you can enter anything and it will be read as a string. Entering 123 as an input will be read as "123" and it won't throw any exceptions. If you want to check if the input string is alphabetic, i.e., contains only letters, you can refer to Check if String contains only letters
For pin code, you can check it with a try/catch block like this:
System.out.println("Enter your pin code: ");
try {
int pin = myuser.nextInt();
System.out.println("Your pin code is: " + pin);
} catch(InputMismatchException e) {
System.out.println("Incorrect pin!");
}
It will check if the given pin code is a Java Integer, please note that given input can be a negative integer, and you should check it if you need to.
Unfortunately the command line and Scanner has no validation; has no Exceptions.
String username = "";
do {
System.out.println("Enter your username:");
username = myuser.nextLine();
} while (username.isEmpty());
int pin = -1;
do {
System.out.println("Enter your pin code: ");
if (myuser.hasNextInt()) {
pin = myuser.nextInt();
} else if (myuser.hasNext()) {
myuser.next();
System.out.println("You must enter digits for the pin code.");
}
myuser.nextLine();
} while (pin == -1);
As you see Scanner.hasNextInt() should be queried, to check that an integer was provided. Any other non-numeric token could be consumed with next().
You could also use myuser.hasNextLine() when the typing user broke out of inputting.
This makes the use of Scanner circumstantial. I prefer reading lines and parsing them, say with Integer.parseInt(line). Otherwise I strongly advise to use the Console class which even has password entry (so the PIN does not show on the screen). This class however cannot be tested inside the IDE as a "console" in the IDE generally does a System.setIn(...) to capture the console. Console has nice prompts.
// SAMPLE CODE
char[] passwd;
Console cons = System.console();
if (cons != null) {
String username = cons.readLine("User: ");
passwd = cons.readPassword("Password for %s: ", username);
if (passwd != null) {
...
Arrays.fill(passwd, ' '); // Clear sensitive data in memory.
}
}
As you have seen from other answers everything read from the scanner will be read as a String. Here is a little trick or workaround to check if someone enters a number.
public static void main(String[] args) {
Scanner myuser = new Scanner(System.in);
System.out.println("Enter your username: ");
String username = myuser.nextLine();
try {
int valueInInteger = Integer.parseInt(username);
System.out.println("Incorrect username! ");
} catch (NumberFormatException e) {
System.out.println("Your username is: " + username);
}
System.out.println("Enter your pin code: ");
int pin = myuser.nextInt();
System.out.println("Your pin code is: " + pin);
}
The trick here is if you parse a string it will throw a number format exception and you will be sure its a string.
Try the follow code, maybe you can use.
public static void main(String[] args) {
Scanner myuser = new Scanner(System.in);
System.out.println("Enter your username: ");
String username = myuser.nextLine();
boolean isNumeric = username.matches("[+-]?\\d*(\\.\\d+)?");
if (isNumeric){
System.out.println("Retry! Incorrect username!");
main(args);
System.exit(0);
}
System.out.println("Your username is: " + username);
System.out.println("Enter your pin code: ");
int pin = myuser.nextInt();
System.out.println("Your pin code is: " + pin);
}
Related
Just beginning to learn java and I am trying to code a simple password check that gives you tries if you type the incorrect password. The problem is when I type the incorrect password and followed by the correct password it still says its the wrong password.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Tell us the Password");
while(true) {
String password = scanner.nextLine();
if (password.equalsIgnoreCase("Happy")) {
System.out.println("Correct password");
break;
}
else {
for (int i =6; i>0;i--) {
System.out.println("Incorrect password ");
System.out.println(+ i + " Trys left");
password= scanner.nextLine();
}
}
System.out.println("No more tries");
System.out.println("Program exits");
break;
}
}
I want the program to check if the password is correct or incorrect.
Once you entered the wrong password, code flow stuck in the for loop and remain there for available iterations, no comparison with entered password is going on there so you need to modify the flow. One way to do so as per your initial code posted is
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Tell us the Password");
int tryCountForFailure = 6;
while (true) {
String password = scanner.nextLine();
if (password.equalsIgnoreCase("Happy")) {
System.out.println("Correct password");
break;
} else {
System.out.println("Incorrect password ");
System.out.println(tryCountForFailure + " Trys left");
tryCountForFailure--;
if (tryCountForFailure == 0) {
System.out.println("No more trys");
System.out.println("Program exits");
break;
}
}
}
scanner.close();
}
In your code, the loop gets stuck in the Else statement. Let's run through the logic.
The program asks for the password and stores it in a password String.
The program check's if that password is right, if it is the program stops and if not it continues to the else statement.
The program uses a for statement to run this block of code 6 times:
System.out.println("Incorrect password ");
System.out.println(+ i + " Trys left");
password = scanner.nextLine();
The problem is even if you enter a correct String for the password field, it never checks if that value is correct. You would be better of refactoring your code so the logic is sound. Let's run through what should happen.
Program defines a variable named count and set's it to 0.
The program uses a while loop to ask if count is less than 6.
The program takes in a password String with a scanner.
The program checks if that password String is equal to the correct password, if yes, it breaks and,
If it does not equal the correct password it adds one to count
Scanner scanner = new Scanner(System.in);
System.out.println("Tell us the Password");
String password = scanner.nextLine();
if (password.equalsIgnoreCase("Happy")) {
System.out.println("Correct password");
break;
} else {
count++
}
}
`Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name:");
String userName = scanner.nextLine();
if (scanner.hasNextDouble()){
System.out.println("You can't enter numbers");
}`
Here i can't print "You can't enter numbers". Or is there any other option to restrict user to input numbers?
You can try out something like below
public static void main(String[] args) {
boolean validUsername = false;
String regexForNumbers = ".*\\d.*";
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your name:");
while (!validUsername) {
String userName = scanner.nextLine();
if(userName.matches(regexForNumbers)){
System.out.println("Username Can not contain numbers");
System.out.println("Please Enter username again:");
}else{
validUsername = true;
}
}
}
Here String regexForNumbers = ".*\\d.*"; will check whether the username contains a number,and you can expect something like this,
Enter your name:
maneesha123
Username Can not contain numbers
Please Enter username again:
123
Username Can not contain numbers
Please Enter username again:
maneesha
Keep it simple, use the String#matches() method with a small Regular Expression (regex) to make sure numerical digits have not been supplied. The "\\D" regex does exactly that, for example:
Scanner scanner = new Scanner(System.in);
String userName = "";
while (userName.isEmpty()) {
System.out.println();
System.out.print("Enter your User name: --> ");
userName = scanner.nextLine();
// Anything is acceptable 'except' numerical digits.
if (!userName.matches("\\D+")) {
System.err.println("Invalid name supplied (" + userName + ")!.\n"
+ "Numerical digits are not permitted! Try again...");
userName = "";
}
}
System.out.println("Acceptable: " + userName);
I recently started java programming
but I have a problem
i want to write a program. I have a password, I ask the user of the program to enter the password
I want: if the person entered a string, I tell him that please don't enter string
and if the password was right and the type of the password that he entered(int) was right, I tell him OK.
in the test of the program, my problem is that when I entered a wrong password and expect that the program tell me that the pass is wrong, the program just tell me nothing !!
here is my code :
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt() && password.nextInt()==pass)
{
System.out.println("ok");
}
else if (password.hasNextInt())
{
System.out.println("wrong pass");
}
else
{
System.out.println("wrong type");
}
You are using hasNextInt() From Java docs.
Returns true if the next token in this scanner's input can be
interpreted as an int value
So you are asking twice for the input.
Example
Input:
1234 (first Input)
1234 (Then hasNextInt() is asking for input again)
OutPut :
wrong pass
So I made this simple snippet for you can use
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
int pass = 123;
try {
int myInput = password.nextInt();
if (myInput == pass) {
System.out.println("ok");
}else{
System.out.println("wrong pass");
}
}catch (java.util.InputMismatchException e) {
System.out.println("wrong type");
}
The problem is that Scanner methods like nextInt() consume input that's then no longer available to later Scanner calls.
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt() && password.nextInt()==pass) // line A
{
System.out.println("ok");
}
else if (password.hasNextInt()) // line B
{
System.out.println("wrong pass");
}
else
{
System.out.println("wrong type");
}
So in case of entering a wrong password, e.g. 4321, what happens?
Line A checks password.hasNextInt() as the first half of your condition. The Scanner doesn't know that right now and waits for your console input. You enter 4321, and now the Scanner can check whether that's a valid number (and it does so without consuming the 4321, so that it's still available). It is, so the program continues to the next part of the condition (side remark: were it abc, that first part would be false, and Java would already know that the combined password.hasNextInt() && password.nextInt()==pass condition would be false, without a need to go into the second half, thus not consuming the entry).
Line A now checks the second half password.nextInt()==pass. This calls nextInt(), returning the integer 4321 and consuming the input. Comparing this against your number 123 gives false, so the condition doesn't match. That's what you want so far.
Now in line B you want to check for the case of a number not being 123. But your condition password.hasNextInt() no longer sees the 4321 we entered, as that has been consumed in line A. So it waits for the next input. That's the problem, you're still calling hasNextInt() after consuming the input with nextInt().
You can change your program like this:
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt()) {
if (password.nextInt()==pass) {
System.out.println("ok");
} else {
System.out.println("wrong pass");
}
} else {
pass.next(); // consume the invalid entry
System.out.println("wrong type");
}
[ I reformatted the code snippet in a more Java-typical style, doesn't change the functionality of course, but looks more familiar to me. ]
Of course, Gatusko's exception-based approach works as well, and personally I'd do it his way, but maybe you don't feel comfortable with exceptions right now, so I stayed as close to your approach as possible.
You can use the following piece of code.
public static void main(String[] args){
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
if (password.hasNextInt())
{
if(password.nextInt()==pass) {
System.out.println("ok");
}
else {
System.out.println("Wrong password");
}
}
else
{
System.out.println("wrong type");
}
}
What about a while?
int MAX_TRIES = 3
int currentTries = 0;
while (password.hasNextInt() && currentTries < MAX_TRIES) {
if (password.nextInt()==pass) {
// OK!
} else {
// Wrong!
}
currentTries++;
}
if (currentTries == MAX_TRIES) {
// You tried too much
} else {
// Password was a string
}
Try this code, if the input is not an integer then it will throw NumberFormatException, which is caught and displayed.
public static void main(String[] args){
int pass = 123 ;
Scanner password = new Scanner(System.in);
System.out.println("Please Enter Your Password : ");
String enteredPassword ="";
if(password.hasNext() && (enteredPassword = password.next()) !=null){
try{
if(Integer.parseInt(enteredPassword) == pass){
System.out.println("ok");
}else{
System.out.println("wrong pass");
}
}catch (NumberFormatException nfe){
System.out.println("wrong type");
}
}
}
I'm creating a login page for a class assignment and having trouble exiting out of a while loop after a method takes in the username and password then searches through a multi-line text file for a match. It can find a match but goes back to the input area in the main method and asked for the username again. Hope this makes sense.
Any help would be extremely appreciated. As you can tell, I'm new to Java since this code is all over the place and probably a ton of mistakes. I've been up all night trying to figure this out but with no luck. Thanks!
package course.registration;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Welcome {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Course Registration System" + "\n");
System.out.print("Please type Login or Register: ");
String choice = input.nextLine();
while (choice.equalsIgnoreCase("Login")){
System.out.print("Please enter email address to log in: ");
String email = input.nextLine();
System.out.print("Please enter password: ");
String password = input.nextLine();
//goes to method to search and match inputs
VerifyLogin verify = new VerifyLogin();
verify.VerifyInfo(email, password);
}
if (choice.equalsIgnoreCase("Register")) {
System.out.println("Going to registration Page...");
}
input.close();
}
}
Here is the method that searches the text file and tries to find a match for the inputs. I feel like the problem is when the method exits and goes back to the while loop in the main method. I can't figure out a way to exit out of the while loop. Here is how the strings look in the "students_logins.txt" file:
jthomas#gmail.com,1234
kwatson#time.com,3333
legal#prog.com,d567
lavern#shirley.com,34
kwatson#gmail.com,12200
package course.registration;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class VerifyLogin {
private String tempUsername;
private String tempPassword;
public void VerifyInfo(String email, String password) throws FileNotFoundException {
boolean login = false;
File file = new File("student_logins.txt");
Scanner info = new Scanner(file);
info.useDelimiter("[,\n]");
while (info.hasNextLine()) {
tempUsername = info.next();
tempPassword = info.next();
if (tempUsername.trim().equals(email.trim()) && (tempPassword.trim().equals(password.trim()))) {
System.out.println("Email Address or Password Works!!");
break;
}
}
if (!login) {
System.out.println("Email Address or Password is Invalid.");
}
info.close();
}
}
Just move condition insede while loop, and if selected condition is final, e.g. user has enterd valid login and password, then use break to exit the loop. Otherwise, loop will be continued:
public class Welcome {
public static void main(String... args) throws IOException {
final LoginValidator loginValidator = new LoginValidator(Welcome.class.getResourceAsStream("student_logins.txt"));
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Welcome to the Course Registration System");
int choice = 0;
while (choice >= 0) {
System.out.println();
System.out.println("1: LoginPlease");
System.out.println("2: Register");
System.out.print("Your choice: ");
choice = scan.nextInt();
scan.nextLine();
if (choice == 1) {
System.out.print("Please enter email address to log in: ");
String email = scan.nextLine();
System.out.print("Please enter password: ");
String password = scan.nextLine();
if (loginValidator.isValid(email, password)) {
System.out.println("Email Address or Password Works!!");
break;
} else
System.out.println("Email Address or Password is Invalid.");
} else if (choice == 2) {
System.out.println("Going to registration Page...");
break;
}
}
}
}
}
For Validation, it is better to load all logins from file at the application start, and then use it just check Map:
final class LoginValidator {
private final Map<String, String> map = new HashMap<>();
public LoginValidator(InputStream in) {
try (Scanner scan = new Scanner(in)) {
scan.useDelimiter("[,\n]");
while (scan.hasNextLine()) {
map.put(scan.next(), scan.next());
scan.nextLine();
}
}
}
public boolean isValid(String email, String password) {
return map.containsKey(email) && map.get(email).equals(password);
}
}
In the main method you are always staying in the while loop, because you're never obtaining input again.
Before while loop you have:
String choice = input.nextLine();
So when you provide Login as an input while condition is always true , so you are staying in this while loop.
If you want to ask user for correct input Login/Register till he/she provides it, you can try to use my version of Welcome class:
public class Welcome {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Course Registration System" + "\n");
System.out.print("Please type Login or Register: ");
String choice = input.nextLine();
while (!choice.equalsIgnoreCase("Login") && !choice.equalsIgnoreCase("Register")) {
choice = input.nextLine();
}
if(choice.equalsIgnoreCase("Login")){
System.out.print("Please enter email address to log in: ");
String email = input.nextLine();
System.out.print("Please enter password: ");
String password = input.nextLine();
//goes to method to search and match inputs
VerifyLogin verify = new VerifyLogin();
verify.VerifyInfo(email, password);
}
if (choice.equalsIgnoreCase("Register")) {
System.out.println("Going to registration Page...");
}
input.close();
}
}
I'm still relatively new to Java and wanted to try out some new stuff related to strings. I tried to write a code for the user to enter a password between 4-12 characters, and so far it worked fine. But during the process, I had to make little fixes here and there, and honestly it does look pretty messy, like a puzzle where all pieces fit but don't make one whole picture. I want my code to be something more "optimized" so I can have an idea of how codes like this one works, you know, just for future reference. So any help appreciated, please take a look at my code and see if there's anything that can be improved. Thanks!
import static java.lang.System.*;
import java.util.Scanner;
public class PasswordWithLimit {
public static void main (String[] args){
Scanner scan = new Scanner (in);
out.print("Enter your password(4-12 characters): ");
String pass = scan.nextLine () + " ";
char check = pass.charAt (11);
if (pass.indexOf (" ") == 3){
out.println("Please enter a valid password: ");
}
if (Character.isSpaceChar(check) || Character.isWhitespace(check)){
out.println("Your password is " + pass);
}
else{
out.println("Please enter a valid password");
}
}
}
I would recommend using the String's length property. This example prompts the user to enter their password and continues asking them until they have entered something which meets the requirements.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter your password (4 to 12 characters)"); // Prompt the user
boolean valid = false;
while (!valid) {
String password = in.nextLine();
if (password.length() > 3 && password.length() < 13) {
valid = true; // Length between 4 and 12, we can stop asking.
System.out.println("Your password is " + password);
} else {
System.out.print("Please enter a valid password: "); // Invalid length, ask again.
}
}
in.close();
}