What's wrong with my password program? - java

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.

Related

String input exceptions java

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);
}

Simple Password Check

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++
}
}

Code for limiting password characters

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();
}

problems with checking input in java

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

Can't run if statements completely

I have a problem with my java programs when I use if statements. In fact the programs don't run well and completely as I write. To tell you the truth I'm really confused about it because I don't know where is the problem from...
For example I've written these codes but when I run them, I can't get the city codes:
import java.util.Scanner;
public class Code {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Give the name, Get the code!\n* * * * * * * * * * * * * * *\n");
System.out.print("Please enter the name of the country : ");
String countryInput = sc.next().toLowerCase();
System.out.print("Please enter the name of the city : ");
String cityInput = sc.next().toLowerCase();
System.out.println("\n-----------------------------");
switch(countryInput) {
case "iran" :
System.out.print("+98 ");
break;
case "us" :
System.out.print("+1 ");
break;
default: System.out.print("ERROR: the entered country doesn't exist in program database!");
}
if(countryInput=="iran") {
switch(cityInput) {
case "tabriz" :
System.out.print("411");
break;
case "tehran" :
System.out.print("21");
break;
case "mashhad" :
System.out.print("511");
break;
default : System.out.print("\nERROR: the entered city doesn't exist in program database!");
}
}
if(countryInput=="us") {
System.out.print("(Sorry, the US cities aren't avalable!)");
}
System.out.print("\n-----------------------------\nProgrammer: user3891619");
}
}
And also this one. The program never says "Password is wrong" even when is necessary:
import java.util.Scanner;
public class Pass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int pass = 1234 ;
System.out.print("Please enter your password: ");
if(sc.hasNextInt() && sc.nextInt() == pass) {
System.out.println("The password was successfully entered.");
}
else {
if(sc.hasNextInt()) {
System.out.println("The password is wrong.");
}
else {
System.out.println("Password format is incorrect.");
}
}
}
}
Your post has 2 questions.
For the second one it's easy. When you call sc.hasNextInt() it verifies if there is an integer in the next section. Calling sc.nextInt() will read this integer and put the read cursor behind it. If you again call hasNextInt() it will verify if there is a second integer value which is not the case in your situation.
Your if structure should be:
if (sc.hasNextInt())
{
if (sc.nextInt()==pass)
System.out.println("The password was successfully entered.");
else
System.out.println("The password is wrong.");
} else {
System.out.println("Password format is incorrect.");
}
Try with:
while (sc.hasNextInt(){
if(sc.nextInt().equals(pass)) {
System.out.println("The password was successfully entered."); }
else{
if(sc.hasNextInt()){System.out.println("The password is wrong.");}
else{System.out.println("Password format is incorrect.");}
}}
You have to use .equals for Strings instead of ==
Yes Ben Green is right. Please use .equals when comparing strings.
countryInput.equals("something")
Please read this to find your answer.
What is the difference between == vs equals() in Java?

Categories

Resources