problem with comparing a name from getter method to user input string - java

i'm having trouble comparing in my if statement, in C programming i am using "==" double equal sign to compare two string...
how about comparing a string using getter method to a new string... i try to use the double equal sign but i was prompted to change it into this:
if (entry[i].getName().equals(EName))
by the way this is my whole code:
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class AddressBook {
private AddressBookEntry entry[];
private int counter;
private String EName;
public static void main(String[] args) {
AddressBook a = new AddressBook();
a.entry = new AddressBookEntry[100];
int option = 0;
while (option != 5) {
String content = "Choose an Option\n\n"
+ "[1] Add an Entry\n"
+ "[2] Delete an Entry\n"
+ "[3] Update an Entry\n"
+ "[4] View all Entries\n"
+ "[5] View Specific Entry\n"
+ "[6] Exit";
option = Integer.parseInt(JOptionPane.showInputDialog(content));
switch (option) {
case 1:
a.addEntry();
break;
case 2:
break;
case 3:
a.editMenu();
break;
case 4:
a.viewAll();
break;
case 5:
break;
case 6:
System.exit(1);
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Choice!");
}
}
}
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
public void viewAll() {
String addText= "";
for (int i = 0; i < counter; i++) {
addText = addText+(i+1)+ entry[i].getInfo()+ "\n";
}
JOptionPane.showMessageDialog(null, new JTextArea(addText));
}
public void editMenu() {
int option = 0;
while (option != 6) {
String content = "Choose an Option\n\n"
+ "[1] Edit Name\n"
+ "[2] Edit Address\n"
+ "[3] Edit Phone No.\n"
+ "[4] Edit E-mail address\n"
+ "[5] Back to Main Menu";
option = Integer.parseInt(JOptionPane.showInputDialog(content));
switch (option) {
case 1:
editName();
break;
case 2:
editAdd();
break;
case 3:
editPhoneNo();
break;
case 4:
editEmail();
break;
case 5:
return;
default:
JOptionPane.showMessageDialog(null, "Invalid Choice!");
}
}
}
public void editName() {
EName = JOptionPane.showInputDialog("Enter name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(EName)) {
//JOptionPane.showMessageDialog(null, "found");
entry[i].setName(JOptionPane.showInputDialog("Enter new name: "));
}else {
JOptionPane.showMessageDialog(null, "Entered Name not Found!");
}
}
}
public void editAdd() {
EName = JOptionPane.showInputDialog("Enter name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(EName)) {
//JOptionPane.showMessageDialog(null, "found");
entry[i].setAdd(JOptionPane.showInputDialog("Enter new Address: "));
}else {
JOptionPane.showMessageDialog(null, "Entered Name not Found!");
}
}
}
public void editPhoneNo() {
EName = JOptionPane.showInputDialog("Enter name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(EName)) {
//JOptionPane.showMessageDialog(null, "found");
entry[i].setPhoneNo(JOptionPane.showInputDialog("Enter new Phone No.: "));
}else {
JOptionPane.showMessageDialog(null, "Entered Name not Found!");
}
}
}
public void editEmail() {
EName = JOptionPane.showInputDialog("Enter name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(EName)) {
//JOptionPane.showMessageDialog(null, "found");
entry[i].setEmail(JOptionPane.showInputDialog("Enter new E-mail add: "));
}else {
JOptionPane.showMessageDialog(null, "Entered Name not Found!");
}
}
}
}
and this is my other class:
public class AddressBookEntry {
private String name;
private String add;
private String phoneNo;
private String email;
private int entry;
public String getAdd() {
return add;
}
public String getEmail() {
return email;
}
public int getEntry() {
return entry;
}
public String getName() {
return name;
}
public String getPhoneNo() {
return phoneNo;
}
public void setAdd(String add) {
this.add = add;
}
public void setEmail(String email) {
this.email = email;
}
public void setEntry(int entry) {
this.entry = entry;
}
public void setName(String name) {
this.name = name;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getInfo() {
String Info = "NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n"
+ name + "\t " + add + "\t " + phoneNo + "\t " + email + "\n";
return Info;
}
public String getInfo2() {
String content = "INFORMATION:\n\n"
+ "Name: " + name + "\n"
+ "Address: " + add + "\n"
+ "Tel. No: " + phoneNo + "\n"
+ "Email Add: " + email + "\n\n";
return content;
}
}
PLEASE PARDON MY CODE... i am new at java.... please help....
what i want to is traverse to all the array and edit the specific detail if the user input was equals to the entry[i].getName()
thanks a lot in advance...

Use equals() if you want to compare the representation of the string and not its object identity.
Assume we have: String s = "hello";
s == s
=> true // they are the *same* object
"hello" == new String("hello") // see comment below...
=> false // they are different objects representing the same string of text
"hello".equals("hello")
=> true
s.equals("hello")
=> true

There are at least 3 things to understand:
Java: == tests whether two references point to the same object, whereas equals tests whether two objects have the same content. So, even if two Strings have the same content, == may give false whereas s1.equals(s2) will give true. You can find loads about this on google.
C: In C, you shouldn't compare two strings using == either. Strings in C generally are char* (or const char*), and you should compare them with strcmp (or else you will run into the same problems as in Java).
C++: instances of std::string can be compared using ==.

Related

Java Sorting Algorithm Classroom Data Structures Project Trouble

I'm having trouble with a project for my Java data structures and algorithms class. I have a classroom program with an option to create, update, display, or see all students.
Can someone help me by implementing a sorting algorithm and explain it? I was trying to sort the students by grade but I don't know how to implement it with a user input.
Here is main:
package main;
import school.School;
public class Main {
public static void main(String[] args) {
School aSchool = new School();
aSchool.initialMenu();
}
}
Here is school:
package school;
import java.io.PrintStream;
import java.util.Scanner;
import student.Student;
public class School {
private final Scanner keyboard = new Scanner(System.in);
private final PrintStream messagePane = new PrintStream(System.out, true);
private int nextAvailablePosition;
private Student[] classroom;
public School() {
super();
}
private void initializeArray() {
classroom = new Student[4];
nextAvailablePosition = 0;
}
private void storeStudentInArray(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.storeStudentInArray()";
if (nextAvailablePosition >= classroom.length) {
Student[] biggerClassroom = new Student[(int) (classroom.length * 1.5)];
System.arraycopy(classroom, 0, biggerClassroom, 0, classroom.length);
classroom = biggerClassroom;
}
classroom[nextAvailablePosition] = aStudent;
nextAvailablePosition++;
}
private Student searchForStudentInArray(String searchID) {
assert searchID != null : "Null parameter supplied to School.searchForStudentInArray()";
int index = 0;
while (index < nextAvailablePosition) {
if (searchID.equalsIgnoreCase(classroom[index].getID())) {
return classroom[index];
}
index++;
}
return null;
}
public void initialMenu() {
initializeArray();
boolean stillWorking = true;
do {
messagePane.print("\n"
+ "WELCOME to the Student Database Organizer 1.0!\n"
+ "Here you can store students in a virtual classroom.\n"
+ "\n"
+ "(C)reates a Student\n"
+ "(U)pdate a Student\n"
+ "(D)isplay a Student\n"
+ "(A)ll Students\n"
+ "(E)nd\n"
+ "Enter Letter Here: \n");
String initialResponse = keyboard.nextLine();
String response = initialResponse.trim().toUpperCase();
if (response.length() > 0) {
response = response.substring(0, 1);
if (response.equals("E")) {
stillWorking = false;
} else if (response.equals("U")) {
updateStudent();
} else if (response.equals("D")) {
displayStudent();
} else if (response.equals("C")) {
Student aStudent = createStudent();
if (aStudent != null) {
storeStudentInArray(aStudent);
}
} else if (response.equals("A")) {
gpa();
} else {
messagePane.println("Try again " + initialResponse
+ ", is not a valid choice.\n"
+ "Please enter one of the letters from the specified menu.");
}
} else {
messagePane.println("You must enter one of the letters from the specified menu\n"
+ "before you press \"Enter\".");
}
} while (stillWorking);
}
private Student createStudent() {
messagePane.println(
"\nYou can enter the student's information here: \n");
messagePane.print("What's the Student's name?: ");
String name = keyboard.nextLine();
messagePane.print("What year/grade is the student?: ");
String agrade = keyboard.nextLine();
messagePane.print("Birthday (MMDDYY): ");
int birthday = keyboard.nextInt();
keyboard.nextLine();
messagePane.print("What's their ID number? (1-7 Numbers): ");
String id = keyboard.next();
keyboard.nextLine();
messagePane.print("Course(s) taken: ");
String course = keyboard.nextLine();
double gpa;
messagePane.print("GPA: ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
if (inputScanner.hasNextDouble()) {
gpa = inputScanner.nextDouble();
} else if (inputScanner.hasNext()) {
messagePane.println("You entered something other than a number - the gpa "
+ "has been set to the default of " + Student.DEFAULT_GPA);
gpa = Student.DEFAULT_GPA;
} else {
gpa = Student.DEFAULT_GPA;
}
Student newStudent;
try {
newStudent = Student.create(name,
agrade, birthday, id,
course, gpa );
} catch (Exception anException) {
messagePane.println(" Sorry, I couldn't input the student for you. " + anException.getMessage());
newStudent = null;
}
return newStudent;
}
private void displayStudent() {
Student aStudent = locateStudent();
if (aStudent == null) {
messagePane.println("Sorry, this ID number is not in the classroom.");
} else {
messagePane.println(" " + aStudent.getGrade() + " " + aStudent.getName()
+ " (" + aStudent.getBirthday() + ", " + aStudent.getID() + ") " + "\n"
+ " " + aStudent.getCourse() + " GPA: " + aStudent.getGpa()
);
}
}
private void updateStudent() {
Student aStudent = locateStudent();
if (aStudent == null) {
messagePane.println("Sorry, the student is not listed.");
} else {
updateMenu(aStudent);
}
}
private void updateMenu(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.updateMenu()";
String studentBeforeUpdating = singleLineStudentDisplay(aStudent);
messagePane.println("The Student being updated is: \n" + aStudent);
boolean stillTrying = true;
do {
messagePane.print("\n"
+ "Student Database Organizer 1.0\n"
+ "UPDATE MENU OPTIONS\n"
+ ""
+ "Press 1 to change the Student's name\n"
+ "Press 2 to update grade\n"
+ "Press 3 to update course(s)\n"
+ "Press 4 to update gpa \n"
+ "Press 5 to finish updating current Student\n"
+ ""
+ "\nPlease enter your selection: ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
if (inputScanner.hasNextInt()) {
int response = inputScanner.nextInt();
if (response == 1) {
updateName(aStudent);
} else if (response == 2) {
updateGrade(aStudent);
} else if (response == 3) {
updateCourse(aStudent);
} else if (response == 4) {
updateGpa(aStudent);
} else if (response == 5) {
stillTrying = false;
} else {
messagePane.println(
"You typed " + response + ", which is not a legit option.\n"
+ "Please check the list of numbers in the menu..");
}
} else if (inputScanner.hasNext()) {
String junk = inputScanner.next();
messagePane.println("You entered " + junk + ", which is not a legal option.\n"
+ "Please enter one of the numbers from the specified menu.");
} else {
messagePane.println("Hold your horses! You need to enter a number\n"
+ "before you press \"Enter\".");
}
} while (stillTrying);
messagePane.println("\n" + "Student before updating: " + studentBeforeUpdating);
messagePane.println("Student after updating: " + singleLineStudentDisplay(aStudent));
}
private void updateName(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.updateName()";
int result;
messagePane.println("The student's name is: " + aStudent.getName());
messagePane.print("Now it is...: ");
String name = keyboard.nextLine();
result = aStudent.setName(name);
messagePane.println("\nUpdate status: "
+ Student.getDescriptionOfReturnedSignal(result) );
messagePane.println("\nFinalized changes: " + singleLineStudentDisplay(aStudent));
}
private void updateBirthday(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.updateBirthday()";
int result;
messagePane.println("The current birthday is: " + aStudent.getBirthday());
messagePane.print("New birthday (exactly four digits): ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
if (inputScanner.hasNextInt()) {
int birthday = keyboard.nextInt();
keyboard.nextLine();
result = aStudent.setBirthday(birthday);
messagePane.println("Update status: "
+ Student.getDescriptionOfReturnedSignal(result));
messagePane.println("Finalized Changes: " );
} else {
messagePane.println("You didn't enter a number\n"
+ "Please Check the Format MMDDYY \n\n"
+ "Sorry, no changes were made.");
}
}
private void updateGrade(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.updateGrade()";
int result;
messagePane.println("The student's grade is: " + aStudent.getGrade());
messagePane.print("Now it is... (at least three characters: ");
String agrade = keyboard.nextLine();
result = aStudent.setGrade(agrade);
messagePane.println("Update status: "
+ Student.getDescriptionOfReturnedSignal(result));
messagePane.println("Finalized Changes: " + singleLineStudentDisplay(aStudent));
}
private void updateCourse(Student aStudent){
assert aStudent != null : "Null parameter supplied to School.updateCourse()";
int result;
messagePane.println("The course(s) taken are: " + aStudent.getCourse());
messagePane.print("Now it is...: ");
String course = keyboard.nextLine();
result = aStudent.setCourse(course);
messagePane.println("Update status: "
+ Student.getDescriptionOfReturnedSignal(result));
messagePane.println("Finalized Changes: " + singleLineStudentDisplay(aStudent));
}
private void updateGpa(Student aStudent){
assert aStudent != null: "Null parameter supplied to School.updateGpa()";
int result;
messagePane.println("GPA is: " + aStudent.getGpa());
messagePane.print("Now it is... (Must be Postive Number): ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
double gpa;
if (inputScanner.hasNextDouble())
{
gpa = keyboard.nextDouble();
}
else
{
messagePane.println("You entered something other than a number - " +
"GPA is back to default " + Student.DEFAULT_GPA);
gpa = Student.DEFAULT_GPA;
}
result = aStudent.setGPA(gpa);
messagePane.println("Update status: " +
Student.getDescriptionOfReturnedSignal(result));
messagePane.println("Finalized Changes" + singleLineStudentDisplay(aStudent));
}
private void gpa() {
int studentCount = nextAvailablePosition;
if (studentCount > 0) {
messagePane.println("\nThe student database has " + studentCount + " student(s):");
messagePane.printf(" %25s, %-35s (%4s, %13s) %-30s %9s \n",
"Grade/Standing", "Student's Name", "Birthday", "ID Number",
"Course(s) taken", "GPA");
int index = 0;
while (index < studentCount) {
Student temp = classroom[index];
messagePane.printf(" %25s, %-35s (%4d, %-13s) %-30s %9.2f \n",
temp.getGrade().length() < 25
? temp.getGrade() : temp.getGrade().substring(0, 25),
temp.getName().length() < 35
? temp.getName() : temp.getName().substring(0, 35),
temp.getBirthday(),
temp.getID(),
temp.getCourse().length() < 30
? temp.getCourse() : temp.getCourse().substring(0, 30),
temp.getGpa());
index++;
}
} else {
messagePane.println("The classroom is currently empty.");
}
}
private Student locateStudent() {
Student aStudent;
messagePane.print("\nEnter the Student's ID you would like to find: ");
Scanner inputScanner = new Scanner(keyboard.nextLine());
if (inputScanner.hasNext()) {
String searchID = inputScanner.next();
aStudent = searchForStudentInArray(searchID);
} else {
messagePane.println("Please enter an ID");
aStudent = null;
}
return aStudent;
}
private String singleLineStudentDisplay(Student aStudent) {
assert aStudent != null : "Null parameter supplied to School.singleLineStudentDisplay()";
return aStudent.getGrade() + ", " + aStudent.getName() + " ("
+ aStudent.getID() + ", " + aStudent.getBirthday() + ") "
+ aStudent.getCourse() + " GPA: " + aStudent.getGpa();
}
}
Here is Student :
package student;
public class Student {
public static final int SET_SUCCESSFUL = 0;
public static final int GRADE_CANNOT_BE_NULL = -1;
public static final int GRADE_CANNOT_BE_EMPTY = -2;
public static final int GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS = -3;
public static final int NAME_CANNOT_BE_NULL = -11;
public static final int NAME_CANNOT_BE_EMPTY = -12;
public static final int BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT = -24;
public static final int ID_MUST_BE_ONE_OR_SEVEN_NUMBERS = -31;
public static final int ID_CANNOT_BE_NULL = -32;
public static final int ID_CANNOT_BE_EMPTY = -33;
public static final int COURSE_CANNOT_BE_EMPTY = -41;
public static final int GPA_CANNOT_BE_NEGATIVE = -51;
public static final double DEFAULT_GPA = 0.0;
private String name;
private String grade;
private int birthday;
private String id;
private String course;
private double gpa;
private Student() {
super();
}
public static Student create(String theName,
String theGrade, int theBirthday,String theId,
String theCourse, double theGpa) throws Exception {
Student newStudent = new Student();
int result;
result = newStudent.setName(theName);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setGrade(theGrade);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setBirthday(theBirthday);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setId(theId);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setCourse(theCourse);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
result = newStudent.setGPA(theGpa);
if (result != SET_SUCCESSFUL) {
throw new Exception(Student.getDescriptionOfReturnedSignal(result));}
return newStudent;}
// <editor-fold defaultstate="collapsed" desc="------------------------------------------------------------------------------"> /* */
// </editor-fold>
public String getName() {
return name;}
public String getGrade() {
return grade;}
public int getBirthday() {
return birthday;}
public String getID() {
return id;}
public String getCourse() {
return course;}
public double getGpa() {
return gpa;}
#Override
public String toString() {
StringBuilder temp = new StringBuilder(name);
temp.append("\nwho is a ");
temp.append(grade);
temp.append("\nwith a Birthday on ");
temp.append(birthday);
temp.append("\nID Number ");
temp.append(id);
temp.append("\nwho takes ");
temp.append(course);
temp.append("\nwith a GPA of ");
temp.append(gpa);
temp.append(' ');
return temp.toString();
}
public static String getDescriptionOfReturnedSignal(int aSignal) {
if (aSignal == SET_SUCCESSFUL) {
return "SET_SUCCESSFUL";}
if (aSignal == GRADE_CANNOT_BE_NULL) {
return "GRADE_CANNOT_BE_NULL";}
if (aSignal == GRADE_CANNOT_BE_EMPTY) {
return "GRADE_CANNOT_BE_EMPTY";}
if (aSignal == GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS) {
return "GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS";}
if (aSignal == NAME_CANNOT_BE_NULL) {
return "NAME_CANNOT_BE_NULL";}
if (aSignal == NAME_CANNOT_BE_EMPTY) {
return "NAME_CANNOT_BE_EMPTY";}
if (aSignal == BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT) {
return "BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT";}
if (aSignal == ID_CANNOT_BE_NULL) {
return "ID_CANNOT_BE_NULL";}
if (aSignal == ID_CANNOT_BE_EMPTY) {
return "ID_CANNOT_BE_EMPTY";}
if (aSignal == ID_MUST_BE_ONE_OR_SEVEN_NUMBERS) {
return "ID_MUST_BE_ONE_OR_SEVEN_NUMBERS";}
if (aSignal == COURSE_CANNOT_BE_EMPTY) {
return "COURSE_CANNOT_BE_EMPTY";}
if (aSignal == GPA_CANNOT_BE_NEGATIVE) {
return "GPA_CANNOT_BE_NEGATIVE";}
return "Sorry, but the signal value " + aSignal + " is not recognized.";
}
public int setName(String theName) {
if (theName == null) {
return NAME_CANNOT_BE_NULL;
}
String trimmedName = theName.trim();
if (trimmedName.isEmpty()) {
return NAME_CANNOT_BE_EMPTY;
}
name = trimmedName;
return SET_SUCCESSFUL;
}
public int setGrade(String theGrade) {
if (theGrade == null) {
return GRADE_CANNOT_BE_NULL;
}
String trimmedGrade = theGrade.trim();
if (trimmedGrade.isEmpty()) {
return GRADE_CANNOT_BE_EMPTY;
}
if (trimmedGrade.length() < 6) {
return GRADE_MUST_BE_AT_LEAST_SIX_CHARACTERS;
}
grade = trimmedGrade;
return SET_SUCCESSFUL;
}
public int setBirthday(int theBirthday) {
if (theBirthday <= 7) {
return BIRTHDAY_MUST_BE_EXACTLY_SIX_DIGITS_CHECK_FORMAT;
}
birthday = theBirthday;
return SET_SUCCESSFUL;
}
private int setId(String theId) {
if (theId == null) {
return ID_CANNOT_BE_NULL;
}
String trimmedId = theId.trim();
if (trimmedId.isEmpty()) {
return ID_CANNOT_BE_EMPTY;
}
if (trimmedId.length() != 1 && trimmedId.length() != 7) {
return ID_MUST_BE_ONE_OR_SEVEN_NUMBERS;
}
id = trimmedId;
return SET_SUCCESSFUL;
}
public int setCourse(String theCourse) {
if (theCourse == null) {
course = "";
return SET_SUCCESSFUL;
}
String trimmedCourse = theCourse.trim();
if (trimmedCourse.isEmpty()) {
return COURSE_CANNOT_BE_EMPTY;
}
course = trimmedCourse;
return SET_SUCCESSFUL;
}
public int setGPA(double theGPA) {
if (theGPA < 0.0) {
return GPA_CANNOT_BE_NEGATIVE;
}
gpa = theGPA;
return SET_SUCCESSFUL;
}
/*
public String getbirthday() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
*/
}
Don't have sufficient reputation to comment so adding as answer.
You must remove the current code and specify only the snippets that you tried for 1) Reading the inputs, which I see you are using Scanner 2) What's your approach for sorting
To guide you on this considering this is your classroom program, look at these:
How to read inputs:
How can I read input from the console using the Scanner class in Java?
Comparision:
https://www.baeldung.com/java-comparator-comparable
When should a class be Comparable and/or Comparator?
and then sorting:
https://www.geeksforgeeks.org/collections-sort-java-examples/
https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/

See if name exists in arraylist, if it does, ask for new name

public Event(String name, int numberOfTries) {
this.name = name;
this.numberOfTries = numberOfTries;
}
public String getName() {
return name;
}
public int getNumberOfTries() {
return numberOfTries;
}
public String toString() {
return name + ", " + numberOfTries;
}
public void addEvent() {
scan = new Scanner(System.in);
eventList.add(new Event("Jacob", 5));
System.out.print("Event name: ");
String name = scan.nextLine();
boolean match = true;
for (int i = 0; i < eventList.size(); i++) {
if (eventList.get(i).getName().equalsIgnoreCase(name)) {
match = false;
if (!match) {
System.out.println(name + " has already been added\n");
}
else {
System.out.println("Event name: ");
}
}
}
System.out.print("Attempts allowed: ");
int numberOfTries = scan.nextInt();
scan.nextLine();
eventList.add(new Event(name, numberOfTries));
System.out.println(name + " added\n");
}
When I enter the pre-existing name "Jacob", it goes like this:
"Event name: Jacob
Jacob has already been added
Attempts allowed:"
I want the program to ask me for a new name, since Jacob already exists.
But I can't seem to go back in the loop.
I don't want to use Maps or anything like that, only ArrayLists.
First of all, you can't define match=false; and then ask if(!match). It is going yo be always true.
Instead, write the if...else statement outside of the loop. And when the loop finishes It will check for the match boolean. if (!match) { System.out.println(name + " has already been added\n");} else { System.out.println("Event name: "); match = true;}
Then introduce a loop which checks for match = true so the user can try several times: while(!match){
scan = new Scanner(System.in); eventList.add(new Event("Jacob", 5)); System.out.print("Event name: "); String name = scan.nextLine(); for (int i = 0; i < eventList.size(); i++) { if (eventList.get(i).getName().equalsIgnoreCase(name)) { match = false; } }
if (!match) { System.out.println(name + " has already been added\n"); eventList.removeLast();} else { System.out.println("Event name: "); match = true;}
}
Remember to initiallize the match variable as false, before the while checks it.

How to get the total of each column

Its been a ridiculous task especially to build the total of each vertical column & to show it on screen. Though, calculating the total of horizontal row never seemed to be a challenge.
The problem I'm having is three-fold.
How do I calculate the total of each vertical column ?
The index (id) is getting printed in descending order. How do I make it print in ascending order ?
Further, in the percentage column the value after the decimal point is being discarded. How do I get that displayed? For eg.. if
answer is supposed to be 78.25% it exhibits as 78.0%
P.S : (2 places after the decimal point is what I'm aiming at.)
POJO class -- StudentsProg.java
package com.students.marks;
import java.util.Arrays;
public class StudentsProg {
private int id = 0;
private String name;
private int english;
private int german;
private int french;
private int arabic;
private double percentage;
private int total_marks;
private int rowHighest;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getGerman() {
return german;
}
public void setGerman(int german) {
this.german = german;
}
public int getFrench() {
return french;
}
public void setFrench(int french) {
this.french = french;
}
public int getArabic() {
return arabic;
}
public void setArabic(int arabic) {
this.arabic = arabic;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public int getTotal_marks() {
return total_marks;
}
public void setTotal_marks(int total_marks) {
this.total_marks = total_marks;
}
public int getRowHighest() {
return rowHighest;
}
public void setRowHighest(int rowHighest) {
this.rowHighest = rowHighest;
}
public String toString() {
id = id+1;
return (id + "\t" +name+ "\t\t" +english+ "\t" + " " +german+ "\t" + " "+ french+ "\t" + " " +arabic+ "\t" +" " +total_marks+ "\t\t" + " " +percentage+ "\t\t" +rowHighest);
}
}
StudentsProgMain.java
import java.util.Scanner;
public class StudentsProgMain {
#SuppressWarnings("resource")
public static void main(String[] args) {
int count = 0;
StudentsProg[] stud = new StudentsProg[15];
int choice=0;
int max = 0;
Scanner scanner = new Scanner(System.in);
do{
System.out.println("1: Add new Student");
System.out.println("2: List Student");
System.out.println("3: List Student By Name.");
System.out.println("4: Delete Student");
System.out.println("5: Exit");
System.out.println("Please enter your choice \n\n");
choice=scanner.nextInt();
switch(choice){
case 1:
stud[count] = new StudentsProg();
System.out.println("Enter student name");
stud[count].setName(scanner.next());
System.out.println("Enter marks in English");
stud[count].setEnglish(scanner.nextInt());
System.out.println("Enter marks in German");
stud[count].setGerman(scanner.nextInt());
System.out.println("Enter marks in French");
stud[count].setFrench(scanner.nextInt());
System.out.println("Enter marks in Arabic");
stud[count].setArabic(scanner.nextInt());
count++;
break;
case 2:
System.out.println("ID\t" + "Name \t\t\t" + "English\t" + " " + "German\t"+ " " + "French\t" + " " + "Arabic\t"
+" "+ "Total Marks\t" + " " + "Percentage\t" + "Highest Marks(Row)\n" +
"------------------------------------------------------------------------"
+ "------------------------------------------- \n ");
for(int i=0; i<count; i++){
if(stud[i]!=null){
int total_marks = stud[i].getEnglish()+stud[i].getGerman()+ stud[i].getFrench()+stud[i].getArabic();
stud[i].setTotal_marks(total_marks);
double calc_per = ((total_marks*100)/400);
stud[i].setPercentage(calc_per);
int arrayListMarks [] = {stud[i].getEnglish(), stud[i].getFrench(), stud[i].getGerman(), stud[i].getArabic()};
max = arrayListMarks[0];
for (int j = 1; j < arrayListMarks.length; j++) {
if(arrayListMarks[j] > max)
max = arrayListMarks[j]; }
stud[i].setRowHighest(max);
System.out.println(stud[i].toString());
System.out.println("\n");}
}
System.out.println("--------------------------------------------------------------"
+ "----------------------------------------------------- \n");
System.out.println("\tTotal :" +"\n");
break;
case 3 :
System.out.println("Please enter your name");
String name = scanner.next();
System.out.println("\n" + "ID\t" + "Name \t\t\t" + "English\t" + " " + "German\t"+ " " + "French\t" + " " + "Arabic\t"
+" "+ "Total Marks\t" + " " + "Percentage\t" + "Highest Marks(Row)\n" +
"------------------------------------------------------------------------"
+ "------------------------------------------- \n ");
for(int i =0 ; i<count; i++){
if(stud[i]!=null && stud[i].getName().equals(name))
System.out.println(stud[i].toString()); }
System.out.println("--------------------------------------------------------------"
+ "----------------------------------------------------- \n");
break;
case 4 :
System.out.println("Please enter your name");
String naam = scanner.next();
for (int i = 0; i<count; i++) {
if(stud[i]!=null && stud[i].getName()==naam)
stud[i]=null;
}
break;
case 5:
System.exit(0);
System.out.println("You have exited successfully");
default :
System.out.println("Invalid choice");
}
}while(true);
}
}
The problem with the percentage calculation is that the line of code double calc_per = ((total_marks*100)/400); will do integer arithmetic and truncate each intermediate result as an integer. To fix this you need to include a floating point number somewhere in the calculation either by converting total_marks to double like so:
double calc_per = ((Integer.valueOf(total_marks).doubleValue()*100)/400);
Or using a float constant like so:
double calc_per = ((total_marks*100.0)/400);
Vertical totals should just be a matter of adding the row value to a variable inside your print loop.
I'm not really sure about your index order problem but the code in toString() that reads id = id+1; looks wrong. This will increment the Id each time you call toString(). Instead of that, your creation code should set the value of id just after creating the object, something like:
stud[count] = new StudentsProg();
// add the following line of code.
stud[count].setId(count);
System.out.println("Enter student name");
stud[count].setName(scanner.next());

Create a loop to generate a new "user" with own variable names if user makes number of users = 2, or 3, etc

You don't have to read all my code, don't worry. My main problem is highlighted in the body of this message.
I am very new to programming. I'm supposed to create a Java program that reads a string input, separates that string into chars mapped to an array (that array is a Memo for answers to multiple choice Questions). Then read another string input from user, separate that input into chars in an array as well, and then compare the two array indices. basically, it's supposed to see how many array indices are the same, and then generate a score of correct answers (it's a multiple choice answer program, so the chars in the strings will be A B or C).
I have to store the student's (user's) name and keep his score. But the program will ask you for how many students there are and then run a loop asking of name, and answer (as many times as the amount of students you typed in. Max is 10), then compare the answer to the memo, generate a score, and use all the students answers to calculator an average score. So far I have managed to create a program that will do this for one user. The problem I have is looping it to store multiple user names, and scores, to calculate an average score.
Here is my code. if you copy and paste this into your IDE, you'll see that it runs perfectly (apart from some error handling and JOptionPane dialog button stuff left out). But it will only work IF you enter the number of users as 1. Anything else, and it won't run properly. So how do I get it to loop for several users?
package multiquestions;
import javax.swing.JOptionPane;
public class MultiQuestions {
public static void main(String[] args) {
String aMemo = getInput0();
int aStudentNumber = getInput1();
String aStudentName = getInput2();
String aStudentAnswer = getInput3();
int aScore = CalcScore(aStudentAnswer, aMemo);
if (aStudentNumber == 1) {
StudentInfo(aStudentName, aScore);
}
System.exit(0);
}
public static String getInput0() {
String Memo = JOptionPane
.showInputDialog("Please enter the memo answers to the 10 multiple choice questions\nno spaces and all in Capital letters e.g.ABCDEABCDE");
return Memo;
}
public static int getInput1() {
int StudentNumber = Integer.parseInt(JOptionPane
.showInputDialog("Please enter the number of students in the class"));
return StudentNumber;
}
public static String getInput2() {
String StudentName = JOptionPane.showInputDialog("Please enter the student's name");
return StudentName;
}
public static String getInput3() {
String StudentAnswer = JOptionPane
.showInputDialog("Please enter the student's answers to the 10 multiple choice questions\nno spaces and all in Capital letters e.g.ABCDEABCDE");
return StudentAnswer;
}
public static int CalcScore(String bStudentAnswer, String bMemo) {
int One;
int Two;
int Three;
int Four;
int Five;
int Six;
int Seven;
int Eight;
int Nine;
int Ten;
char Reference[] = new char[10];
for (char Ref : Reference) {
Reference[0] = bMemo.charAt(0);
Reference[1] = bMemo.charAt(1);
Reference[2] = bMemo.charAt(2);
Reference[3] = bMemo.charAt(3);
Reference[4] = bMemo.charAt(4);
Reference[5] = bMemo.charAt(5);
Reference[6] = bMemo.charAt(6);
Reference[7] = bMemo.charAt(7);
Reference[8] = bMemo.charAt(8);
Reference[9] = bMemo.charAt(9);
}
char Answer[] = new char[10];
for (char Ans : Answer) {
Answer[0] = bStudentAnswer.charAt(0);
Answer[1] = bStudentAnswer.charAt(1);
Answer[2] = bStudentAnswer.charAt(2);
Answer[3] = bStudentAnswer.charAt(3);
Answer[4] = bStudentAnswer.charAt(4);
Answer[5] = bStudentAnswer.charAt(5);
Answer[6] = bStudentAnswer.charAt(6);
Answer[7] = bStudentAnswer.charAt(7);
Answer[8] = bStudentAnswer.charAt(8);
Answer[9] = bStudentAnswer.charAt(9);
}
/*
* Below is the list of if statements which add one to each variable (Variables One to Ten
* declared at top of this method) if the array characters match each other at their indeces
*/
if (Reference[0] == Answer[0]) {
One = 1;
} else {
One = 0;
}
if (Reference[1] == Answer[1]) {
Two = 1;
} else {
Two = 0;
}
if (Reference[2] == Answer[2]) {
Three = 1;
} else {
Three = 0;
}
if (Reference[3] == Answer[3]) {
Four = 1;
} else {
Four = 0;
}
if (Reference[4] == Answer[4]) {
Five = 1;
} else {
Five = 0;
}
if (Reference[5] == Answer[5]) {
Six = 1;
} else {
Six = 0;
}
if (Reference[6] == Answer[6]) {
Seven = 1;
} else {
Seven = 0;
}
if (Reference[7] == Answer[7]) {
Eight = 1;
} else {
Eight = 0;
}
if (Reference[8] == Answer[8]) {
Nine = 1;
} else {
Nine = 0;
}
if (Reference[9] == Answer[9]) {
Ten = 1;
} else {
Ten = 0;
}
int Score = One + Two + Three + Four + Five + Six + Seven + Eight + Nine + Ten;
return Score;
}
public static void StudentInfo(String bStudentName, int bScore) {
switch (bScore) {
/*
* Below is case stament for values of bScore(score returned from CalcScore() For each value of
* bScore it must do something specific
*/
case 10:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 A Marvelous");
break;
case 9:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 A Marvelous");
break;
case 8:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 B Outstanding");
break;
case 7:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 C Significant");
break;
case 6:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore
+ "/10 D Above Average");
break;
case 5:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore
+ "/10 E Barely Adequate");
break;
case 4:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 F Fail");
break;
case 3:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 F Fail");
break;
case 2:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 F Fail");
break;
case 1:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 F Fail");
break;
case 0:
JOptionPane.showMessageDialog(null, bStudentName + " " + bScore + "/10 F Fail");
}
}
public static void Exit() {
int exit = JOptionPane.showConfirmDialog(null, "Are you sure you want to exit?");
if (exit == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
public static void CalcAverage() {}
}
Might be helpful for learning purpose (assuming strings are not null and lengths of strings are equal):
public static int CalcScore(String bStudentAnswer, String bMemo) {
char[] answer = bStudentAnswer.toCharArray();
char[] memo = bMemo.toCharArray();
int score = 0;
for (int i = 0; i < answer.length; i++) {
if (answer[i] == memo[i]) score++;
}
return score;
}
instead of saying if == 1, do
for (int i = 0; i < aStudentNumber; i++) {
String aStudentName = getInput2();
String aStudentAnswer = getInput3();
int aScore = CalcScore(aStudentAnswer, aMemo);
StudentInfo(aStudentName, aScore);
}
Now, if you want to store that data programmatically so you can access it later on, change your StudentInfo method to something like
public static StudentInfo createStudentInfo(String bStudentName, int bScore){
...
return someObj;
}
where someObj is a an instance of a StudentInfo class (that you have to create) that actually holds all of the data you want to keep track of. Then, simply add that class to a list (inside your loop):
ArrayList<StudentInfo> siList = new ArrayList<StudentInfo>();
for (int i = 0; i < aStudentNumber; i++) {
String aStudentName = getInput2();
String aStudentAnswer = getInput3();
int aScore = CalcScore(aStudentAnswer, aMemo);
//StudentInfo(aStudentName, aScore); // get rid of this line since we are adding it to a list now
siList.add(createStudentInfo(aStudentName, aScore));
}
Now you can recall all of that data if need be.
The biggest thing is that you need a loop. Loop until the index is at your count, and perform the same actions for each answer set.
Edit: The following is to address the question posted in the comments.
I think you're better off with a constructor. Use a class something like this:
public class StudentInfo {
private String bStudentName;
private int bScore;
public StudentInfo (String bStudentName, int bScore) {
this.bStudentName = bStudentName;
this.bScore = bScore;
}
public String getStudentName() {
return this.bStudentName; //'this' keyword not really necessary, but helpful
}
public int getScore() {
return this.bScore;// again, 'this' not necessary
}
public void doStuff() { // optional method to do stuff with the data if need be
...
}
}
Then, in your loop, do
ArrayList<StudentInfo> siList = new ArrayList<StudentInfo>();
for (int i = 0; i < aStudentNumber; i++) {
String aStudentName = getInput2();
String aStudentAnswer = getInput3();
int aScore = CalcScore(aStudentAnswer, aMemo);
//StudentInfo(aStudentName, aScore); // get rid of this line since we are adding it to a list now
//siList.add(createStudentInfo(aStudentName, aScore));
StudentInfo si = new StudentInfo(aStudentName, aScore);
si.doStuff(); // optional method call in case you want to do something with the data other than store it.
siList.add(si);
}
your StudentInfo class should be in the same package as your main class. If, for some reason, it is not, at the top of your main class add include theotherpackage.StudentInfo;

How can I Enhance my AddressBook addEntry() method?

I have an Address Book Program that [1] adds Entry [2] delete entry [3] update/edit entry [4] view all entry and [5] view specific entry..
Entries were stored in an Array entry[] like:
entry[counter] = new AddressBookEntry();
It all runs properly but the thing is... i want there was a checking if the user's input name was already used or if the user doesn't typed anything when i ask "Enter Name: "
here's my addEntry() method:
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
It allows user input any Entry he likes... but no checking if the name is already used and if the user leave the "Enter Name: " blank it still allows the user to proceed to the "Enter Add.: "
here's my complete code in my main program:
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class AddressBook {
private AddressBookEntry entry[];
private int counter;
private String SName;
private int notfound = 0;
public static void main(String[] args) {
AddressBook a = new AddressBook();
a.entry = new AddressBookEntry[100];
int option = 0;
try {
while (option != 5) {
String content = "Choose an Option\n\n"
+ "[1] Add an Entry\n"
+ "[2] Delete an Entry\n"
+ "[3] Update an Entry\n"
+ "[4] View all Entries\n"
+ "[5] View Specific Entry\n"
+ "[6] Exit";
option = Integer.parseInt(JOptionPane.showInputDialog(content));
switch (option) {
case 1:
a.addEntry();
break;
case 2:
a.deleteEntry();
break;
case 3:
a.editEntry();
break;
case 4:
a.viewAll();
break;
case 5:
a.searchEntry();
break;
case 6:
System.exit(1);
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Choice!");
}
}
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Please Choose a Number in the displayed Menu");
}
}
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
public void viewAll() {
String addText = " NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n\n";
int nonNull = 0;
for (int i = 0; i < entry.length; i++) {
if (entry[i] != null) {
addText = addText + entry[i].getInfo() + "\n";
nonNull++;
}
if (nonNull == counter) {
break;
}
}
JOptionPane.showMessageDialog(null, new JTextArea(addText));
}
public void searchEntry() {
SName = JOptionPane.showInputDialog("Enter Name to find: ");
searchMethod();
}
public void searchMethod() {
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, entry[i].getInfo2());
notfound = 0;
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
}
public void editEntry() {
SName = JOptionPane.showInputDialog("Enter Name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
entry[i] = new AddressBookEntry();
entry[i].setName(JOptionPane.showInputDialog("Enter new name: "));
entry[i].setAdd(JOptionPane.showInputDialog("Enter new add: "));
entry[i].setPhoneNo(JOptionPane.showInputDialog("Enter new Phone No.: "));
entry[i].setEmail(JOptionPane.showInputDialog("Enter new E-mail: "));
notfound = 0;
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
}
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;
break;
}
}
}
}
Hope you can can help me I am new in Java and I really don't what to add in my code for checking.
* What should I add in my addEntry() method to check if the name was already used or no name entered?
* Do I need a condition like in my searchMethod()?
An address book tends to be a thing where given a name, you look up an address, and other information.
so this falls under a general pattern where you have a Key (the name) and a value (the other information)
When ever you see this, you want to think of using a Map
So, i'd recommend instead of putting your AddressBookEntry's in an array, use a map like this
Map<String, AddressBookEntry> addressBook = new HashMap<String, AddressBookEntry>();
then when you want to add a new entry do
addressBook.put("John", new AddressBookEntry());
the nice thing about a map is that you can only have one entry for the same person.
So you don't have to worry about what happens if you put John in the book twice. It will only allow one in there.

Categories

Resources