nullpoint exception. Java. ATM - java

I am working on an ATM system in java.
And I keep getting NullPointerException error when I execute this code :
Why am I getting this?
The only way for the function to work is, if I create a new user with the admin user. But when I log in without creating new user ( two user are initialised at the start of the program) and try to delete users, the console throws the NullPointerException error.
public void showDeleteUser() {
System.out.println("-----------------------------");
System.out.println("Username of user to delete");
input.nextLine();
String userToDelete = input.nextLine();
User _userToDelete = null;
for (User user : users) {
if (userToDelete.equals(user.getName())) {
_userToDelete = user;
}
}
if (_userToDelete != null) {
users.remove(_userToDelete);
System.out.println("Following user is deleted: " + userToDelete);
} else {
System.out.println("User: " + userToDelete
+ "User could not be found would you like to try again?");
}
}

It could be because input.nextLine(); is never assigned to a variable and thus returns a NullPointer.
You could try: String delete = nextLine(); if you really need it. Because the next line is quite the same String userToDelete = nextLine(); if it is so, then just remove the above mentioned line.

Related

Eclipse Syntax error on token "}", delete this token and Syntax error, insert "}" to complete ClassBody

I am trying to make a practice program for a bookstore clerk that allows the clerk to add, remove, edit, and search for books in its database. I have all but made the entire program however I am getting stuck on 2 errors. It is a total of 234 lines of code in all so I will try to shorten it to the relevant parts to make it easier on those willing to help me. I am using Eclipse with JDE and JDK 10. The Eclipse project was initiated using the JavaSE-10 execution environment as far as I am aware. Below are the 2 methods causing the errors.
public class Bookstore {
public static void main(String[] args) {
try(
//Creating table connection and statement
Connection conn = DriverManager.getConnection("***********",
"****", "*********"); //Please note that I blocked out the actual connection information here
Statement stmt = conn.createStatement();
){
Scanner input = new Scanner(System.in);
int selection = 0;
//Menu for action selection and user input
while(selection != 5) {
System.out.println("Please enter the number corresponding to the action you would like to take:\n"
+ "1. Enter book\n"
+ "2. Update book\n"
+ "3. Delete book\n"
+ "4. Search books\n"
+ "5. Exit");
selection = input.nextInt();
//Selection sorting
if(selection == 1) {
//Collecting book information
System.out.println("Please enter the Title of the book you would like to put into the system: ");
String title = input.next();
System.out.println("Please enter the Author of said book: ");
String author = input.next();
System.out.println("Please enter the number of said book currently in stock: ");
int qty = input.nextInt();
//Sending info to the addBook method
addBook(title, author, qty, stmt);
} else if(selection == 2) {
//Collecting book information
System.out.println("Please enter the id of the book you would like to update: ");
int id = input.nextInt();
//Sending info to the updateBook method
updateBook(id, stmt);
} else if(selection == 3) {
//Collecting book information
System.out.print("Please enter the id of the book you would like to delete from the system: ");
int id = input.nextInt();
//Sending info to deleteBook method
deleteBook(id, stmt);
} else if(selection == 4) {
searchStore(stmt);
} else if(selection == 5) {
System.out.println("Goodbye");
input.close();
} else { //Invalid entry handler
System.out.println("Sorry, that isn't a valid selection.");
}
}
} catch(SQLException ex) {
ex.printStackTrace();
}
}
} //This is the line giving me the error "Syntax error on token "}", delete this token"
Now I have already done some research regarding the error at the bottom of this block of code. As far as I can tell I am not missing any brackets and there are no variables or anything being created outside of a class that would cause this error. The only other solution I have been able to find is that "Eclipse is just being weird".
My second error comes from this block of code:
public static void resultSetPrinter(ResultSet rset) {
while(rset.next()) {
String title = rset.getString("Title");
String author = rset.getString("Author");
int qty = rset.getInt("qty");
System.out.println("Title: " + title + "\nAuthor: " + author + "\nNumber in stock: " + qty + "\n\n");
}
if(rset == null) {
System.out.println("No records for the entry could be found.");
}
} //This is the line giving me the "Syntax error, insert "}" to complete ClassBody" error
I have also done some research regarding the error at the bottom of this block and when I do remove the bracket as requested the error just jumps up to the method before this one. I haven't included the other 4 methods in the class to try and reduce the headache of running through all this code since they aren't giving me errors. Any help would be greatly appreciated at this point, I am completely stumped.
Thanks mainly to Elliott Frisch I have found my answer. Essentially I needed to put all my methods into my main class by the name of Bookstore. I moved the } to the end of my program and added try catch statements for each method. For example I changed the last code block I put in my question to:
public static void resultSetPrinter(ResultSet rset) {
try {
if(rset.next()) {
while(rset.next()) {
String title = rset.getString("Title");
String author = rset.getString("Author");
int qty = rset.getInt("Qty");
System.out.println("Title: " + title + "\nAuthor: " + author + "\nNumber in stock: " + qty + "\n");
}
} else {
System.out.println("No records for the entry could be found.\n");
}
} catch(SQLException ex) {
ex.printStackTrace();
}
}
You'll also note that I added an if else statement to check if the ResultSet rset was empty, if it wasn't I proceeded as normal and if it was I printed a simple message to let the user know nothing was found.
Thank you both Elliott Frisch and Marco13 for the asssistance.

Java How to dispaly no data found when the user input no reach the condition

If the user key in 4 I wish to pop up a message to inform the user that is no data found for user id "4" in the array list.
But when the user key in 4 there is 3 no data found appear.
User usr1 = new User(1,"Ken", 55.5, 26, Arrays.asList("0140392812", "0123456789"));
User usr2 = new User(2, "Mark", 54.7, 33, Arrays.asList("0129876543"));
User usr3 = new User(3, "Ong", 62.3, 34, Arrays.asList("06123456", "0987654322", "01798654321"));
ArrayList<User> ulist = new ArrayList<User>();
ulist.add(usr1);
ulist.add(usr2);
ulist.add(usr3);
String answer ="";
do{
Scanner scan = new Scanner(System.in);
System.out.println("Please Enter user ID");
int userid = scan.nextInt();
for(User uid: ulist){
if(userid == uid.getUID()){
System.out.println(uid.getUID() +", " + uid.getName() +", " + uid.getAge() +" years old, " + uid.getWeight() +"kg");
}else{
System.out.println("no data found");
}
}
System.out.println("Continue(Y/N)");
answer = scan.next();
}while(answer.equalsIgnoreCase("y"));
current result:
no data found
no data found
no data found
Result that i wish:
no data found
Remove else { System.out.println("no data found"); } from the loop and put it outside. The for loop intent is to find, to lookup the correct user.
Once found you may use it: you have to declare a variable of type User before loop, initialized to null and if it's null after lookup, you have to print the message 'not found'.
You get no data found 3 times because you print it in the cycle: for every user in the list, if his id doesn't match specified id, System.out.println("no data found"); You can avoid this modifying your cycle or writing a method that fidns user by id.
User found;
for (User uid : ulist) {
if (userid == uid.getUID()) {
found = uid;
break; // assuming that ids are unique
}
}
if (found != null) {
System.out.println(found.getUID() +", " + found.getName() +", " + found.getAge() +" years old, " + found.getWeight() +"kg");
} else {
System.out.println("no data found");
}
You have problem in your logic.
in your for loop you should have a break statement, in case there is no data found.
else {
System.out.println("no data found");
break;
}

Java - Storing Names in ArrayList and Using it to Login

I have a task to do which involves asking the user to input their last name and giving the user an account number to login to the program. I have listed the steps below which might make more sense.
1) User creates an account
2) User enters their last name (Stores into the arraylist)
3) User is given an account number (Stores into the arraylist)
4) User can then login using their last name and account number (checks arraylist for lastname and accountnumber, if it matches then login message, if it doesnt then error message)
A user enters their last name and they are given an account number which they then use to login to deposit, withdraw and check balance.
How do i create a programe to do this without the use of database?
Account Class
private static int number = 500;
Account(){
accountNumber = number++;
}
Create Account
public void createAccount(){
String firstName;
System.out.print("Please Enter Last Name: ");
lastName = scanner.nextLine();
System.out.println("This is your Account Number to log into: " + _______ );
}
public void logIn(){
System.out.println("Please enter your last name: ");
System.out.println("Please enter your account number: ");
}
I would like to suggest another method using xml to store credentials follow the steps below
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
string username;
string pwd;
string CurrentUser = "";
string CurrentPwd = "";
bool LoginStatus = false;
username = Login1.UserName;
pwd = Login1.Password;
XmlDocument xmxdoc = new XmlDocument();
xmxdoc.Load(Server.MapPath("Register.xml"));
XmlNodeList xmlnodelist = xmxdoc.GetElementsByTagName("user");
foreach (XmlNode xn in xmlnodelist)
{
XmlNodeList xmlnl = xn.ChildNodes;
foreach (XmlNode xmln in xmlnl)
{
if (xmln.Name == "Name")
{
if (xmln.InnerText == username)
{
CurrentUser = username;
}
}
if (xmln.Name == "Password")
{
if (xmln.InnerText == pwd)
{
CurrentPwd = pwd;
}
}
}
if ((CurrentUser != "") & (CurrentPwd != ""))
{
LoginStatus = true;
}
}
if (LoginStatus == true)
{
Session["UserAuthentication"] = username;
Session.Timeout = 1;
Response.Redirect("welcome.aspx");
}
else
{
Session["UserAuthentication"] = "";
}
}
in your xml file
<user>
<Name>smashcode</Name>
<Password>smashcode</Password>
</user>
I guess this would be better approach than a arraylist approach
if you want to try in using arraylist follow steps
step1:username_list{uesr1,user2,user3}
password_List{pass1,pass2,pass3}
step:check all entries with entered userid and password in a loop as follows
int flag = 0;
while(username_list.get(i)!=null)
{
if((username_list.get(i).equals(enteredusername))&&((password_list.get(i).equals(enteredpassword)))
{
flag = 1;
}
}
if(flag==1)
{
System.out.println("login successful ");
Response.Redirect("welcome.aspx");
}
I had written second code implementation in cut short
Hope my work will be helpful.Keep coding
Not a full answer here but a few suggestions....
You could create a "bank" class... It might hold the arraylist of accounts, also holding
createAccount()
delAccount()
findAccount()...
So on and so forth
Having posted this I now see it is an answer, my bad guys
I assume you need to be able to keep this information after the execution is complete, which means you need to store the information somewhere besides the running program.
Of the top of my head, you can use a file to store this store of information, where each line of the file would equal a match of last name - account. When opening the program, you read the file. Try reading:
http://www.tutorialspoint.com/java/java_files_io.htm or
https://docs.oracle.com/javase/tutorial/essential/io/file.html
The solution is similar to using a database, so I don't know if it will do or not. Hope it does.

Java for loop with if statement only iterating once

I have a version of a login for an employee system i would like to make, I have a for loop which should go through the entire list of Accounts, then see if the name of an employee matches one in the list then the if statement continues, further questions asked etc... it seems to only iterate once and then stop as it will only find the first user and tell me the other accounts do not exisit, even though they do!! What am i doing wrong? Also my list contains Employees and Managers which inherit from Account, the if statement uses the getName in Account to compare if it equals to the user input. Sorry if this is ridiculously stupid/bad! thanks.
List <Account> Accounts = new LinkedList<Account>();
Here is where i populate my Account, the main method calls this and the list() is called whihc contains the problematic loop
public void add() {
Employee Geoff = new Employee("Geoff", "password1");
Manager Bob = new Manager("Bob", "password2");
Employee John = new Employee("John", "password3");
Accounts.add(Geoff);
Accounts.add(Bob);
Accounts.add(John);
list();
}
problem:
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
}
}
System.out.println("Employee does not exist!");
login();
}
I am doing the print statement in the for loop to see what it is findng, and unfortunalty it is only the first account
EDIT: I have included more code here, my after my initial if statement i want to check if the code the user enters is also correct.
see if the name of an employee matches one in the list then the if
statement continues, further questions asked etc... it seems to only
iterate once and then stop as it will only find the first user and
tell me the other accounts do not exisit, even though they do!!
If it works for one employee and tells that others don't exist then your for loop does not iterate once.
The output you get is exactly what the code looks like. You get username once then try to match the same name with every employee in the list. If the names are equal you ask for password, otherwise you print out that employee doesn't exist. Everything right as it is in the code. You should add to your question the expected behaviour so I, or someone else can fix your code without guessing the purpose of your methods.
Here's one of those guesses:
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
boolean userFound = false;
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
userFound = true;
break;
}
}
}
if(userFound) {
login();
} else {
System.out.println("User not found.");
}
This is a possible solution that doesn't use your Account class (since I do not know what it looks like) and instead uses a Map:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = input.nextLine();
boolean found = false;
Map<String, String> accounts = new HashMap<String, String>();
accounts.put("Geoff", "password1");
accounts.put("Bob", "password2");
accounts.put("John", "password3");
Set<String> names = accounts.keySet();
for (String a : names)
{
if (!a.equals(empName))
{
continue;
}
found = true;
// three tries to login
boolean success = false;
for(int i = 0; i < 3; i++)
{
System.out.println("Please enter your passcode: ");
String code = input.nextLine();
if (accounts.get(a).equals(code))
{
System.out.println("logged in");
success = true;
}
else
{
System.out.println("Wrong password... try again");
}
}
if(!success)
{
System.out.println("User failed to authenticate after 3 attempts. User has been locked out!");
}
}
if(!found)
{
System.out.println("Employee does not exist!");
}
}
Since I do not know what the login() method does, I just simply added that into the code. This solution iterates three times in an attempt to get the correct password. If that fails, a message is displayed.

Why won't this method call work?

I'm creating a method to take an input by a user and validate it to make sure it's correct. If it's correct it will call a method and input the user input in to it. But for some reason, the method call is not working. It doesn't produce any errors, it just simply doesn't do it. I placed a print statement at the end of the code to make sure it actually reaches there and it does, but for some reason it's just not calling the method like it's supposed to. The other method works fine if I call it by itself and input a string via the parameters.
The code is:
public void getGetScheduledShowByFilmInput()////new - omar////
{
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
String filmInput;
filmInput = "";
boolean foundFilm;
foundFilm = false;
System.out.println("Here is a list of films that are currently showing:");
for(Film film : films){
System.out.println(film.getFilmName());
}
System.out.println("");
System.out.println("Please type the film name that you wish to view the corresponding shows for and press enter.");
System.out.println("Type 'exit' and press enter to exit this process.");
while(foundFilm == false){
try{
filmInput = reader.readLine();
}
catch (IOException e){
System.out.println("Error");
}
//If user enters "exit" then return.
if(filmInput.equals("exit")){
return;
}
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName() == filmInput){
foundFilm = true;
break;
}
}
if(foundFilm = true){
System.out.println("Film found.");
}
else{
System.out.println("The film name you entered has not been recognised. Please try again.");
}
}
//Call the function and input the film name input by the user.
getScheduledShowsByFilm(filmInput); ////This is the code that seems to be the problem.
System.out.println("reached bottom");
}
and the second method is:
public void getScheduledShowsByFilm(String inputFilmName)
{
ArrayList<Show> scheduledShows;
scheduledShows = new ArrayList<Show>();
for(Film film : films){
if(inputFilmName == film.getFilmName()){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}
for(Show show : scheduledShows){
System.out.println("**********************************");
show.getShowDetails();
System.out.println("**********************************");
}
}
The second method works perfectly when I call it on its own and enter parameters manually though.
It's probably something extremely simple that I'm not understanding! haha, thank you for your help :)
foundFilm can never be false because you always assign true to it:
if(foundFilm = true){
System.out.println("Film found.");
}
try changing it to this:
if(foundFilm)
{
System.out.println("Film found.");
}
In getGetScheduledShowByFilmInput() and getScheduledShowsByFilm(String) avoid doing string comparison using the equality operator (==). The == operator tests for object equality, but you want to test whether two strings contain the same sequence of characters. Therefore, use equals instead:
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName().equals(filmInput)){
foundFilm = true;
break;
}
}
and
for(Film film : films){
if(inputFilmName.equals(film.getFilmName())){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}

Categories

Resources