I haven't been able to find an answer to this question. It is a proof of concept bank login page.
The purpose is that if the input matches an entry in the array, you are allowed in.
I have tried object.equals and the like but get I cannot compile correctly.
Here is my code:
import java.util.Scanner;
public class JBLogin {
public static void main(String[] args);
{
String username
Scanner login = new Scanner(System.in);
String [] database;
database = new String[2];
database[0] = "placeholderone";
database[1] = "placeholdertwo";
System.out.println(" Welcome To JavaBank!");
System.out.println("Please Enter Your Username:");
username = login.next();
System.out.println("Welcome Back, " + username);
if (username.object.equals(database))
{
System.out.println("_____________");
}
else
{
System.out.println("Username Not Found.");
}
}
}
You need to compare every element in the array database with username. You can do that using a loop.
Also, to call the Object.equals method on username, you just say: username.equals(...). You shouldn't put .object in between.
boolean found = false;
for (int d = 0; d < database.length; d++) {
if (database[d].equals(username)) {
found = true;
}
}
if (found) {
System.out.println("_____________");
} else {
System.out.println("Username Not Found.");
}
And as others have mentioned, you should also remove the semicolon from the end of the method declaration line:
public static void main(String [] args);
And you should put a semicolon behind the line that declares the String username:
String username;
Related
I'm creating a login page for a class assignment and having trouble exiting out of a while loop after a method takes in the username and password then searches through a multi-line text file for a match. It can find a match but goes back to the input area in the main method and asked for the username again. Hope this makes sense.
Any help would be extremely appreciated. As you can tell, I'm new to Java since this code is all over the place and probably a ton of mistakes. I've been up all night trying to figure this out but with no luck. Thanks!
package course.registration;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Welcome {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Course Registration System" + "\n");
System.out.print("Please type Login or Register: ");
String choice = input.nextLine();
while (choice.equalsIgnoreCase("Login")){
System.out.print("Please enter email address to log in: ");
String email = input.nextLine();
System.out.print("Please enter password: ");
String password = input.nextLine();
//goes to method to search and match inputs
VerifyLogin verify = new VerifyLogin();
verify.VerifyInfo(email, password);
}
if (choice.equalsIgnoreCase("Register")) {
System.out.println("Going to registration Page...");
}
input.close();
}
}
Here is the method that searches the text file and tries to find a match for the inputs. I feel like the problem is when the method exits and goes back to the while loop in the main method. I can't figure out a way to exit out of the while loop. Here is how the strings look in the "students_logins.txt" file:
jthomas#gmail.com,1234
kwatson#time.com,3333
legal#prog.com,d567
lavern#shirley.com,34
kwatson#gmail.com,12200
package course.registration;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class VerifyLogin {
private String tempUsername;
private String tempPassword;
public void VerifyInfo(String email, String password) throws FileNotFoundException {
boolean login = false;
File file = new File("student_logins.txt");
Scanner info = new Scanner(file);
info.useDelimiter("[,\n]");
while (info.hasNextLine()) {
tempUsername = info.next();
tempPassword = info.next();
if (tempUsername.trim().equals(email.trim()) && (tempPassword.trim().equals(password.trim()))) {
System.out.println("Email Address or Password Works!!");
break;
}
}
if (!login) {
System.out.println("Email Address or Password is Invalid.");
}
info.close();
}
}
Just move condition insede while loop, and if selected condition is final, e.g. user has enterd valid login and password, then use break to exit the loop. Otherwise, loop will be continued:
public class Welcome {
public static void main(String... args) throws IOException {
final LoginValidator loginValidator = new LoginValidator(Welcome.class.getResourceAsStream("student_logins.txt"));
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Welcome to the Course Registration System");
int choice = 0;
while (choice >= 0) {
System.out.println();
System.out.println("1: LoginPlease");
System.out.println("2: Register");
System.out.print("Your choice: ");
choice = scan.nextInt();
scan.nextLine();
if (choice == 1) {
System.out.print("Please enter email address to log in: ");
String email = scan.nextLine();
System.out.print("Please enter password: ");
String password = scan.nextLine();
if (loginValidator.isValid(email, password)) {
System.out.println("Email Address or Password Works!!");
break;
} else
System.out.println("Email Address or Password is Invalid.");
} else if (choice == 2) {
System.out.println("Going to registration Page...");
break;
}
}
}
}
}
For Validation, it is better to load all logins from file at the application start, and then use it just check Map:
final class LoginValidator {
private final Map<String, String> map = new HashMap<>();
public LoginValidator(InputStream in) {
try (Scanner scan = new Scanner(in)) {
scan.useDelimiter("[,\n]");
while (scan.hasNextLine()) {
map.put(scan.next(), scan.next());
scan.nextLine();
}
}
}
public boolean isValid(String email, String password) {
return map.containsKey(email) && map.get(email).equals(password);
}
}
In the main method you are always staying in the while loop, because you're never obtaining input again.
Before while loop you have:
String choice = input.nextLine();
So when you provide Login as an input while condition is always true , so you are staying in this while loop.
If you want to ask user for correct input Login/Register till he/she provides it, you can try to use my version of Welcome class:
public class Welcome {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Course Registration System" + "\n");
System.out.print("Please type Login or Register: ");
String choice = input.nextLine();
while (!choice.equalsIgnoreCase("Login") && !choice.equalsIgnoreCase("Register")) {
choice = input.nextLine();
}
if(choice.equalsIgnoreCase("Login")){
System.out.print("Please enter email address to log in: ");
String email = input.nextLine();
System.out.print("Please enter password: ");
String password = input.nextLine();
//goes to method to search and match inputs
VerifyLogin verify = new VerifyLogin();
verify.VerifyInfo(email, password);
}
if (choice.equalsIgnoreCase("Register")) {
System.out.println("Going to registration Page...");
}
input.close();
}
}
Alrighty, I'm currently trying to make a program that takes input, in the form of a email address, from the user and checks to see if it has a '#' in it. I want to use a loop to steps through the whole string that the user entered, and checks each character for the '#'. I'm a little lost as to how to get started.
What I did, was use a for loop to iterate through the whole string that the user entered. Then I used a do/while loop to execute a certain line of code until the user entered a valid email. However, it seems to always be valid no matter if it has a '#' or not. I also want to check if it only contains 1 '#' in it. I'm a little lost as you can see, but any help would be appreciated!
import java.util.Scanner;
class Test
{
public static void main(String args[])
{
System.out.print("Enter an email address ");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
valid c = new valid(input);
}
}
class valid
{
String scan2;
char amper = '#';
int i;
valid(String scan1)
{
scan2 = scan1;
for (i = scan2.length() - 1 ; i <= 0; i--)
do
{
System.out.print("That input is invalid");
} while(scan2.indexOf(i) != amper);
System.out.println("That input is valid");
}
}
Since you have to use a loop, I would recommend charAt. It gives you the character at a given index in a string:
boolean found = false;
//where string is the input that you are scanning to find an email address
for (int i = 0; i < string.length; i++){
if (string.charAt(i) == '#'){
found = true;
break;
}
}
if (found){
System.out.println("Found the # character!");
}
Hope it helps you
Loop the each character in the loop.
Check for '#' character
String email = "test#gmal.com";
boolean valid = false;
for (int i=0;i<=email.length();i++) {
if (email.charAt(i)== '#') {
valid = true;
break;
}
}
if (valid) {
System.out.println("This is valid email Id");
} else {
System.out.println("This is an Invalid email Id");
}
Others have already made some helpful comments, but here a few other things I have noticed:
Did you mean to have no "{} after the for statement? Not having that { } can change the program.
In the for statement, did you want it to be i <= 0 or i >= 0? If i starts out being the length of the input string and the test in the for statement is i <= 0, it will never be true unless the input is zero length.
Why do you have a scan1 and a scan2 String?
You may want to consider removing your search logic from the constructor.
I recommend using charAt() method in this case. Here is my code.
import java.util.Scanner;
public class EmailAddr {
private String emailAddress;
public EmailAddr(String emailAddress){
this.emailAddress = emailAddress;
}
public boolean isValid(){
boolean isValid = false;
int nAtSign = 0;
for (int i = 0; i < emailAddress.length(); i++){
if(emailAddress.charAt(i) == '#')
nAtSign++;
}
if(nAtSign == 1)
isValid = true;
return isValid;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your email address: ");
EmailAddr emailTest = new EmailAddr(sc.nextLine());
sc.close();
if(emailTest.isValid()){
System.out.println("The email address is VALID!");
} else {
System.out.println("The email address is INVALID!");
}
}
}
Javadoc concerning indexOf:
the index of the first occurrence of the specified substring, or -1 if there is no such occurrence.
For example:
Scanner sc = new Scanner(System.in);
System.out.println("Enter your E-Mail:");
String line;
do {
line = sc.nextLine();
}
while(line.indexOf('#') == -1);
Why dont you try with regular expressions ??
public class EmailValidation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean flag;
do{
String pattern="[a-zA-Z]*#[a-zA-Z.]*";
//if u need to think of much better email validation..
//String pattern="^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$";
System.out.println("Enter your Email here :");
flag=scanner.next().matches(pattern);
if(!flag){
System.out.println("Not a valid Email.");
}else{
System.out.println("Valid Email.");
}
}while(!flag);
}
You can use this code as class valid.
class valid {
String scan2;
char amper = '#';
boolean isFound = false;
valid(String scan1) {
scan2 = scan1;
for (int i = 0; i < scan2.length(); i++) {
if (scan2.charAt(i) == amper) {
isFound = true;
}
}
if(isFound) {
System.out.println("Seems like valid email.");
}
}
}
This code based on your class valid and continue some critical errors. As example : "What happen if user input contains more # characters.
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!
I have an array of 8 strings
(Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi")
all referenced by "county"
I'd prompt the user to input a number of 1-8 (iVal), 1 being Carter, 2 being Cocke, etc...
Is there a way I could do this other than using a switch statement?
Also, how would I go about this if the user were to input Washington I'd display "Washington is in the array" and the opposite if the string isn't in the array?
Thanks in advance.
Here is my array.
String [] county = {"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
for (int i = 0; i< county.length; i++)
{
System.out.print (county [i]+ "\n");
}
To prompt the user to enter a county, and then display it (without a switch) is simple enough. You could use something like,
String[] county = { "Carter", "Cocke", "Washington", "Greene",
"Hawkins", "Johnson", "Sullivan", "Unicoi" };
Scanner scan = new Scanner(System.in);
for (int i = 0; i < county.length; i++) {
System.out.printf("%d %s%n", i + 1, county[i]);
}
System.out.println("Please select a county from above: ");
int choice = scan.nextInt();
if (choice > 0 && choice <= county.length) {
System.out.println("You selected: " + county[choice - 1]);
} else {
System.out.println("Not a valid choice: " + choice);
}
As for testing if a String array contains a particular String you could write a utility function using the for-each loop like
public static boolean contains(String[] arr, String val) {
if (arr != null) {
for (String str : arr) {
if (str.equals(val)) {
return true;
}
}
}
return false;
}
i was working on the same thing, use ArrayList. this was my code
import java.util.*;
public class Practice{
public static void main(String[] args){
ArrayList<String> mylist = new ArrayList<>();
mylist.add("Maisam Bokhari");
mylist.add("Fawwad Ahmed");
mylist.add("Ali Asim");
mylist.add("Maheen Hanif");
mylist.add("Rimsha Imtiaz");
mylist.add("Mugheer Mughal");
mylist.add("Maaz Hussain");
mylist.add("Asad Shahzada");
mylist.add("Junaid Khan");
System.out.println("Name of the student: "+mylist);
}
}
now if u want a specific name from the list put this in system.out.println
System.out.println("Name of the student: "+mylist.get(1));
now the trick is to let the user enter the number in get( )
for this i made this program, here is the code
first make a scanner
Scanner myScan = new Scanner(System.in);
int a = myScan.nextInt();
System.out.println("Name of the student: "+mylist.get(a));
now it will only print that name depending on what number user have entered !!
I didn't understand well your questions, but I am going to answer on what I have understand.
In case you want to print the value of a given index by the user here is the solution:
Try an i with correct (existing) index and another one which does not exist e.g i=9
public class app
{
public static void main(String[] args)
{
String [] county ={"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
int i = 10; //i is the user input, you should do that using a BufferedReader or Scanner.
try
{
System.out.println(county[i-1]);
}
catch(IndexOutOfBoundsException e)
{
System.out.println("This index doesn't exist");
}
}
}
In case you want to check if a given word exist you can do it that way:
Again try a string which exist and one which does not exist.
public class app
{
public static void main(String[] args)
{
String [] county = {"Carter","Cocke","Washington","Greene","Hawkins","Johnson","Sullivan","Unicoi"};
String word = "Cocke"; //word is the user input, you should do that using a BufferedReader or Scanner.
boolean found = false;
for(int i=0; i<=7; ++i)
{
if(word == county[i])
{
found = true;
break;
}
}
if(found == true)
{
System.out.println(word + " is in the array.");
}
else
{
System.out.println(word + " is not in the array.");
}
}
}
EDIT--VERSION
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.
Below is what I have so far...
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;
}
}
public static boolean checkPasswordLetter(String password){
for (int i = 0; i < password.length();){
if (!Character.isLetter(password.charAt(i))){
return false;
}
}
return true;
}
Here you didn't increment variable i , need in for i++ or your loop is going forever if is not letter, same and in checkPasswordDigit
checkPasswordLetter and checkPasswordDigit will only return true if ALL chars are letters/digits respectively. Is this what you meant?
First off... It's not that Java is not looping or checking Boolean. Java is doing what you are telling it to do.
Now, what you want to do is different than what you are doing.
What you need to do is something like:
public static void main(String[] args) {
// ...
String password = enterPassword();
while ( !isPasswordValid(password) ) {
password = enterPassword();
}
System.out.println("Username and Password Accepted!");
}
public static boolean isPasswordValid(String password) {
// return true if and only if password:
// 1. has 6-10 characters
// 2. contains at least one digit
// 3. contains at least one character
// print messages accordingly
}
There are two things wrong.
Your letter checking is failing on the first non-letter. Same thing happening with your digit checking. You only want to reject if every character is a non-letter, for example. So logic error.
You have three loops. Bad idea, because if you pass the length check once, it is never going to be checked again. Consider what would happen if someone entered: 12345678. Length ok, but no letter. Ok, now enter: a1. Length not checked again.
import java.util.Scanner;
import java.util.*;
import java.lang.String;
import java.lang.Character;
public class CheckingPassword
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter a Password: ");
String password = input.next();
if (isValid(password)) {
System.out.println("Valid Password");
} else {
System.out.println("Invalid Password");
}
}
public static boolean isValid(String password) {
if (password.length() < 9) {
return false;
}
else {
char c = 0 ;
int count=0;
System.out.println(password.length());
for (int i = 0;i<=password.length()-1; i++)
{
c = password.charAt(i);
System.out.println(c);
if (!Character.isLetterOrDigit(c))
{
return false;
}
else if (Character.isDigit(c))
{
count++;
if(count==3)
{
return false;
}
}
}
return true;
}
}
}
import java.util.Scanner;
public class password{
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Prompt the user to enter a string
System.out.print("Enter a password ") ;
String s = input.nextLine();
if(isValid(s))
System.out.println(s + " is a valid password");
else
System.out.println(s + " is not a valid password");
}
public static boolean isValid(String s )
{
int i = 0,j=0;
if(s.length()>=8)
{
for(i=0;i<s.length();i++)
{
//if(Charcter.isLetter(s.charAt(i))||Digit.isLetter(s.charAt(i)))
if (Character.isLetterOrDigit(s.charAt(i)))
{
if(Character.isDigit(s.charAt(i)))
j++;
}
}
}
else
return false;
if(j>=2)
return true;
return false;
} }