I am having trouble with the logic of deleting an entry in an Address Book... I am saving all the entries using an ARRAY.
I am try to make the array[i] = null, if array[i] is equals to the entered name of the user. But after i delete an entry and then try to view all entries again, nothing shows.. and output says :
Exception in thread "main" java.lang.NullPointerException
at AddressBook.viewAll(AddressBook.java:61)
at AddressBook.main(AddressBook.java:35)
Java Result: 1
this is my code in deleting an Entry:
public void deleteEntry() {
SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
//JOptionPane.showMessageDialog(null, "Found!");
entry[i] = null;
}
}
}
Can you help me figure out what was wrong with my code... or LOGICAL ERROR?
If you have any suggestion or better way to delete an entry that would be a big help..
please help...
if (entry[i].getName().equals(SName)) {
if on one pass you make
entry[i] = null
then how would you getName() afterwords?
try adding a null check to your if statement
if (entry[i] != null && entry[i].getName().equals(SName)) {
EDIT: Benjamin brings up a good point. You should be prepared for a null result from showinputdialog(). For example, there's a cancel button right? If they press that, you'll get null I believe. Here's some better code for that case:
public void deleteEntry() {
/* get the input */
SName = JOptionPane.showInputDialog("Enter Name to delete: ");
/* if no input, nothing to delete */
if(SName == null) return;
/* find the name */
for (int i = 0; i < counter; i++) {
/* make sure we have an entry*/
/* we know SName is not null */
if (entry[i] != null && SName.equals(entry[i].getName())) {
/* null out the deleted entry */
entry[i] = null;
// break; /* If you know you have unique names, you can leave the for loop now */
} /* end if */
} /* end for i*/
}
Related
Here is my code. I am trying to use JUnit to test the deleteUsers() method, but everytime I write my test, it deletes all the users that I have in the database. How can i delete a single user? Below is the code for the method and for the test.
#Override
public boolean deleteUsers(List<String> ids) throws Exception {
StringBuilder sql = new StringBuilder();
sql.append("delete from user where ");
for (String id : ids) {
sql.append(" id = ? or");
}
String strSql = sql.toString().substring(0, sql.length() - 2) + ";";
PreparedStatement preparedStatement = this.connection.prepareStatement(strSql);
for (int i = 0; i < ids.size(); i++) {
preparedStatement.setInt(1 + i, Integer.parseInt(ids.get(i)));
}
int lines = preparedStatement.executeUpdate();
preparedStatement.close();
return lines > 0;
}
You're missing a check for empty input. In your test you pass an empty list to deleteUsers which results in this SQL statement:
delete from user wher;
I'd expect that the DBMS would reject this as invalid SQL but perhaps there are some where this is interpreted as delete from user which simply deletes all users. (As #SteveBosman pointed out the wher is interpreted as table alias as it is - due to the missing last e - no reserved word anymoere)
Basically you have 2 options. Either deleting all users by passing an empty list is a valid use case - in which case you should handle it properly by producing proper SQL. Or this is not expected and you should adapt your code to throw an Exception if ids is empty.
#Override
public boolean deleteUsers(List<String> ids) throws Exception {
if (ids == null || ids.size() == 0) {
throw new IllegalArgumentException("List of IDs must not be empty");
}
...
}
You could of course return false in case of an empty input as well to indicate no users were deleted.
To pass values to the deleteUsers method in your test you need to add values to the used list:
userDAOImpl.addUser("admin3", "111222");
final List<String> idsToDelete = new ArrayList<>();
idsToDelete.add("111222");
userDAOImpl.deleteUsers(idsToDelete);
The problem is caused by how the SQL is built. When deleteUsers is passed an empty list then the generated SQL will be:
delete from user wher
which will result in all data being deleted (the table user is given the alias "wher"). I highly recommend checking at the start of the method if the collection is empty and either raising an exception or returning.
Add the following check
if (ids == null || ids.isEmpty()) {
throw new IllegalArgumentException("ids must not be empty");
}
StringBuilder sql = new StringBuilder();
sql.append("delete from user where");
String orClause = "";
for (String id : ids) {
sql.append(orClause);
sql.append(" id = ?");
orClause = " or";
}
everyone who is watching this question. I have a small problem that i am not fixing. I have a program in which a user or a manager can login in and the input check whether the person who logged is a user or a manager. Unfortunately I can't separate them. This is what i would get all the time.
Incorrect username or password. Try Again!
This is the code:
int check = 0;
while(check == 0)
{
screen.displayString("Enter the username: ");
String usernameLogin = keypad.getString();
screen.displayString("Enter the password: ");
String passwordLogin = keypad.getString();
for (int i = 0; i < users.size(); i++) {
if (users.get(i).getUsername().equals(usernameLogin) && users.get(i).getPassword().equals(passwordLogin)) {
no = users.get(i).getId();
check = 1;
break;
}
else
{
check = 0;
}
}
if(check == 1)
{
break;
}
if (manager.getUsername().equals(usernameLogin) && manager.getPassword().equals(passwordLogin)) {
no = manager.getId();
check = 1;
break;
}
else {
check = 0;
}
if(check==0)
{
screen.displayStringLine("Incorrect username or password. Try Again!");
}
}
Thank you once again for the help.
first off a bit of small advice for code formatting, after each curly brace/code block leave one empty line - it will be easier to read
So let's clean your code a little bit by adhering to these steps:
do the easier tasks first, meaning there are many users in this app but only one manager so maybe we should check if it's him firstly and not waste compute resources
remove redundant variables - to break the loop you don't need the check variable, only a break statement after a correct login
you can use for each to iterate through a collection
while (true) {
screen.displayString("Enter the username: ");
String usernameLogin = keypad.getString();
screen.displayString("Enter the password: ");
String passwordLogin = keypad.getString();
if (manager.getUsername().equals(usernameLogin) && manager.getPassword().equals(passwordLogin)) {
no = manager.getId();
break;
}
for (User user : users) {
if (user.getUsername().equals(usernameLogin) && user.getPassword().equals(passwordLogin)) {
no = users.get(i).getId();
break;
}
}
screen.displayStringLine("Incorrect username or password. Try Again!");
}
This code should be easier to debug - just place 2 breakpoints on both lines containing if statement and check if values are matching.
If you see that everything looks good, check the string encoding - maybe there is a mismatch there (Java uses by default UTF8)
This is my whole code, it's quite complex but please help me. It's taken me for 2 days but I failed:
public static ArrayList<DocGia> XuatDocGia() throws IOException {
ArrayList<DocGia> listDocGia = new ArrayList<>();
File fileDocGia = new File("fileDocGia.txt");
if(fileDocGia.exists() == false) {
System.out.println("Chưa có đọc giả nào trong thư viện");
} else {
BufferedReader br = new BufferedReader(new FileReader("fileDocGia.txt"));
if (br.readLine() == null) {
System.out.println("Chưa có đọc giả nào trong thư viện");
} else {
int soDong = DemSoDong("fileDocGia.txt");
int dongHienTai = 0;
Scanner fileScanner = new Scanner(fileDocGia);
for(int i = 0, z = 0;;i++, z++) {
DocGia docGia = null;
System.out.println("***Đọc giả thứ: " + (i+1));
docGia.tendocgia = fileScanner.nextLine();
if(i >= 1) {
docGia.tendocgia = fileScanner.nextLine();
}
docGia.maDocGia = fileScanner.nextLine();
docGia.soSachmuon = fileScanner.nextInt();
docGia.thoiGianMuonSach = fileScanner.nextInt();
listDocGia.add(docGia);
docGia.XuatDocGia();
dongHienTai += 4;
if(dongHienTai == soDong) {
fileScanner.close();
break;
}
}
}
for(DocGia docGia: listDocGia) {
docGia.XuatDocGia();
}
}
return listDocGia;
}
look at my code, when i run:
docGia.XuatDocGia();
-> the value of every single element is right at debug. it also means the value of the variable inside is right. but at the end of this function. i run
for(DocGia docGia: listDocGia) {
docGia.XuatDocGia();
}
this is XuatDocGia funtion:
public static void XuatDocGia(){
System.out.println(tendocgia);
System.out.println(maDocGia);
System.out.println(soSachmuon);
System.out.println(thoiGianMuonSach);
}
It just shows for me the last element in this ArrayList, repeat in 3 times( equal the number of elements).
I think a problem come from adding process of listDocGia.add(docGia);
You guys no need to bother everything else in my code, because i know it's really complex. I have tested carefully, just focus on my problem.
I'm so sorry because i'm Vietnamese and beginner at Java. The next time everything will be English. Thank you so much.
If this is the actual code, you are adding null references to your List, but since you are using a static method to print the values, you don't get a NullPointerException. Assuming your code passes compilation, this means all the members of the DocGia class are static, which explains why you get the same values in each iteration of your loop.
You should change
DocGia docGia = null;
to
DocGia docGia = new DocGia ();
and change all the members of DocGia (including the XuatDocGia method that prints them) to be non static.
This question already has answers here:
null pointer exception apache poi
(2 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
public class ExecuteTest {
#Test
public void testLogin() throws Exception {
// TODO Auto-generated method stub
`WebDriver webdriver = new FirefoxDriver();
ReadExcelFile file = new ReadExcelFile();
ReadObject object = new ReadObject();
Properties allObjects = object.getObjectRepository();
UIOperation operation = new UIOperation(webdriver);
//Read keyword sheet
Sheet RDSheet = file.readExcel(System.getProperty("user.dir")+"\\","TestCase.xlsx" , "KeywordFramework");
//Find number of rows in excel file
int rowCount = //Loop over all the rows RDSheet.getLastRowNum()-RDSheet.getFirstRowNum();
//Create a loop over all the rows of excel file to read it
for (int i = 1; i < rowCount+1; i++) {
Row row = RDSheet.getRow(i);
//Check if the first cell contain a value, if yes, That means it is the new testcase name
if(row.getCell(0).toString().length()==0){
//Print testcase detail on console
System.out.println(row.getCell(1).toString()+"----"+ row.getCell(2).toString()+"----"+
row.getCell(3).toString()+"----"+ row.getCell(4).toString());
//Call perform function to perform operation on UI
operation.perform(allObjects, row.getCell(1).toString(), row.getCell(2).toString(),
row.getCell(3).toString(), row.getCell(4).toString());
}
else{
//Print the new testcase name when it started
System.out.println("New Testcase->"+row.getCell(0).toString() +" Started");
}
}
}
}
getting null pointer exception when first cell is empty.
I have searched many blogs but couldn't find any solution
can anyone please help me with code.
for every .toString() add a " "+ x.toString() to it, so that the value doesnt become a null.
`
for (int i = 1; i < rowCount+1; i++) {
Row row = RDSheet.getRow(i);
//Check if the first cell contain a value, if yes, That means it is the new testcase name
if((row.getCell(0)+"").toString().length()==0){
//Print testcase detail on console
System.out.println((row.getCell(1)+"").toString()+"----"+ (row.getCell(2)+"").toString()+"----"+
(row.getCell(3)+"").toString()+"----"+ (row.getCell(4)+"").toString());
//Call perform function to perform operation on UI
//your operations
}
else{
//Print the new testcase name when it started
System.out.println("New Testcase->"+row.getCell(0).toString() +" Started");
}
}
`
Make sure you add a null check before using toString() method otherwise you will get NPE if the value is null.
if (row.getCell(0) != null) {
row.getCell(0).toString() //in this case you are trying to call toString on null value.
}
Refer this SO question
try below Code its working fine for me, we cannot define length of a Null
if(row.getCell(0)==null){
//Print testcase detail on console
//System.out.println("testing");
System.out.println(row.getCell(1)+"----"+ row.getCell(2)+"----"+
row.getCell(3)+"----"+ row.getCell(4));
//Call perform function to perform operation on UI
try{
operation.perform(allObjects, row.getCell(1)==null?"Not a Valid KeyWord":row.getCell(1).toString(),
row.getCell(2)==null?null:row.getCell(2).toString(),
row.getCell(3)==null?null:row.getCell(3).toString(),
row.getCell(4)==null?null:row.getCell(4).toString());
}catch(Exception e)
{
//will print Error Row and break the flow
System.out.println(i);
System.out.println(e);
break;
}
}
else{
//Print the new testcase name when it started
System.out.println("New Testcase->"+row.getCell(0) +" Started");
}
}
I managed to display 1 record of the asked category but what i need is for the program to display everything from that category. If it's too vague the code might help. Thanks in advance
public static void SearchCatRecord() throws Exception
{
LoadFile();
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\t---------SEARCH CATEGORIZED ITEM--------");
System.out.println("\n\t\t\t*******************************");
System.out.print("\t\t\tEnter Category: ");
String searchnum = br.readLine();
boolean found = false;
for(int i=0;i<row;i++)
{
String record[] = list.get(i).split(",");
String num = record[1];
if(searchnum.equals(num))
{
found = true;
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\t---------RECORD FOUND----------");
System.out.println("\n\t\t\tProduct Number : "+record[0]);
System.out.println("\t\t\tCategory : "+record[1]);
System.out.println("\t\t\tProduct Name : "+record[2]);
System.out.println("\t\t\tPrice : "+record[3]);
System.out.println("\t\t\tQuantity : "+record[4]);
System.out.println("\n\t\t\t*******************************");
Thread.sleep(2000);
found = true;
System.out.println("\n\n\t\t\tSearch Completed");
exiting();
}
}
if(found == false)
{
System.out.println("\t\t\tNo Record Found");
System.out.println("\t\t\t*******************************");
exiting();
}
MainMenu();
}
The following code asks the user which category should the program display. then it displays the asked category but it only displays one record.
This is because you call exiting(); when you found the first record. You should remove it in your loop.
for example:
for(int i=0;i<row;i++)
{
String record[] = list.get(i).split(",");
String num = record[1];
if(searchnum.equals(num))
{
found = true;
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\t---------RECORD FOUND----------");
System.out.println("\n\t\t\tProduct Number : "+record[0]);
System.out.println("\t\t\tCategory : "+record[1]);
System.out.println("\t\t\tProduct Name : "+record[2]);
System.out.println("\t\t\tPrice : "+record[3]);
System.out.println("\t\t\tQuantity : "+record[4]);
System.out.println("\n\t\t\t*******************************");
Thread.sleep(2000);
}
}
System.out.println("\n\n\t\t\tSearch Completed");
if(found == false)
{
System.out.println("\t\t\tNo Record Found");
System.out.println("\t\t\t*******************************");
}
exiting();
If you want to find all the records then you should not breakout after finding one record that meets your criteria. I believe your method invocation exiting() is not needed in loop.
On a side note why are you setting found=true twice in the loop? Also what is the need of Thread.sleep(2000) in the code?