Im having trouble getting the program to read the info in a text file and compare it to user input. If the input and text match a menu will then be displayed if not the user will be locked out. I heard of a buffer line, but I'm not sure how it works. Any help will be appreciated!!
import java.util.Scanner;
import java.io.*;
public class test123{
public static void main(String[] args)throws IOException {
Scanner sc1 = new Scanner (System.in);
System.out.println("Please enter correct credentials to log in");
System.out.println("Username: ");
System.out.println("Password: ");
String userName = sc1.nextLine();
String passWord = sc1.nextLine();
File inFile = new File ("employee.txt");
while (sc1.hasNextLine())
{
Scanner sc = new Scanner (inFile);
String [] arrayName= new String [4];
String uName = arrayName[0];
String pWord = arrayName[1];
String line = sc.nextLine();
line = sc.nextLine();
if(userName.equals(uName) && passWord.equals(pWord))
{
System.out.println("Welcome " + userName + "!");
System.out.println("Menu: ");
System.out.println("\t1) Account");
System.out.println("\t2) Payroll");
System.out.println("\t3) Attendance Report");
System.out.println("\t4) Service Desk");
}
}
}
}
Your Scanner sc = new Scanner(inFile); should be outside your while loop.
Also check out this resource : https://www.geeksforgeeks.org/different-ways-reading-text-file-java/
If I understand correctly, you are checking if a user's username and password is correct or not!. This might work
public static void main(String[] args)throws IOException {
Scanner sc1 = new Scanner (System.in);
System.out.println("Please enter correct credentials to log in");
System.out.println("Username: ");
System.out.println("Password: ");
String userName = sc1.nextLine();
String passWord = sc1.nextLine();
File inFile = new File ("employee.txt");
Scanner sc = new Scanner (inFile);
String uName = sc.nextLine();
String pWord = sc.nextLine();
sc.close();
if(userName.equals(uName) && passWord.equals(pWord))
{
System.out.println("Welcome " + userName + "!");
System.out.println("Menu: ");
System.out.println("\t1) Account");
System.out.println("\t2) Payroll");
System.out.println("\t3) Attendance Report");
System.out.println("\t4) Service Desk");
}
else {
System.out.println("Error.!");
}
}
Well if you had empty lines in file or no text in file etc., this will not work as expected.
Related
I am trying to run this code where it reads a file and sorts the words by the tabs in between the words.
File Example
Area Word Area Word Area 1111 Word
public static void start() throws FileNotFoundException {
// Create Empty address book
AddressBook book = new AddressBook();
Scanner scnr = new Scanner(System.in);
String filename = "contacts.txt";
addContactfromFile(book,filename);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
// Insert contacts FEATURE
System.out.println("------------------------INSERTING CONTACT--------------------------------");
int ans = 0;
System.out.println("Would you like to insert a Contact? 1 or 2");
ans = scnr.nextInt();
scnr.nextLine();
if(ans == 1){
System.out.println("What is the First name");
String f = scnr.nextLine();
System.out.println("What is the Last name");
String l = scnr.nextLine();
System.out.println("What is the Number name");
String n = scnr.nextLine();
System.out.println("What is the Address name");
String a = scnr.nextLine();
System.out.println("What is the City name");
String c = scnr.nextLine();
System.out.println("What is the State name");
String s = scnr.nextLine();
System.out.println("What is the Zip Code name");
int z = scnr.nextInt();
book.insertContact(f,l,n,a,c,s,z);
System.out.println("Contact has been added!");
}else {
System.out.println("Ok");
}
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// search FEATURE
System.out.println("------------------------SEARCHING CONTACT--------------------------------");
addContactfromFile(book, "contacts.txt");
checkSearch(book);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// delete Contact FEATURE
System.out.println("------------------------DELETING CONTACT--------------------------------");
addContactfromFile(book, "contacts.txt");
checkDelete(book);
System.out.println("Number of Contacts" +book.getNumberOfContacts());
System.out.println("Now emptying the Address Book");
book.emptyAddressBook();
// Check if address book is empty FEATURE
addContactfromFile(book, "contacts.txt");
System.out.println("Is the Address Book Empty: "+book.isAddressBookEmpty());
System.out.println(book.getNumberOfContacts());
}
public static void checkSearch(AddressBook book) throws FileNotFoundException{
Scanner scnr = new Scanner(System.in);
System.out.println("Who would like to look for?'First name'");
String first = scnr.nextLine();
System.out.println("Who would like to look for?'Last name'");
String last = scnr.nextLine();
try{
Contact c = book.searchContact(first,last);
System.out.println(c.getFirstName()+ " " + c.getAddress().getStreet());
}catch (Exception e){
System.out.println(e);
System.out.println("Contact isnt there");
}
}
public static void checkDelete(AddressBook book) throws FileNotFoundException{
Scanner scnr = new Scanner(System.in);
System.out.println("Enter First Name");
String first = scnr.nextLine();
System.out.println("Enter Last Name");
String last = scnr.nextLine();
try{
book.deleteContact(first,last);
}catch (Exception e){
System.out.println(e);
System.out.println("Didnt work");
}
}
public static void addContactfromFile(AddressBook book, String filename) throws NumberFormatException, FileNotFoundException{
Scanner reader = new Scanner(new File(filename));
while(reader.hasNextLine()) {
String contactString = reader.nextLine();
String[] contactElementStrings = contactString.split("\t");
int zipcode = Integer.parseInt(contactElementStrings[5]);
Address address = new Address(contactElementStrings[2],contactElementStrings[3],contactElementStrings[4],zipcode);
Contact contact = new Contact(contactElementStrings[0],contactElementStrings[1],address,contactElementStrings[6]);
book.insertContact2(contact);
}
}
The Error I receive from this is:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Helper.addContactfromFile(Helper.java:106)
at Helper.start(Helper.java:16)
at Driver.main(Driver.java:17)
contactElementStrings[5] contains an empty string.
Integer.parseInt(contactElementStrings[5]) is throwing NumberFormatException because an empty string cannot be parsed to an int.
Add a check to see whether contactElementStrings[5] can be parsed to an int.
int zipcode;
if (contactElementStrings.length > 6) {
if (contactElementStrings[5] != null && !contactElementStrings[5].isEmpty()) {
zipcode = Integer.parseInt(contactElementStrings[5]);
}
else {
zipcode = 0;
}
}
EDIT
From your comment, it appears that there are lines that don't contain all the fields that you expect. Hence you also need to check whether the split line contains all the expected parts. I have edited the above code to also check whether the split line contains all the expected parts.
I can't get this login system to work. I want the program when run to display,
Username:
Password:
and I want to then enter credentials.
Here is my code:
import java.util.Scanner;
public class Customer {
public void Login() {
Scanner sc = new Scanner(System.in);
System.out.print("SUPERMARKET - ONLINE PORTAL LOGIN \n");
System.out.print("Username: ");
System.out.print("\n");
System.out.print("Password: ");
String string = sc.nextLine();
if("hmirza".equals(string) )
{
String string2 = sc.nextLine();
if("mirza".equals(string2) )
{
System.out.print("Logging you in... ");
System.out.print("\n\n\n");
new Products().search();
}
}
sc.close();
}
}
Try this:
public void Login() {
Scanner sc = new Scanner(System.in);
System.out.print("SUPERMARKET - ONLINE PORTAL LOGIN \n");
System.out.print("Username: ");
String username = sc.nextLine();
System.out.print("\n");
System.out.print("Password: ");
String password = sc.nextLine();
if ("hmirza".equals(username)) {
if ("mirza".equals(password)) {
System.out.print("Logging you in... ");
System.out.print("\n\n\n");
new Products().search();
}
}
sc.close();
}
I just started to code in Java and I have a question. After my "else" statement, I want to repeat my code again. How do I do that? Is there a keyword or something?
import java.util.Scanner;
public class UserInputStory {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
userinput:
System.out.println("Enter you name:");
String name = input.nextLine();
System.out.println("OK! Now enter your age:");
int age;
age = input.nextInt();
System.out.println("Good! And the city you live in, please:");
Scanner in = new Scanner(System.in);
String city = in.nextLine();
System.out.println("So, let's check");
System.out.println(
"Your name is " + name + ". You are " + age + " years old and you currently live in " + city + ".");
System.out.println("Is that right?");
Scanner inp = new Scanner(System.in);
String yesno = inp.nextLine();
if (yesno.equals("yes") || yesno.equals("Yes") || yesno.equals("YES")) {
System.out.println("Great job!");
}
else {
System.out.println("Let's try again then!");
}
}
}
Place the body of your code that you want repeating inside a while loop and break when your end-condition is true:
public static void main(String[] args) {
while(true) {
Scanner input = new Scanner(System.in);
userinput:
System.out.println("Enter you name:");
String name = input.nextLine();
System.out.println("OK! Now enter your age:");
int age;
age = input.nextInt();
System.out.println("Good! And the city you live in, please:");
Scanner in = new Scanner(System.in);
String city = in.nextLine();
System.out.println("So, let's check");
System.out.println("Your name is " + name + ". You are " + age + " years old and you currently live in " + city + ".");
System.out.println("Is that right?");
Scanner inp = new Scanner(System.in);
String yesno = inp.nextLine();
if (yesno.equals("yes") || yesno.equals("Yes") || yesno.equals("YES")) {
System.out.println("Great job!");
break;
}
else {
System.out.println("Let's try again then!");
}
}
}
You can envelop our whole code by:
while(1)
ut its not a good approach and there must be some condition applied (depending upon the xontext of your program) which can take you out of the loop
I've a problem with my while loop.
It works fine if the while loop conditions is false(when the password is wrong), but when the password is right it writes both You are logged in and Wrong password.
I understand why it does so but I don't understand how to solve the problem. I need to use a while loop because it's a school assignment that requires it.
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
String scan = scanner.nextLine();
while(scan.equals(rightPassword)){
System.out.println("You are logged in");
break;
}
System.out.println("Wrong password");
}
}
What you should have done is :
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
String scan="";
while(true){
System.out.println("Write your password: ");
scan = scanner.nextLine();
if(scan.equals(rightPassword)) {
System.out.println("You are logged in");
break;
} else {
System.out.println("Wrong password");
}
}
}
}
In this what we do is we have an endless for loop which will not break until you supply the right password. You can add some kin of number of tries to this as a breaking condition too.
Based on the comment I know, it become a infinite loop and that's why i use break. My requirement is that i must use a While loop. I know how to use a if-loop to solve the problem. Your solution should look like :
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
while(!rightPassword.equals(scanner.nextLine())) {
System.out.println("Wrong password");
System.out.println("Write your password: ");
}
System.out.println("You are logged in");
}
}
You can use below code.
int a=1;
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
String scan = scanner.nextLine();
while(scan.equals(rightPassword)){
System.out.println("You are logged in");
a=0;
break;
}
if(a==1){
System.out.println("Wrong password");
}
without changing your code this will help you.
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
String scan = scanner.nextLine();
while(scan.equals(rightPassword)){
System.out.println("You are logged in");
break end;
}
System.out.println("Wrong password");
end:
}
}
You may have a couple of things backwards. Check for a wrong password, not a right one in the loop, and ask for their password again. This way you will receive one message from the system and that's a bad password, or a good one once they 'successfully log in'.
import java.util.Scanner;
public class Password {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String rightPassword = "Hello123";
System.out.println("Write your password: ");
String scan = scanner.nextLine();
while(!scan.equals(rightPassword)){
System.out.println("Wrong password. Please try again");
System.out.println("Write your password: ");
String scan = scanner.nextLine();
}
System.out.println("You are logged in");
}
}
SOLVED!!! Thanks for the hand guys got it working. Appreciate it!
I'm writing a program that has user name and password input. I am trying to check if a file exists for a user if the user puts in a user name that already exists when they create a user name and password.
The .exists method isn't working and I cant figure it out. Error cannot find symbol comes back. I've changed things, moved things around and got it down to one error. Tried using loops as well as if statements but using if gets me to only one error .Any help would be great.
import java.util.Scanner;
import java.io.*;
class UserData
{
public static void main ( String[] args ) throws IOException
{
Scanner kb = new Scanner(System.in);
System.out.println("Do you have an account? Yes or No: ");
String answer = kb.next().trim();
if ((answer.startsWith("N")) || (answer.startsWith("n")))
{
System.out.println("Create user name: ");
String user = kb.next().trim();
String fileName = user + ".txt";
FileWriter userData = new FileWriter(fileName);
if (userData.exists())
{
System.out.println("User already exists");
System.out.println("Create user name: ");
user = kb.next().trim();
fileName = user + ".txt";
userData = new FileWriter(fileName);
}
System.out.println("Create Password: ");
String ps = kb.next().trim();
userData.write(user + " ");
userData.write(ps);
userData.close();
}
else if ((answer.startsWith("Y")) || (answer.startsWith("y")))
{
System.out.println("Enter user name: ");
String user = kb.next().trim();
System.out.println("Enter Password: ");
String ps = kb.next().trim();
String fileName = user + ".txt";
Scanner inFile = new Scanner(new File(fileName));
String userName = inFile.next();
String password = inFile.next();
// If ((userName != user) || (password != ps))
// {
// System.out.println("User Not Found");
// System.out.println("Enter user name: ");
// String user = kb.next().trim();
//
// System.out.println("Enter Password: ");
// String ps = kb.next().trim();
//
// String fileName = user + ".txt";
// Scanner inFile = new Scanner(new File(fileName));
//
// String userName = inFile.next();
// String password = inFile.next();
// }
// else
// {
System.out.println("User Found");
// }
}
}}
You have compilation error here:
FileWriter userData = new FileWriter(fileName);
if (userData.exists())
Change it to:
File userDataFile = new File(fileName);
if (userDataFile.exists())
and of course:
FileWriter userData = new FileWriter(userDataFile);
userData.write(user + " ");
userData.write(ps);
userData.close();
If file doesn't exist anyway, you might be looking in a wrong directory. Try to add this:
System.out.println(new File(fileName).getAbsolutePath());
And check yourself if the file available on the printed path.