Incorrect Output
May I know can I fix this program, it was inputted incorrectly - specifically on case 4. I already input a name but when I go for case 4 it says name not found -sorry for the grammatical error https://code.sololearn.com/cMfULUxMMU8f case 4: //Edit (Make changes / Update in any field) found = false; System.out.print("Enter NAME to UPDATE: "); name=console.next(); ListIterator<Person>li = c.listIterator(); while(li.hasNext()){ Person e = li.next(); if (e.getName() == name) { System.out.println("Enter new gender: "); gender = console.next(); System.out.println("Enter new age: "); age = console.nextInt(); li.set(new Person (name,gender,age)); found = true; } } if (!found){ System.out.println("Record Not Found: "); }else{ System.out.println("Record Updated Successfully: "); } break;
5/26/2022 5:52:53 PM
Eyy
9 Answers
New AnswerBefore those, can you correct total code? You class name is Program but your constructor name is Person()..? Mismatch. You don't have actually main method.. I think case 4 have no error in code!! Mention sample input. Expected output.. Error details if any..
change class Program to class Person change main() to main(String[] args) use nextLine() for person name with space console.nextLine() (I don't use it for this test) in case 4 : p is empty brcause you store to array c first (but weak) solution can be change c = Arrays.asList(p); // fixed size ListIterator<Person> li = c.listIterator(); for compare Strings use equals() //if (e.getName() == name) { if (e.getName().equals(name) ) { it doesn't update name it update each person with same name
my input: 1 Name1 M 21 1 Name2 M 44 1 Name3 F 33 1 Name4 M 44 1 Name5 F 45 4 Name3 F 20 5 0
Arrays with s at the end //c = Array .asList(p); c = Arrays.asList(p); in case 4 is used name not tempName also check Main() line
like this sir zemiak? c = Array.asList(p); ListIterator<Person>li = c.listIterator(); while(li.hasNext()){ Person e = li.next(); if (e.getName().equals(name)) { System.out.println("Enter new gender: "); gender = console.next(); System.out.println("Enter new age: "); age = console.nextInt(); li.set(new Person (tempName,gender,age)); found = true; } }
c = Array.asList(p); ListIterator<Person>li = c.listIterator(); while(li.hasNext()){ Person e = li.next(); if (e.getName().equals(name)) { System.out.println("Enter new gender: "); gender = console.next(); System.out.println("Enter new age: "); age = console.nextInt(); li.set(new Person (tempName,gender,age)); found = true; } }
sir zemiak, I added a case5 to delete by name.. if you don't mind sir can you please check again the program please . //case4 is fix. thanks sir