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++
}
}
Related
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);
}
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 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();
}
The title is deceiving however I didn't really know how to ask this.
I am playing around with java. This is my code:
package zodiac;
import java.util.Scanner;
public class Zodiac {
public static void main(String[] args) {
Scanner username = new Scanner(System.in);
String uname;
System.out.println("Please enter your username: ");
uname = username.nextLine();
boolean test = (uname.length() <= 3);
int trip = 0;
while (trip == 0) {
trip++;
if (test) {
trip = 0;
System.out.println("Sorry username is too short try again");
uname = username.next();
}
else {
System.out.println("Welcome Mr/Mrs: " + uname);
}
}
}
}
what i'm trying to do is prompt the user to enter their username and once they do check if the name is less than or equal to 3 make them type the username again, if the username if more than 3 chars print welcome mr/mrs blablabla
at the moment if the username if more than 3 chars it prints out the welcome message, however if you enter 3 or less chars it tells you to enter the username again and if you type a username with more than 3 chars afterwords it keeps telling the user that the password is too short.
How can i fix this. I have just recently started studying java at university however my teachers lack motivation to teach so i have to result to the internet, thank you.
There are two things that you might want to think about in your code:
don't use an integer to stop looping if a boolean would be sufficient
a do-while loop might be more appropriate for your case (you don't have to rewrite code that way!
Now to your question: You are not checking the required minimum length of the inserted string in your loop again! This code might help you to understand all of the points i mentioned:
public static void main(String[] args) {
Scanner username = new Scanner(System.in);
String uname;
System.out.println("Please enter your username: ");
boolean tooShort = true;
do {
uname = username.next();
if (uname.length() <= 3)
System.out.println("Sorry username is too short try again");
else {
System.out.println("Welcome Mr/Mrs: " + uname);
tooShort = false;
}
} while (tooShort);
username.close();
}
insert boolean test = (uname.length() <= 3) in your loop
Helllo can somebody tell my why it doesn't tell my that the password is invalid, when I don't write the valid password?
import java.util.Scanner;
public class Password {
private static Scanner in;
public static void main(String[] args) {
System.out.println("Please enter the password:");
in = new Scanner (System.in);
String pass;
pass = in.nextLine();
if(pass.length() < 4){
System.out.println("The password is too short");
} else if(pass.length() > 9){
System.out.println("The password is too long");
}
if(pass.equalsIgnoreCase("hudhud")){
System.out.println("Welcome BOSS");
while (!pass.equals("hudhud")){
System.out.println("The password is invalid");
}
}
}
}
Test cases:
Input: foo
Output: The password is too short
Input: foobar
Output:
Input: foobarfoobar
Output: The password is too long
Input: hudhud
Output: Welcome BOSS
Your while statement
while (!pass.equals("hudhud")){
System.out.println("The password is invalid");
}
is dead code - it cannot be reached. You check if pass equals hudhud. Inside that check, you have a while loop without a break statement testing if the password doesn't equal hudhud. At this point, it cannot equal anything other than hudhud.
Note that nothing is printed to the screen when the password is between 4 and 9 characters and not equal to hudhud. If you're trying to change that, add an else to the if(pass.equalsIgnoreCase("hudhud")) check.