Here is a simple version without any loops. How can I make it loop like "Wrong password. Try again." until user puts the right password instead stopping the program
(or give them 3 chances before it stops)?
import java.util.Scanner;
public class helloworld2
{
public static void main(String[] arg)
{
Scanner q = new Scanner(System.in);
long Pass;
boolean auth = true;
System.out.println("Enter Password :");
Pass = q.nextLong();
if ( Pass != 1234 )
{
System.out.println("Wrong Password!");
auth = false;
}
else
{
System.out.println("Password Confirmed.");
auth = true;
}
if (auth) {
////blablabla
}
else
{
return;
}
}
}
public class helloworld2
{
public static void main(String[] arg)
{
Scanner q = new Scanner(System.in);
long Pass;
boolean auth = true;
boolean rightPassword = false;
while(!rightPassword){//repeat until passwort is correct
System.out.println("Enter Password :");
Pass = q.nextLong();
if ( Pass != 1234 )
{
System.out.println("Wrong Password!");
auth = false;
}
else
{
rightPassword = true;//let the loop finish
System.out.println("Password Confirmed.");
auth = true;
}
}
// Here do what you want to do
//because here the user has entered a right password
}
}
Related
(formatting is off, couldn't post how I copied and pasted from eclipse)
I'm trying to verify the username before moving on to ask for password, I tried splitting username and password out in a service subclass, but that didn't work. Right now, it's going right from username to asking for password even if the username is not stored in the txt file I have it reading form. Here is what I have so far:
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class LoginConsole {
public static User[] loginUsers = new User[4];
private static UserService userService = new UserService();
public static void main (String[] args) throws IOException {
ReadFile();
Scanner input = null;
try {
input = new Scanner(System.in);
boolean validInput = false;
int attempts = 0;
while (!validInput && attempts != 5) {
System.out.println("Enter your username:");
String username = input.nextLine();
System.out.println("Enter your password:");
String password = input.nextLine();
User found = userService.yesFound(username, password);
if (found != null) {
System.out.println("Welcome: " + found.getName());
validInput = true;
break;
} if(attempts < 4) {
System.out.println("Invalid input, please try again!");
attempts++;
} else {
System.out.println("Too many failed attempts, you are
now locked out!");
break;
}
}
} finally {
if (input != null)
input.close();
}
}
private static void ReadFile() throws IOException, FileNotFoundException {
String verInput = "data.txt";
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(verInput));
String currLine;
int i = 0;
while ((currLine = reader.readLine()) != null) {
loginUsers[i] = new User(currLine.split(","));
i++;
}
} finally {
if (reader != null)
reader.close();
}
}
}
Since you're trying to verify username before password, then you should validate before you ask for the password.
System.out.println("Enter your username:");
String username = input.nextLine();
// Validate Username here. (example ..)
User user = userService.findUser(username); // you can create a method dedicated to find user.
if(user != null) {
System.out.println("Enter your password:");
String password = input.nextLine();
...
}
I have recently started working on this program, and I'm new to inter-thread communications such as wait and notify. However when I run this, the notify doesn't seem to execute correctly. Here is the code: (sorry about the extra stuff)
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws InterruptedException {
Main console = new Main();
console.restart();
}
public void restart() throws InterruptedException {
Scanner restartinput = new Scanner(System.in);
System.out.println("System has been restarted");
System.out.println("Restarting requires an admin restart password.");
System.out.println("You may also login as a normal user to reboot but will cause that account to be temporarily locked.");
System.out.println("Enter 1 for normal user, 2 for admin");
String input12 = restartinput.nextLine();
boolean lockall = false;
if (input12.equals("1")) {
System.out.println("Enter username:");
String input13 = restartinput.nextLine();
if (input13.equals("normalusertest")) {
boolean passwordgotten2 = false;
while (passwordgotten2 == false) {
// Not perfect hash function, some Strings and numbers have the same hash.
int realhashedpassword2 = 1544190;
System.out.println("PIN:");
Scanner input = new Scanner(System.in);
String enteredpassword2 = input.nextLine();
String plaintextguess2 = new String(enteredpassword2);
if (plaintextguess2.hashCode() == realhashedpassword2) {
System.out.println("Access granted.");
passwordgotten2 = true;
} else if (plaintextguess2.equals("/override")) {
System.out.println("Admin override password:");
String overridepasswordguess2 = input.nextLine();
if (overridepasswordguess2.hashCode() == 843331265) {
System.out.println("Access granted.");
passwordgotten2 = true;
} else {
System.out.println("Access denied.");
System.exit(0);
}
} else {
System.out.println("Access denied. Incorrect password");
}
}
for (int w = 0; w <= 45; w++) {
System.out.println(".");
}
fulllogin(0, 1);
} else {
System.out.println("That is not a normal username");
}
}
if (input12.equals("2")) {
boolean gottenpassword3 = false;
while (gottenpassword3 == false) {
System.out.println("Enter the restart password:");
String input8 = restartinput.nextLine();
if (input8.hashCode() == 48818447) {
System.out.println("Access granted.");
System.out.println("Restarting.");
for (int j = 0; j <= 45; j++) {
System.out.println(".");
}
gottenpassword3 = true;
}
}
fulllogin(0, 0);
}
}
public void fulllogin(int lockall, int locknormalusertest) throws InterruptedException {
int lockall1 = lockall;
int locknormalusertest1 = locknormalusertest;
Scanner usernameScanner = new Scanner(System.in);
System.out.println("Username:");
String inputtedusername = usernameScanner.nextLine();
String username = login(inputtedusername, lockall1, locknormalusertest1);
int currentadministrativelevel = 0;
if (username.equals("admintest")) {
currentadministrativelevel = 2;
}
if (username.equals("normalusertest")) {
currentadministrativelevel = 1;
}
runCommands(username, currentadministrativelevel, lockall, locknormalusertest);
}
public void runCommands(String username, int administrativelevel, int lockall, int locknormalusertest) throws InterruptedException {
int currentadministrativelevel = administrativelevel;
System.out.println("Command:");
Scanner commandinput = new Scanner(System.in);
String input2 = commandinput.nextLine();
if (input2.equals("/manage")) {
if (currentadministrativelevel == 2) {
System.out.println("1 user to manage");
System.out.println("Enter 1 to manage normalusertest");
if (commandinput.nextLine().equals("1")) {
System.out.println("1 to view data, 2 to manage password, 3 to lock/unlock user");
String input1 = commandinput.nextLine();
if (input1.equals("1")) {
System.out.println("No data to view currently");
}
if (input1.equals("2")) {
System.out.println(
"To log in to this account use '/override' as the password. The admin override password is the square of the password for this account.");
}
if (input1.equals("3")) {
System.out.println("'/lock' or '/unlock'");
System.out.println("Command:");
String input10 = commandinput.nextLine();
if (input10.equals("/lock")) {
System.out.println("Reenter password to confirm lock:");
System.out.println("Reenter PIN:");
String input9 = commandinput.nextLine();
if (input9.hashCode() == 1662305) {
System.out.println("Locking normalusertest.");
for (int o = 0; o <= 45; o++) {
System.out.println(".");
}
fulllogin(lockall, 1);
}
}
if (input10.equals("/unlock")) {
System.out.println("Reenter password to confirm unlock:");
System.out.println("Reenter PIN:");
String input11 = commandinput.nextLine();
if (input11.hashCode() == 1662305) {
System.out.println("Unlocking normalusertest.");
for (int p = 0; p <= 45; p++) {
System.out.println(".");
}
fulllogin(lockall, 0);
}
}
}
}
}
if (currentadministrativelevel == 1) {
System.out.println("No users to manage.");
}
}
if (input2.equals("/chat")) {
System.out.println("'/view' or '/send'");
String input14 = commandinput.nextLine();
if (input14.equals("/send")) {
System.out.println("Enter a user to send a message to. Capitalization matters.");
String input15currenttouser = commandinput.nextLine();
System.out.println("Message:");
String input16currentmessage = commandinput.nextLine();
try {
sendMessage(username, input15currenttouser, input16currentmessage, lockall, locknormalusertest);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (input14.equals("/view")) {
synchronized (this) {
boolean viewed = true;
notifyAll();
Thread.sleep(15000);
}
}
}
if (input2.equals("/logout")) {
System.out.println("Logging out.");
;
for (int i = 0; i <= 45; i++) {
System.out.println(".");
}
fulllogin(lockall, locknormalusertest);
} else {
runCommands(username, currentadministrativelevel, lockall, locknormalusertest);
}
}
public String login(String username, int lockall, int locknormalusertest) throws InterruptedException {
if (username.equals("normalusertest") && (lockall == 1 || locknormalusertest == 1)) {
System.out.println("This account has been temporarily locked.");
fulllogin(lockall, locknormalusertest);
}
if (username.equals("normalusertest") && lockall == 0 && locknormalusertest == 0) {
boolean passwordgotten = false;
while (passwordgotten == false) {
// Not perfect hash function, some Strings and numbers have the same hash.
int realhashedpassword = 1544190;
System.out.println("PIN:");
Scanner input = new Scanner(System.in);
String enteredpassword = input.nextLine();
String plaintextguess = new String(enteredpassword);
if (plaintextguess.hashCode() == realhashedpassword) {
System.out.println("Access granted.");
passwordgotten = true;
} else if (plaintextguess.equals("/override")) {
System.out.println("Admin override password:");
String overridepasswordguess = input.nextLine();
if (overridepasswordguess.hashCode() == 843331265) {
System.out.println("Access granted.");
passwordgotten = true;
} else {
System.out.println("Access denied.");
System.exit(0);
}
} else {
System.out.println("Access denied. Incorrect password");
}
}
return "normalusertest";
}
if (username.equals("admintest")) {
boolean passwordgotten = false;
while (passwordgotten == false) {
// Not perfect hash function, some Strings and numbers have the same hash.
int realhashedpassword = 1662305;
System.out.println("PIN:");
Scanner input = new Scanner(System.in);
String enteredpassword = input.nextLine();
String plaintextguess = new String(enteredpassword);
if (plaintextguess.hashCode() == realhashedpassword) {
System.out.println("Access granted.");
passwordgotten = true;
} else {
System.out.println("Access denied. Incorrect password");
}
}
return "admintest";
} else {
System.out.println("Invalid username");
return "error";
}
}
public void sendMessage(String fromuser, String touser, String message, int lockall, int locknormalusertest) throws InterruptedException {
synchronized (this) {
fulllogin(lockall, locknormalusertest);
boolean viewed = false;
while (viewed == false) {
wait();
}
System.out.println("notify test");
}
}
}
After /view is typed, the program just waits and then has "Command:" again, even though it should be printing "notify test".
I didn't grasp the whole concept of the application, but two issues seem apparent:
You're not starting any threads, therefore, there won't be any
inter-thread communications, because the only thread you'll have is
Main. Running your application on multiple threads could be
achieved, for example, by having Main extend Thread, creating
multiple instances in your static main method, and calling
start() on each. (This is just a technical example that most
likely wouldn't be appropriate for your needs, as you wouldn't want
to start printing to the console from multiple threads.)
The following synchronized blocks are trying to communicate via a
boolean viewed, but since they're each creating it as their own
local variable, they never get to each other:
synchronized (this) {
fulllogin(lockall, locknormalusertest);
boolean viewed = false;
while (viewed == false) {
wait();
}
System.out.println("notify test");
}
// ...
synchronized (this) {
boolean viewed = true;
notifyAll();
Thread.sleep(15000);
}
Threads need to communicate via data that's scoped appropriately to be
accessible to all of them. For example, if you create the threads as in my
example in #1, you can create a static field on Main and all
instances will have access to that.
public class Main {
// The 'static' keyword makes this variable available to all Main instances
private static boolean viewed = false;
// ...
I'd suggest that you read up on Java scopes and dig into this excellent resource to get a better grasp on the concepts of multithreading: http://tutorials.jenkov.com/java-concurrency/index.html
In my program, I have a FacebookUser class that has an ArrayList of all of that user's friends. All of those friends may also have friends. I am using recursion to get a new ArrayList that contains all of the user's friends and all of the user's friends' friends and so on. I also serialized the FacebookUser class so I can save the data. Without the new recursive method, I can serialize without error and the data persists over executions. With the recursive method, though, I get an InvalidClassException. It shows that the exception is at the line that uses the ObjectInputStream to get the FacebookUser from memory.
I'm not understanding why the new method is causing the exception to be thrown from another method. I believe the problem lies only in the FacebookUser.java class (since getRecommendations is recursive method) but I thought it'd be best to also show the UserAccount.java class since the former extends the latter. Any help will be appreciated. Thank you.
Execution:
Exception in thread "main" java.io.InvalidClassException: FacebookUser; local class incompatible: stream classdesc serialVersionUID = 4110981517967863740, local class serialVersionUID = 5032562666539812166
at java.base/java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.base/java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.base/java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.base/java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.base/java.io.ObjectInputStream.readObject0(Unknown Source)
at java.base/java.io.ObjectInputStream.readObject(Unknown Source)
at FacebookUser.readFile(FacebookUser.java:157)
at DriverClass.main(DriverClass.java:12)
FacebookUser.Java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class FacebookUser extends UserAccount implements Serializable{
private String passwordHint;
private ArrayList<FacebookUser> friends;
public FacebookUser(String username, String password) {
super(username, password);
friends = new ArrayList<FacebookUser>();
}
#Override
public void getPasswordHelp() {
System.out.println("Password Hint: " + passwordHint);
}
public void getPasswordHelp(String username) {
if (friends.size() == 0) {
System.out.println("There is no user with that username.");
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
friends.get(i).getPasswordHelp();
break;
}
if (i == friends.size() - 1) {
System.out.println("There is no user with that username.");
break;
}
}
}
}
void setPasswordHint(String hint) {
passwordHint = hint;
}
void friend(FacebookUser newFriend) {
if (friends.contains(newFriend)) {
System.out.println("That person is already your friend.");
} else {
friends.add(newFriend);
}
}
void friend(String username) {
Scanner s = new Scanner(System.in);
if (friends.size() == 0) {
System.out.println("Please create a password: ");
String password = s.nextLine();
System.out.println("Please create a password hint: ");
String passHint = s.nextLine();
FacebookUser fbu = new FacebookUser(username, password);
fbu.setPasswordHint(passHint);
friends.add(fbu);
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
System.out.println("That person is already your friend.");
break;
}
if (i == friends.size() - 1) {
System.out.println("Please create a password: ");
String password = s.nextLine();
System.out.println("Please create a password hint: ");
String passHint = s.nextLine();
FacebookUser fbu = new FacebookUser(username, password);
fbu.setPasswordHint(passHint);
friends.add(fbu);
break;
}
}
}
}
void defriend(FacebookUser formerFriend) {
if (friends.contains(formerFriend)) {
friends.remove(formerFriend);
} else {
System.out.println("That person is not your friend.");
}
}
void defriend(String username) {
Scanner s = new Scanner(System.in);
if (friends.size() == 0) {
System.out.println("That person is not your friend.");
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
System.out.println("Password for " + username + ": ");
String passw = s.nextLine();
if (friends.get(i).getPassword().equals(passw)) {
friends.remove(i);
break;
} else {
System.out.println("Incorrect Password");
break;
}
}
if (i == friends.size() - 1) {
System.out.println("That person is not your friend.");
break;
}
}
}
}
ArrayList<FacebookUser> getRecommendations(FacebookUser friend) {
ArrayList<FacebookUser> recFriends = new ArrayList<FacebookUser>();
for (int i = 0; i < friend.getFriends().size(); i++) {
for (int j = 0; j < recFriends.size(); j++) {
for (int k = 0; k < recFriends.size(); k++) {
if (recFriends.get(j).equals(recFriends.get(k))) {
recFriends.remove(j); // This removes any duplicate friends so there won't be an infinite loop.
break;
}
}
}
recFriends.addAll(friend.getFriends().get(i).getRecommendations(friend)); // This adds the friends' friends' friends and so on into the ArrayList.
}
return recFriends;
}
ArrayList<FacebookUser> getFriends() {
ArrayList<FacebookUser> friendsCopy = new ArrayList<FacebookUser>();
for (int i = 0; i < friends.size(); i++) {
friendsCopy.add(friends.get(i));
}
Collections.sort(friendsCopy, new Comparator<FacebookUser>() {
#Override
public int compare(FacebookUser fb1, FacebookUser fb2) {
return fb1.toString().compareToIgnoreCase(fb2.toString());
}
});
return friendsCopy;
}
public static void writeToFile(FacebookUser facebookUser) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("FacebookUser.bin"));
oos.writeObject(facebookUser); // This saves the data.
}
public static FacebookUser readFile() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("FacebookUser.bin"));
FacebookUser facebookUser = (FacebookUser) ois.readObject(); // This reads in the data which is called in the DriverClass class line 12.
return facebookUser;
}
}
UserAccount.java
import java.io.Serializable;
public abstract class UserAccount implements Serializable{
private String username;
private String password;
private boolean active;
public UserAccount(String username, String password) {
this.username = username;
this.password = password;
active = true;
}
public boolean checkPassword(String password) {
if (password.equals(this.password)) {
return true;
} else {
return false;
}
}
public void deactivateAccount() {
active = false;
}
public String getPassword() {
return password;
}
public String toString() {
return username;
}
public boolean checkActive() {
if (active == true) {
return true;
} else {
return false;
}
}
public abstract void getPasswordHelp();
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserAccount other = (UserAccount) obj;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
}
DriverClass.java
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class DriverClass {
public static void main(String[] args) throws IOException, ClassNotFoundException {
int choice = 0;
String username;
FacebookUser fu0;
try {
fu0 = FacebookUser.readFile();
} catch (FileNotFoundException e) {
fu0 = new FacebookUser("Robert", "password1");
}
while (choice != 5) {
System.out.println(
"1. List Users \n2. Add a User \n3. Delete a User \n4. Get Password Hint \n5. Get Recommendations \n6. Quit");
Scanner s = new Scanner(System.in);
choice = s.nextInt();
switch (choice) {
case 1:
System.out.println(fu0.getFriends());
break;
case 2:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.friend(username);
break;
case 3:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.defriend(username);
break;
case 4:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.getPasswordHelp(username);
break;
case 5:
System.out.println(fu0.getRecommendations(fu0));
break;
case 6:
FacebookUser.writeToFile(fu0);
break;
}
}
}
}
The exception suggests that the SerialVersionUID the JVM generated differs for some instances of the FacebookUser object. If you make your class implement Serializable, it is highly recommended that you explicitly declare the SerialVersionUID variable to avoid exceptions like these.
So in the FacebookUser class you should declare a variable like this:
private static final long serialVersionUID = 42L;
See this answer for more details.
I'm creating an app in which I need to create account and log into first.
I thought that I can use HashMap for it, where login is my key and password is my value.
Unfortunately, I've got problem with log into account that I've created.
Here is class with methods that take responsible for log. There is problem with checkIfLoginDataIsIncorrect
void inputLoginAndPassword() {
System.out.println("Input your login");
login = input.next();
System.out.println("Input your password");
password = input.next();
}
boolean checkIfLoginDataIsIncorrect() {
if (loginDetails.containsKey(login)
&& loginDetails.get(login).equals(password)) {
System.out.println("You've logged in.");
return false;
}
else
System.err.println("Bad login or password");
return true;
}
Main.java:
AccountMaker accountMaker = new AccountMaker();
AccountLogger accountLogger = new AccountLogger();
//I'VE WRITTEN IT JUST FOR CHECK:
HashMap<String, String> loginDetails = accountMaker.getLoginDetails();
loginDetails.put("lala","papa");
[...]
case 2:
while (loopIsTrue) {
accountLogger.inputLoginAndPassword();
if(!accountLogger.checkIfLoginDataIsIncorrect()) {
loopIsTrue = false;
} else {
loopIsTrue = true;
}
}
break;
AccountMaker.java:
public class AccountMaker {
private HashMap<String, String> loginDetails = new HashMap<>();
private String login, password;
private Scanner input = new Scanner(System.in);
[...]
HashMap<String, String> getLoginDetails() {
return loginDetails;
}
}
AccountLogger.java:
public class AccountLogger {
private AccountMaker accountMaker = new AccountMaker();
private Scanner input = new Scanner(System.in);
private HashMap<String, String> loginDetails = accountMaker.getLoginDetails();
private String login, password;
void inputLoginAndPassword() {
System.out.println("Input your login");
login = input.next();
System.out.println("Input your password");
password = input.next();
}
boolean checkIfLoginDataIsIncorrect() {
//I'VE WRITTEN IT JUST FOR CHECK
System.out.println(login);
System.out.println(password);
///
if (loginDetails.containsKey(login) && loginDetails.get(login).equals(password)) {
System.out.println("You've logged in.");
return false;
}
else
System.err.println("Bad login or password");
return true;
}
}
For example, if I write loginDetails.put("lala","papa"); and then I want to log into this acc program says Bad login or password.
The issue you're running into is you're polling the wrong HashMap
Create AccountMaker
The AccountMaker makes a new HashMap
Create 'AccountLogger'
The AccountLogger makes a new AccountMaker
The AccountMaker makes a new HashMap
We end up with two different instances of AccountMaker, and their different HashMaps
Try using the same AccountMaker that your AccountLogger uses, or pass it to the constructor
Using constructor:
//Main.java
AccountMaker accountMaker = new AccountMaker();
AccountLogger accountLogger = new AccountLogger(accountMaker);
//AccountLogger.java
class AccountLogger
{
private AccountMaker accountMaker;
public AccountLogger(AccountMaker maker)
{
accountMaker = maker;
}
}
Getting the same AccountMaker:
//Main.java
AccountLogger accountLogger = new AccountLogger();
AccountMaker accountMaker = accountLogger.getAccountMaker();
//AccountLogger.java
public AccountMaker getAccountMaker()
{
return accountMaker;
}
I am trying to understand your problem and have written below sample program to meet your requirement. Compare your code and see if you can fix your issue. If not, can you modify below code and let me know where it is failing.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Testlogin {
static Scanner input = new Scanner(System.in);
static Map<String, String> loginDetails = new HashMap<String, String>();
static String login,password;
static void inputLoginAndPassword() {
System.out.println("Input your login");
login = input.next();
System.out.println("Input your password");
password = input.next();
}
boolean checkIfLoginDataIsIncorrect() {
if (loginDetails.containsKey(login)
&& loginDetails.get(login).equals(password)) {
System.out.println("You've logged in.");
return false;
}
else
System.err.println("Bad login or password");
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
loginDetails.put("lala", "papa");
inputLoginAndPassword();
boolean loopIsTrue =true;
Testlogin testlogin = new Testlogin();
while (loopIsTrue) {
// Testlogin.inputLoginAndPassword();
System.out.println("You have entered login = "+login);
System.out.println("You have entered password = "+password);
if(!testlogin.checkIfLoginDataIsIncorrect()) {
loopIsTrue = false;
} else {
inputLoginAndPassword(); // bad login detected so asking for correct details again.
loopIsTrue = true;
//
}
}
//break;
}
}
I am creating a simple login program in java. Here is the code i have so far.
import java.util.Scanner;
import java.io.*;
import java.util.Arrays;
public class PasswordProgram {
public static String user;
public String password;
public static boolean part1Finish = false;
public File file = new File("D:/file.txt");
public FileWriter UsernameWrite;
public char[] user1;
public void part1() {
System.out.println("Please create an account: ");
Scanner input = new Scanner(System. in );
System.out.println("Type in a username: ");
String user = input.next();
System.out.println("Type in a Password: ");
String password = input.next();
try {
UsernameWrite = new FileWriter(file);
UsernameWrite.write(user);
UsernameWrite.write(password);
System.out.println(user);
UsernameWrite.close();
part1Finish = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void part2() {
Scanner scan = new Scanner(System. in );
System.out.println("Please confirm your username: ");
String usercheck = scan.next();
int PassAttempts = 5;
int UserAttempts = 5;
user1 = user.toCharArray();
user1 = password.toCharArray();
char[] usernamecheck = java.util.Arrays.copyOfRange(user1, 0, user.length());
System.out.println(usernamecheck);
do {
if (usercheck.equals(usernamecheck)) {
while (PassAttempts > 0) {
System.out.println("Please confirm your password: ");
String passcheck = scan.next();
if (passcheck.equals(password)) {
System.out.println("Thank You ");
} else if (passcheck != password && PassAttempts > 0) {
PassAttempts--;
System.out.println("That is incorrect. Please Try Again");
passcheck = scan.nextLine();
} else {
System.out.println("You have run out of Password Attempts");
break;
}
}
} else if (usercheck != user && UserAttempts > 0) {
UserAttempts--;
System.out.println("That is an incorrect username. Please Try Again");
usercheck = scan.nextLine();
} else {
System.out.println("You have run out of Username Attempts");
break;
}
} while (UserAttempts > 0);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
PasswordProgram login = new PasswordProgram();
login.part1();
if (part1Finish == true) {
login.part2();
}
}
}
The problem i am getting is in the method part2. Here when I try to add the username that was saved under the variable user into a character array to use it as a range I get the error NullPointerException.
After investigating i see that when running part2 the value of user is null and therefore I get the error.
Is there a way I could do this through the FileReader method instead or how can i fix the current error I am getting ? Thank you.
Because the static field user is never assigned in part1, you get a NullPointerException when you try to use it in part2.
There are also other issues in the posted code:
why there is a file involved is unclear
you use != with String, for example in passcheck != password
you use equals between String and char[] in usercheck.equals(usernamecheck)
passcheck is assagned but never used
local variables (because of their names) are hiding some fields
UsernameWrite and UserAttempts have non conventional names (should be usernameWrite and userAttempts
You have two user variables declared, one which is static and has global scope, another which is local to part1(). When part2() is attempting to access user, it is using the static declaration, which is null. Your modifications to user in part1() are done to the local variable.
This is something called variable shadowing and should be avoided at all costs.
See the below example:
class Ideone
{
static String bla = "test1";
public static void myMethod() {
String bla = "test2";
System.out.println(bla);
}
public static void main (String[] args) throws java.lang.Exception
{
myMethod();
System.out.println(bla);
}
}
It outputs:
test2
test1