Strings || Case Sensitive - java

Need to make a password program, where the user sets a password at the beginning and the password can be entered 3 times before the program is stopped. The program can not be case sensitive.
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int attempts = 3;
String password = "";
System.out.println("Please input your password.");
Scanner stringScanner = new Scanner(System.in);
String PASSWORD = stringScanner.next();
while (attempts-- > 0 && !PASSWORD.equals(password)) //compares and then decrements
{
System.out.print("Enter your password: ");
password = sc.nextLine();
if (password.equals(PASSWORD))
System.out.println("Access Granted");
else
System.out.println("Incorrect. Number of attempts remaining: " + attempts);
}
if (attempts < 1) {
System.out.println("You have entered too many incorrect passwords, please try again later.");
}
else {
System.out.println("Secret: Water is not Wet.");
}
}
}
Program prints as expected, but is not case sensitive

The first part of your question says The program can not be case sensitive while afterwards you are stating that Program prints as expected, but is not case sensitive, so it's a little difficult to understand what you want. But by looking at the code and seeing that it is doing a case-sensitive comparison, and that you are not happy with it's behavior, I'm guessing you want this to be a case-INsensitive comparison.
In that case, you can use String#equalsIgnoreCase: !PASSWORD.equalsIgnoresCase(password)

simply if you need not to consider the case sensitive just do password.equalIgnoreCase(PASSWORD)
but if you need to be sure that both have same case sensitive you can just convert both variables to .toUpperCase before the comparison

Related

Need help utilising the while loop for repeating parts of code

I am trying to use the while loop for re-running parts of code in my simple program. In this program, the user makes a simple account, types in a verification number, then signs in. Once signed in, I wish to allow the user to sign out, edit his profile settings and more. However I have a small problem.
Say the user has just edited their account settings. Instead of the program terminating, I want them to be able to return to the "menu".
The problem lies with how to do that. As there is no goto statement in java, from what I have read, I must use the while loop. I have no idea of how to go about that. I just can't wrap my head around it. Loops have always confused me. Also, should I even use the while loop? Would it be better to use the for or do-while loops? And what expression should I use? Will I need the break statement?
I know it isn't a concrete question, but any help that puts me on the right path is well appreciated.
Below is the full code for reference.
public static void main(String[] args) {
System.out.println("Hi! To begin please choose your username.");
System.out.println("To do this, please enter your username below. ");
System.out.println("This name must be at least three characters.");
Scanner userInput = new Scanner(System.in);
String userName = userInput.next();
int nameLength = userName.length();
if (nameLength > 2) {
System.out.println("Now please enter your password.");
System.out.println("This password must be at lease five characters");
String passWord = userInput.next();
int passLength = passWord.length();
if (passLength > 4) {
System.out.println("Signup alost complete.");
Random rand = new Random();
int randm = rand.nextInt(100000) + 1;
System.out.println("To confirm you are not a robot, please enter this code: " + randm);
int code = userInput.nextInt();
if (code == randm) {
System.out.println("Thank you, " + userName);
System.out.println("You may now login. Begin by entering your username");
//Where I would go if the user signed out
String name = userInput.next();
if (name.equals(userName)) {
System.out.println("Now please enter you password");
String pass = userInput.next();
if (pass.equals(passWord)) {
System.out.println("Thank you. You have now successfully logged in");
//Where the "main menu" will be
//Rest of code will also go here
}
else {
System.out.println("Password is incorrect");
}
}
else {
System.out.println("Username is incorrect");
}
}
else {
System.out.println("The code entered is incorrect.");
}
}
else {
System.out.println("Invalid Password");
}
}
else {
System.out.println("Invalid Username");
}
}
You have placed a comment //where would I go if the user signed out?
The answer is, You will show the message to sign in when he is signed out, so that he can sign in again. You can do this by using for loop or loop or whatever loop you want. That means the part of user login will be in a loop, if the user logged in then the menu will be shown up. If the user sign out, the sign in form will be shown up infinitely.
You can put your code inside do. It will not break and will keep looping.
do{
}
while(true);

Write a program reads in a series of passwords into an array&Store 10 passwords.After, have the reader enter a password & see if it is in the array.

import java.util.Scanner;
public class Password
{
public static void main (String [] args)
{
{String [] myArray = new String[10];
int i;
System.out.println("Enter a password: ");
Scanner in = new Scanner(System.in);
String myString = in.next();
//my arrays are here//
myArray[0] = "password";
myArray[1] = "password1";
myArray[2] = "iloveyou";
myArray[3] = "abc123";
myArray[4] = "abc1234";
myArray[5] = "bears55";
myArray[6] = "shelby27";
myArray[7] = "Mjcheer38";
myArray[8] = "sillypineapple";
myArray[9] = "freshvase";
//not sure if this is where this for loop should go//
for (i=0;i<9;i++)
{
if (myString.equals(myArray[i]))
{
System.out.println("Password Accepted");
break;
}
else
{
System.out.println("Password Rejected");
break;
}
//I think my if statements are right....//
}
}
}
}
The full question is: 6. Write a program reads in a series of passwords into an array. Store 10 passwords. After creating the password array, have the reader enter a password and see if it is in the array. If it is there, print “Valid password” and if it is not there, print “Invalid password”. I have no idea what I could be doing wrong. For the first password, it says accepted, but for the rest it says rejected. Can someone please point out where I have gone wrong. I cannot seem to figure it out.
Well, you don't want to immediately break out of the loop; that defeats the purpose of the loop entirely.
Including a break; statement in every possible execution branch of the for loop (i.e. it's impossible for break; not to execute) will ensure that the loop body will never execute multiple times. It won't be much of a loop, then.
Try turning your for loop into this:
boolean validPassword = true;
for (i=0;i<9;i++) {
if (myString.equals(myArray[i])) {
System.out.println("Invalid password");
validPassword = false;
break;
}
}
if(validPassword) {
System.out.println("Valid password");
}
Note that you only want to print "Valid password" if the user-entered string is not equal to ANY of the passwords in the array. Thus, printing "Valid password" and then "Invalid password" wouldn't be a good idea.

ATM pin verification in java

I am very new to programming and need some help. I need to write a simple program that verifies an ATM users pin number. The program will either, accept the pin and exit, tell the user it was an incorrect pin and have them try again up to three times, or tell the user their card is locked because they were wrong three times. I have searched for over an hour now and cannot find an example of this. I know i will need to use a scanner and a loop to accomplish this but not much else. Any help is appreciated as it is due by midnight......
for i = 1..3
prompt user for pin
read pin
check pin
if pin is correct, exit
tell user they were wrong and try again
tell user they got it incorrect three times and their card is locked.
I will give one hint which can trip some newbies up. The pin is an integer, right? So you might be tempted to use Scanner.nextInt() to get the input--do not do that! Just get the next line and compare Strings (you may have to use String.trim() to get rid of whitespace). It's more complicated if you try to use Scanner.nextInt() (what if the user enters something that cannot be parsed as an integer).
import java.util.Arrays;
import java.io.Console;
public class atm {
public static void main(String[] args) {
int counter = 3;
int attempt = 3;
char[] ch = null;
Console c=System.console();
System.out.println("Enter PIN: ");
ch=c.readPassword();
String pass=String.valueOf(ch);
if(pass.equals("enigma")){
System.out.println("Correct PIN entered!");
}
while(!pass.equals("enigma") && attempt != 0){
System.out.println("Invalid PIN entered!. " + --attempt + " attempts remaining.");
counter--;
if(attempt != 0){
c=System.console();
System.out.println("Enter PIN: ");
ch=c.readPassword();
pass=String.valueOf(ch);
if(pass.equals("enigma")){
System.out.println("Correct PIN entered!");
}
}
else{
System.out.println("your card has locked!");
break;
}
}
}
}
Note that you can put your PIN code instead of "enigma" string, I hope that will help.
here is the implementation of pseudo code answered by #Jared above
boolean cardLockFlag = false ;
String password;
Scanner scan = new Scanner (System.in);
password = "password" ;
if(!cardLockFlag){
for(int i = 0 ; i < 3 ; i++){
if(password.equals(scan.next().trim())){
System.out.println("Success :) ");
break ;
}else{
if(i==2){
cardLockFlag = true ;
}else{
System.out.println("Wrong Password");
}
}
}
}else{
System.out.println("Card is Locked");
}

Password prompt and calling a method from an if statement

this i my first attempt at asking a question so hopefully it shows correctly. Basically what I need the program to do is to ask the user for a preset account number and password and only allow them 3 attempts. I then want to call up another method when both requirements are met so i can continue with the program. The first problem i have is that when i enter the correct password its is still showing as incorrect and i don't know why, then i would like to know if i have call the method within the if statement correctly. Thanks.
import java.util.Scanner;
public class Part4 {
public static void main(String[] args)
{
String password = "password", passwordattempt = null;
int accnum = 123456789, acctry = 0, tries = 0;
Scanner input = new Scanner (System.in);
while (acctry != accnum){
System.out.println("\nPlease enter your account number");
acctry = input.nextInt();
if (acctry != accnum)
System.out.print("That number is incorrect. Please try again.");
else
if (acctry == accnum)
{
while (tries < 3)
{
System.out.println("\nPlease enter password");
passwordattempt = input.next();
if (passwordattempt != password){
System.out.print("That password is incorrect");
tries++;
}
else
if (passwordattempt == password){
System.out.print("That is correct");
AccountDetails.Details(args);
}
}
System.out.print("\nYou have exceeded the ammount of tries");
}
}
}
public static class AccountDetails {
private static void Details(String[] args){
System.out.print("it works");
}
}
}
two problems.
1: You're executing your while loop regardless of if it is successful or not.
.
while(tries < 3)
should be
while(tries < 3 && !successfulPassword)
You'll need to add the successfulPassword variable, so that you don't get it right the first time and yet continue to have to enter passwords.
2: Your comparison of strings is grossly, umm, well, wrong. There's two things that catch my eye. The first is you can't use == and != and get the results you expect. You must use .equals(). Secondly, you don't need to repeat the opposite clause like you do with a human. For example, I tell my daughter "If you eat your supper, then you may have cookies. Else, if you do not eat your supper, then you may not have cookies." To a computer, you don't need that last "if you do not eat your supper". It's guaranteed to be true (since you're in the else block anyway) and it just clutters it up. So that just becomes
.
if(passwordAttempt.equals(password) {
successfulPassword = true;
} else {
tries++;
}
In the Java language, Strings are objects, and thus comparing them using '==' is testing by reference, and not by equality.
I believe what you are looking for is
if (passwordattempt.equals(password)) {
Check here for more information:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#equals(java.lang.Object)

Java code Check Password for Letter and Digit?

The first post was confusamagin. My assignment is to create a password prompt program. The password needs to be checked to see if it does have at least one digit and one letter in it. Also the password length must be between 6 - 10.
My problem is trying to figure out how see if a digit and letter exist the password. In the check password area I am not sure where to begin really. I am not sure how to see if it has a Letter and a Digit in one. I know how to do either or by using a for statement to count and check but all it does is check to see rather it contains all letters or all digits.
import java.util.Scanner;
class Password {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//------ENTER A USERNAME
System.out.println("Welcome please enter your username and password.");
System.out.print("Username >>");
input.nextLine();
//------PASSWORD AUTHENTICATION BEGIN
String password = enterPassword();
while ( !checkPassword(password) ) {
System.out.println("Password must be 6 - 10 characters long!");
password = enterPassword();
}
//------PASSWORD VERIFY
String passwordverify = enterPassword();
while (!password.equals(passwordverify)){
System.out.println("ERROR - Passwords DO NOT MATCH Re-Enter Passwords Again");
password = enterPassword();
}
//------ACCEPT PASSWORD
System.out.println("Username and Password Accepted!");
}
//--ENTER PASSWORD STATEMENT
public static String enterPassword(){
String password;
Scanner input = new Scanner(System.in);
System.out.print("Password >>");
password = input.nextLine();
return password;
}
//--BOOLEAN CHECK PW
public static boolean checkPassword(String password){
int length;
length = password.length();
if (length < 6 || length > 11){
return false;
}
for (int i = 0; i < password.length();i++){
if (!Character.isLetter(password.charAt(i)))
return false;
}
return true;
}
}
Without writing your homework assignment.... you're on the right track you have make sure that your count of letters, and your count of numbers are both at least 1.
Your code is only missing variable counters. Keep two counters: one to count letters, one to count numbers, and perform the if test at the end of both for loops inside checkPassword to check if both counters are at least one.
An alternative of doing this is using regular expression. See this link:
http://www.mkyong.com/regular-expressions/how-to-validate-password-with-regular-expression/

Categories