NullPointerException on a static attribute - java

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

Related

Java Check if multiple strings are empty

I am trying to add a User into a LinkedList using Java, but I am wondering if there is a shorter way to check if multiple strings are empty instead of using if statements everytime I input a new string
This is the method I came up with
public void addUser() {
int error = 0;
do {
Users user = new Users();
String name = JOptionPane.showInputDialog(null, "Enter your name");
if (name.isEmpty()) {
error = 1;
} else {
String password = JOptionPane.showInputDialog(null, "Enter a password");
if (password.isEmpty()) {
error = 1;
} else {
// more string inputs
}
}
} while (error != 0);
}
Implement a separate method to read the input data until a valid string is provided and call this method with custom prompt:
private static String readInput(String prompt) {
String input;
do {
input = JOptionPane.showInputDialog(null, prompt);
} while (input == null || input.isEmpty());
}
public void addUser() {
String name = readInput("Enter your name");
String password = readInput("Enter a password");
// ...
User user = new User(name, password, ...);
// ...
}

If statement inside while loops not printing correctly

I'm trying to compare a string, pass, to a dictionary file list. If it directly matches a word, it is considered weak (balloon). If it contains the word from the dictionary file (#balloon232), it is considered moderate. If neither, its strong. In this code, weak and moderate both work correctly, but when a strong pass is entered, it says it is moderate. Thanks for the help.
public static void passwordStrength(String pass, String file2) {
boolean found2 = false;
boolean found3 = false;
try {
y = new Scanner(new File(file2));
z = new Scanner(new File(file2));
while (y.hasNextLine()) {
if (pass.equals(y.nextLine().trim())) {
System.out.println("\nYour password is weak");
found2 = true;
break;
}
}
while (z.hasNextLine()) {
if (pass.contains(z.nextLine().trim()) && !found2) {
System.out.println("\nYour password is moderate");
found3 = true;
break;
}
}
if (!found3 && !found2) {
System.out.println("\nYour password is strong");
}
y.close();
z.close();
} catch (Exception e) {
System.out.print("Error");
}
}
The logic seems fine it should print password is strong. You should print out all lines that you read in from the file to debug and see both when the password and the word from the file doesn't match.
I don't think it makes sense to create multiple scanners and read the file twice. You can read in the file once and test the pass to see if it's a week or moderate and return the string and if not found return strong. You can throw the exception so that main up to you. Unless you specifically want to print out the password strength in this function.
Here is a sample.
import java.io.File;
import java.util.Scanner;
public class PasswordTest {
public static String passwordStrength(String pass, String file2) {
try {
Scanner fileScanner = new Scanner(new File(file2));
while (fileScanner.hasNextLine()) {
String passInFile = fileScanner.nextLine().trim();
if (pass.equals(passInFile)) {
return ("Your password is weak");
}
if (pass.contains(passInFile)) {
return "Your password is moderate";
}
}
} catch (Exception e) {
return e.getMessage();
}
return "Your Password is strong";
}
public static void main(String[] args) {
System.out.println(passwordStrength("test", "test.txt"));
}
}

How can I use method abstraction for checking userInput against login details?

We worked progressively on a project. Last milestone is dividing this into the following: Create a class with four methods: main method, a method for creating customer information(void), a method for creating user name and password (void) and finally a method for log-in(return type).
I have implemented the log-in method, when moving to implementation of the loginDetails, I ran into problems. I don't understand how I can create loginDetails in a void method, and also be able to check against it in a different method. My loginDetail method is not returning a value to main, and my variables are local for the methods.
How can I create the user details in a void method, and be able to create the login check in a separate method?
This is my code, I would like to use the details generated in loginDetails(); as the values to check against instead of the manually inserted strings.
public class Customer {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
loginDetails("testtest", "testtest", "11111121111");
System.out.print(logIn("ABC", "212"));
}
public static void customerInformation() {
//Create customerInformation
}
public static void loginDetails(String firstName, String lastName, String number) {
String userName, password;
userName = firstName.charAt(0) + lastName.substring(0, 3);
password = lastName.substring(0, 3) + number.substring(7);
}
public static String logIn(String userName, String password) {
int count = 0;
while (count < 3) {
System.out.print("Input Username");
String inputUserName = input.nextLine();
System.out.print("Input password");
String inputPassword = input.nextLine();
if (inputUserName.equals(userName) && inputPassword.equals(password)) {
return "You are now logged in";
} else {
count++;
if (count < 3)
System.out.println("Wrong Username or password. Try again");
}
} //While
return "Try again in a few hours"; //Third try
} //logIn
}
class Customer {
static Scanner input = new Scanner(System.in);
static String userName=null;
static String password=null;
public static void main(String[] args) {
loginDetails("testtest", "testtest", "11111121111");
System.out.print(logIn("ABC", "212"));
}
public static void customerInformation() {
//Create customerInformation
}
public static void loginDetails(String firstName, String lastName, String number) {
userName = firstName.charAt(0) + lastName.substring(0, 3);
password = lastName.substring(0, 3) + number.substring(7);
}
public static String logIn(String userName, String password) {
int count = 0;
while (count < 3) {
System.out.print("Input Username");
String inputUserName = input.nextLine();
System.out.print("Input password");
String inputPassword = input.nextLine();
if (inputUserName.equals(userName) && inputPassword.equals(password)) {
return "You are now logged in";
} else {
count++;
if (count < 3)
System.out.println("Wrong Username or password. Try again");
}
} //While
return "Try again in a few hours"; //Third try
} //logIn
}

New Method is not working

I'm getting an error that
"Illegal start of expression and error ';' expected"
I don't know if I'm doing the new method right, so please help me I need this for school work.
public class Testing{
public static void main(String args[])throws IOException{
String un, pw, login;
final String Username = "javajava";
final String Password = "testing";
BufferedReader inpt = new BufferedReader (new InputStreamReader(System.in));
public void Login(){
System.out.println("Please enter your Username & Password for you to be able to use the program");
System.out.println("Warning! Case Sensitive!");
for(int trial=3; trial>=1; trial--){
System.out.print("Username: ");
un = inpt.readLine();
System.out.print("Password: ");
pw = inpt.readLine();
System.out.println();
if(un.equals(Username) && pw.equals(Password)){
System.out.println("User has successfully logged in!");
break;
} else {
System.out.println("Sorry, you've entered an incorrect Username/Password - (" + (trial-1) + ") retries left");
}
if (trial==1){
System.out.println("It seems that you've reached the limit for the login attempts, please try again later");
}
}
}
You can't[1] have a method inside a method.
Move
public void Login(){
To outside
public static void main(String args[])throws IOException{.
I advise you to go through the tutorial Defining Methods.
[1] You can, indirectly, have a "method inside a method". It is possible to have a method that contains an inner class, and that class will contain a method. So.. you actually get a method inside a method ;)
try
import java.io.*;
public class Testing {
static String un, pw, login;
static final String Username = "javajava";
static final String Password = "testing";
public static void Login() throws IOException {
System.out
.println("Please enter your Username & Password for you to be able to use the program");
System.out.println("Warning! Case Sensitive!");
BufferedReader inpt = new BufferedReader(new InputStreamReader(
System.in));
for (int trial = 3; trial >= 1; trial--) {
System.out.print("Username: ");
un = inpt.readLine();
System.out.print("Password: ");
pw = inpt.readLine();
System.out.println();
if (un.equals(Username) && pw.equals(Password)) {
System.out.println("User has successfully logged in!");
break;
} else {
System.out
.println("Sorry, you've entered an incorrect Username/Password - ("
+ (trial - 1) + ") retries left");
}
if (trial == 1) {
System.out
.println("It seems that you've reached the limit for the login attempts, please try again later");
}
}
}
public static void main(String args[]) throws IOException {
Login();
}
}
You need to declare your method outside your main method:
public static void main(String[] args) {...}
public static void Login() {...}

Java : Simple Loop

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
}
}

Categories

Resources