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();
}
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);
}
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++
}
}
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
I am writing a program that has 4 usernames and 4 passwords. If the user enters the right name with the right password, it then outputs "Welcome!". It only gives 2 tries. This is what I wrote, but when I run this code it doesn't end. It keeps asking for username non-stop. Can someone help me, guide on what I'm doing wrong, or what I am missing? Thanks.
public class password
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int limit = 2;
int count = 0;
String[] user = {"Diana","Jasmin","Jimmy","Ross"};
String[] passwords = {"Flower01","Cheer02","Reading03","Math04"};
while (true)
{
System.out.print("Enter Username: ");
String [] name = input.nextLine();
if(user.equals(name))
{
while (count < user.length)
{
System.out.print("Enter password: ");
String [] word = input.nextLine();
if (word.equals(passwords))
{
System.out.println("Welcome!");
}
else
{
System.out.print("Sorry can not be found");
count++;
}
}
}
}
}
}
while(true) {...}
is a loop that never ends, you should put you condition at the place of the true.
You can for example add a second count for the first loop (here you want 4 I suppose).
String [] name = input.nextLine();
This line should not compile because you are assigning a string to an array.
Here is simple cut of your code that works. Couple of things
Start Class name in capital.
You were reading input as Arraywhich should really fail at compile time really.
You were not updating the count or displaying any thing if username is wrong.
Use Printlnto get new line after print.
import java.util.Scanner;
public class Password
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int limit = 2;
int count = 0;
String[] user = {"Diana","Jasmin","Jimmy","Ross"};
String[] passwords = {"Flower01","Cheer02","Reading03","Math04"};
while (count <4)
{
System.out.print("Enter Username: ");
String name = input.nextLine();
if(user.equals(name))
{
while (count < user.length)
{
System.out.print("Enter password: ");
String word = input.nextLine();
if (word.equals(passwords))
{
System.out.println("Welcome!");
}
else
{
System.out.println("Sorry can not be found");
count++;
}
}
}
else
{
System.out.println("Sorry can not be found");
count++;
}
}
}
}
You have a while true in your code. What you probably want to do, is to replace the while true with count and limit condition. Most of your code is already in place, you'll only need to replace the while true.
I'm also not sure why you have the second loop, which iterates over the users, sort of. I think what you can better do is replace the 2 arrays with a simple HashMap, something like this:
Map users = new HashMap();
users.put("name1", "password1");
users.put("name2", "password2");
users.put("name3", "password3");
users.put("name4", "password4");
And then, based on the username, you do a users.get(username) to get the password. Then, compare the password with the password the user typed. If it's correct, say welcome, if it's not correct, say error, and increment the counter. Then, if the counter is bigger than the max, stop the program. Hope that helps!
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.