This should be a program to take in a password from the user and check it against various parameters.
I've an issue with the do while loop, it prints:
Please enter your password.
Error. Password is too short. Try again.
Then it prints this after selecting option
1. Enter your own password for verification
The program should allow the user to enter a password before printing any error messages.
First time using this site. Any help with this would be greatly appreciated.
import java.security.SecureRandom;
import java.util.*;
public class CC_CA2
{
// Main Method
public static void main(String[] args)
{
Scanner keyboardIn = new Scanner(System.in); //Create Scanner object
String[] data = {"123456","password","12345","12345678","qwerty","123456789","1234","baseball","dragon","football","1234567","monkey","letmein","abc123","111111","mustang","access","shadow","master","michael"};
String correct;
int numLetterCheck = 0;
int option;
boolean found = false;
boolean check;
boolean digitFound = false;
boolean letterFound = false;
//Menu
System.out.println("Welcome to the password checker.");
System.out.println("Would you like to:");
System.out.println("1. Enter your own password for verification.");
System.out.println("2. Have an easy to remember random password generated for you.");
option = keyboardIn.nextInt();
if (option==1)
{
do
{
check = true;
found=false;
System.out.println("Please enter your password."); // get user password
correct = keyboardIn.nextLine();
if (correct.length()<8) // 1. check password > 8 characters
{
System.out.println("Error. Password is too short. Try again.");
check=false;
continue;
}
if (correct.contains(" ")) //2. check if password contains any spaces
{
System.out.println("Error. Password contains a space. Try again.");
check=false;
continue;
}
for(int i = 0; i < data.length; i++) // 3. check common passwords
{
if(data[i].equals(correct)) //if match found
{
found = true; //remember that it is found
}
}
if(found) //if found is true
{
System.out.println("Error. This is a common password. Try again.");
check=false;
continue;
}
for (char ch : correct.toCharArray()) // 4. Make sure password contains at least one letter and one number
{
if (Character.isDigit(ch))
{
digitFound = true;
}
if (Character.isLetter(ch))
{
letterFound = true;
}
if (digitFound && letterFound)
{
numLetterCheck = 0;
}
else
{
numLetterCheck = 1;
}
}
while (numLetterCheck == 1)
{
letterFound=false;
digitFound=false;
System.out.println("Error. Password must contain at least one letter and one number. Try again.");
correct = keyboardIn.nextLine();
}
}while(check == false);
}
}}
Related
Information needed 3 tries then program closes.
The same password is used for every user.
The password is set too password = 12345678.
User data is extracted from a GUI component
Code I've tried:
String password = "12345678";
String userInput = String.valueOf(jPasswordField1.getPassword());
int length = userInput.length();
if (userInput.equals(password)) {
this.dispose();
new INPUT().setVisible(true);
}
else if (!userInput.equals(password)) {
if (length > 9) {
lblValid.setText("To many characters");
tries++;
}
else if (length < 8) {
lblValid.setText("To little characters");
tries++;
}
}
if (tries == 3) {
System.exit(0);
}
You can use Scanner along with a while loop to achieve it:
Scanner scanner = new Scanner(System.in);
int tries=0;
String password = "asdf123";//DO NOT USE THIS PASSWORD
while(tries<3) {
System.out.print("\nEnter password: ");
String passwordattempt = scanner.nextLine();
if(!passwordattempt.equals(password)) {
System.out.println("Wrong password");
tries++;
}else {
System.out.println("Correct");
break;
}
}
scanner.close();
I am trying to catch no input (enter key) and invalid input everything but y/n in one method. I tried it two different ways (pasted) but I cannot make work both “enter key” and “mistype y/n” together. Thank you for your help.
1st attempt:
public static String askToContinue(Scanner sc) {
String choice = "";
boolean isValid = false;
while (!isValid){System.out.print("Continue? (y/n): ");
if (sc.hasNext()){
choice = sc.next();
isValid = true;
} else {System.out.println("Error! "
+ "This entry is required. Try again");
}
if (isValid && !choice.equals("y") || !choice.equals("n")) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again");
isValid = false;
}
}
//sc.nextLine(); // discard any other data entered on the line
System.out.println();
return choice;
}
2nd attempt
public static String askToContinue(Scanner sc) {
System.out.print("Continue? (y/n): ");
String choice;
while (true) {choice = sc.next();
//?????????????????????????????????????????????????????
if (choice.length() == 0){ System.out.println("Error! "
+ "This entry is required. Try again");
continue;
}
if (!(choice.equals("y") || choice.equals("n"))) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again");
continue;
}
break;
}
sc.nextLine(); // discard any other data entered on the line
System.out.println();
return choice;
}
I tried with 1st attempt of your code. I explained with comment line which is included in below code like ;
public static String askToContinue(Scanner sc) {
String choice = "";
boolean isValid = false;
while (!isValid) {
System.out.print("Continue? (y/n): ");
choice = sc.nextLine(); //to reads all line , because this cannot read with empty enter input
isValid = true;
if (choice.isEmpty()) { //this isEmpty for empty enter
System.out.println("Error! "
+ "This entry is required. Try again");
}
System.out.println(choice);
//this logic if not y or n , it will return error
if (!choice.equals("y") && !choice.equals("n")) {
System.out.println("Error! Entry must be 'y' or 'n'. Try again");
isValid = false;
}
}
//sc.nextLine(); // discard any other data entered on the line
System.out.println();
return choice;
}
Your if statement in first case is wrong. You are checking if choice is not equal to 'y' or not equal to 'n' which will always be true .
Change
if (isValid && !choice.equals("y") || !choice.equals("n"))
To
if (isValid && !choice.equals("y") && !choice.equals("n"))
I'm making a login program, but it is getting some errors. If I put in a name that is not in the list, I get an error. It doesn't seem to reach the else statement also, and I'm not sure why.
import java.lang.*;
import java.util.*;
import java.io.*;
import java.math.*;
public class HelloWorld {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userName;
int n = 10;
int i = 0;
String[] array = new String[n];
array[0] = "John";
array[1] = "Johny";
array[2] = "ben";
System.out.println("Enter your user name(Note:**Case Sensative**)");
userName = input.nextLine();
while (i <= array.length) {
if (array[i].equals(userName)) {
System.out.println("Your UserName is valid");
break;
}
else if (!array[i].equals(userName)){
i++;
}
else {
System.out.println("Your UserName is not valid");
break;
}
}
}
}
First, I'd consider using a for-loop as it'll manage the i value for you, but also consider the logic you have
if element.equals(userName) {...}
else if !element.equals(userName) {...}
else {...}
How is it possible to ever get into the else block, either element will be or won't be equal to the userName, there is no other state. I'd consider having a flag which indicates if a user was found or not and checking that at the other end of the loop
As a general concept...
//...
userName = input.nextLine();
String validUser = null;
for (int index = 0; index < array.length; index++) {
if (array[i].equals(userName)) {
validUser = userName;
break;
}
}
if (validUser != null) {
System.out.println("UserName is valid");
} else {
System.out.println("Your UserName is not valid");
}
Because you probably don't care about the index so much, you can also do something like...
for (String element : array) {
if (array[i].equals(userName)) {
validUser = userName;
break;
}
}
which is shorthand version.
Have a look at The for statement for more details
First of all your if and else if are the only condition the java will run in your context and there are no other condition running afterwards. It is like you are doing TRUE and FALSE and expecting another condition. Make use of foreach in java much simpler way.
boolean found = false;
for(String name: array){
if (name.equals(userName)) {
found = true;
break;
}
}
if(!found){
System.out.println("Your UserName is not valid");
}else{
System.out.println("Your UserName is valid");
}
When you get mastered use the methods of Array , Collections and specially lambdas stream api for little bit lift up your java knowledge.
Your Statement will never go to the else part, because the the input(userName) will either EQUAL array[i], or not. Think about it...
if (array[i].equals(userName)) { //It will do this if userName is array[i]
System.out.println("Your UserName is valid");
break;
}
else if (!array[i].equals(userName)) { //It will do this if userName is NOT array[i]
i++;
}
else { //this is impossible, unreachable code
System.out.println("Your UserName is not valid");
break;
}
The reason your else is not reachable is because it is an impossible scenario. I edited your program, and it works now. Here's the whole thing:
import java.util.Scanner;
public class Experiments {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userName;
boolean found = false;
String[] array = new String[3];
array[0] = "John";
array[1] = "Johny";
array[2] = "ben";
System.out.println("Enter your user name:");
userName = input.nextLine();
for(int i=0; i<array.length; i++) {
if (userName.equalsIgnoreCase(array[i])) {
System.out.println("Your UserName is valid");
found = true;
break;
}
if (!found && i == array.length-1) {
System.out.println("Your UserName is not valid");
}
}
input.close();
}
}
If the input (userName) is in the array at any spot, it will say "Your UserName is valid" If it isn't in the array, it will say "Your UserName is not valid".
Here is an example of a valid userName:
Enter your user name:
John
Your UserName is valid
And if the UserName is invalid:
Enter your user name:
Jimmy
Your UserName is not valid
Please comment if you have any questions about this, and I will explain.
So I have been working on this program which prompts the user to enter a password but the password must be at least 8 characters long and only contain letters and digits. Here is my code:
import java.util.Scanner;
public class Password {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Please enter a password: ");
String password = input.nextLine();
boolean valid = true;
if (valid(password)) {
System.out.println("Password accepted!");
}
}
public static boolean valid(String password) {
if (password.length() < 8) {
System.out.println("Password must have at least eight characters.");
return false;
} else {
char c;
for (int i = 0; i < password.length(); i++) {
c = password.charAt(i);
if (password.matches("[0-9a-zA-Z]+")) {
return true;
} else {
System.out.println("Password must only contain letters and digits.");
return false;
}
}
return true;
}
}
}
The problem I'm having is that when I enter an input like $$$, the only output is "Password must have at least eight characters", but I need both this output and ""Password must only contain letters and digits." In other words, I need the program to check if both conditions are false and display both outputs. How would I go about doing that?
Also, if you have any suggestions on how to make my program better, that would be helpful as well.
Thank you!
You could simply move your valid variable from the main method to the valid method and set it to false for every condition not met. Only return in the end after every condition has been checked.
public static boolean checkValid(String password) {
boolean valid = true;
if (password.length() < 8) {
System.out.println("Password must have at least eight characters.");
valid = false;
}
if(!password.matches("[0-9a-zA-Z]+")) {
System.out.println("Password must only contain letters and digits.");
valid = false;
}
return valid;
}
And you don't need to iterate through every character of the password to match the regex.
Can someone help me with my code please. Im a begginer and this thing called java really confusses me :) my problem is that i have to remove user/s, but my ouput is allways just user name not found... thanks in advance
public void removeUser() {
java.util.Scanner input = new java.util.Scanner(System.in);
int checks = 1;
if (checks == 1) {
for (int i = 0; i < userList().size(); i++) {
System.out.println("Input user name for the account you want to be deleted");
userName = input.next();
if (userList.equals(userName)) {
userList.get(i);
userList.remove(userName);
System.out.println("You succesfully removed user acount");
System.out.println("If you want to exit press 0, if you want to continue press 1");
checks = input.nextInt();
} else {
System.out.println("User name not found");
}
}
}
if (checks == 0) {
administrator();
}
}
why do you think that this would work?
if (userList.equals(userName))
??
Maybe just try removing it
boolean removed = userList.remove(userName);
if (removed) {
System.out.println("You succesfully removed user acount");
}
No looping required
see
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(java.lang.Object)
So your code could look like
java.util.Scanner input = new java.util.Scanner(System.in);
int checks = 1;
while (checks == 1) {
System.out.println("Input user name for the account you want to be deleted");
userName = input.next();
if (userList.remove(userName)) {
System.out.println("You succesfully removed user acount");
}
else {
System.out.println("User name not found");
}
System.out.println("If you want to exit press 0, if you want to continue press 1");
checks = input.nextInt();
}
First thing that here you do with your code is change theif (checks == 1) to while loop while(checks == 1), because if can be executed only one time.
Second thing if (userList.equals(userName)) is never true, thus the if clause won't be executed. You first get the user name from the list like this String name userList.get(i); then now you can check if it is equal like this
if(name.equals(userName)) //or userList.contains(userName){
// userList.remove(userName);
// OR
// userList.remove(i);
}
Eidt:
You can change your code as below, maybe work for you
List<String> userList = new ArrayList<>();
userList.add("AA");
userList.add("BB");
userList.add("CC");
java.util.Scanner input = new java.util.Scanner(System.in);
int checks = 1;
while (checks == 1) {
for (int i = 0; i < userList.size(); i++) {
System.out.println("Input user name for the account you want to be deleted");
String userName = input.next();
if(userList.remove(userName)) {
System.out.println("You scornfully removed user account");
} else {
System.out.println("User name not found");
}
System.out.println("If you want to exit press 0, if you want to continue press 1");
checks = input.nextInt();
}
}
if (checks == 0) {
administrator();
}
public static void main(String[] args) {
List<String> customerNames = new ArrayList<String>();
customerNames.add("john");
customerNames.add("lily");
customerNames.add("druid");
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Please enter 1 ");
if(input.nextInt() != 1){
System.out.println("break checks ... ...");
return;
}
for(int i = 0; i < customerNames.size(); i++) {
System.out.println("Input user name for the account you want to be deleted");
if (customerNames.get(i).equals(input.next())) {
customerNames.remove(i);
System.out.println("You succesfully removed user acount");
System.out.println("If you want to exit press 0 ... ...\n");
if(input.nextInt() == 0){ //break
break;
}
} else {
System.out.println("User name not found... ...\n");
}
}
}
public static void main(String[] args) {
List<String> customerNames = new ArrayList<String>();
customerNames.add("john");
customerNames.add("lily");
customerNames.add("druid");
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.println("Please enter 1: ");
if(input.nextInt() != 1){
System.out.println("break checks ... ...");
return;
}
System.out.println("========= start =========");
System.out.println("Please enter 1: ");
while(input.nextInt() != 0){
System.out.println("Input user name for the account you want to be deleted... ...");
System.out.println("enter name:");
String _name = input.next();
for(int i = 0; i < customerNames.size(); i++) {
if(_name.equals(customerNames.get(i))){
customerNames.remove(_name);
System.out.println("You succesfully removed user acount");
break;
}
}
System.out.println("If you want to exit press 0 ... ...\n");
System.out.println("input numeric:");
}
System.out.println("========= end =========");
//break
if(customerNames.size() == 0){return;}
for(String name : customerNames){//print names
System.out.println(name);
}
}