Scanner requesting multiple inputs before giving final output - java

So I'm new to Java and am trying to pass a variable from the scanner to my getter/setter method so that depending on the number entered it'll sort the array differently.
I've got it where the list will sort; problem is my scanner repeats where you have to enter your selection in multiple times before the list shows up.
I know the problem has to do with the call "int c = assign_6.choice()". If I hard code in a number it's fine but it appears to be making multiple calls to the choice() function.
I've tried moving the function out of the main and removing the Comparable in my setter/getter file and also removing the quick sort and using Array and Collections. None of which worked.
I feel like it's probably a stupid mistake I'm making and missing it due to not knowing Java that well. Could use help in figuring this out.
Here's my output:
nter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
contacts [age=20, state=Alabama, firstname=Pickles, lastname=Cattle]
contacts [age=35, state=New York, firstname=George, lastname=Constanza]
contacts [age=90, state=Florida, firstname=Adam, lastname=Tree]
contacts [age=32, state=Illinois, firstname=Mary, lastname=Upton]
contacts [age=58, state=Washington, firstname=Bob, lastname=Wiseman]
Code:
import java.util.Scanner;
public class test_6 {
public static void main(String[] args) {
Contacts[] a = {
new Contacts(32, "Illinois", "Mary", "Upton"),
new Contacts(58, "Washington", "Bob", "Wiseman"),
new Contacts(20, "Alabama", "Pickles", "Cattle"),
new Contacts(35, "New York", "George", "Constanza"),
new Contacts(90, "Florida", "Adam", "Tree"),
};
Quick.sort(a);
for (Contacts contacts:a){
System.out.println(contacts);
}
}
public static int choice() {
System.out.print("Enter number 1,2 or 3: ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
return i;
}
}
public class Contacts implements Comparable<Contacts>{
Integer age;
String state;
String firstname;
String lastname;
int c = test_6.choice();
public Contacts(Integer age, String state, String firstname, String lastname){
this.age = age;
this.state = state;
this.firstname = firstname;
this.lastname = lastname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int compareTo(Contacts contacts) {
if (c == 1){
return this.getLastname().compareTo(contacts.getLastname());
}
else if (c == 2){
return this.getState().compareTo(contacts.getState());
}
else if (c == 3){
return this.getAge().compareTo(contacts.getAge());
}
else return 0;
}
#Override
public String toString() {
return "contacts [age=" + age + ", state=" + state + ", firstname=" + firstname + ", lastname=" + lastname
+ "]";
}
}

I'm not entirely sure, you could debug, but it may be something to do with your function being assigned in the global scope. You are better to move the static function choice() to your Contacts class/object.
Then call the choice() function from inside the initializer Contacts. For example:
import java.util.Scanner;
public class test_6 {
public static void main(String[] args) {
Contacts[] a = {
new Contacts(32, "Illinois", "Mary", "Upton"),
new Contacts(58, "Washington", "Bob", "Wiseman"),
new Contacts(20, "Alabama", "Pickles", "Cattle"),
new Contacts(35, "New York", "George", "Constanza"),
new Contacts(90, "Florida", "Adam", "Tree"),
};
Quick.sort(a);
for (Contacts contacts:a){
System.out.println(contacts);
}
}
//Function Choice Moved to Contacts.choice()
}
public class Contacts implements Comparable<Contacts>{
Integer age;
String state;
String firstname;
String lastname;
int c;
public Contacts(Integer age, String state, String firstname, String lastname){
this.age = age;
this.state = state;
this.firstname = firstname;
this.lastname = lastname;
this.c = choice();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int compareTo(Contacts contacts) {
if (c == 1){
return this.getLastname().compareTo(contacts.getLastname());
}
else if (c == 2){
return this.getState().compareTo(contacts.getState());
}
else if (c == 3){
return this.getAge().compareTo(contacts.getAge());
}
else return 0;
}
public static int choice() {
System.out.print("Enter number 1,2 or 3: ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
return i;
}
#Override
public String toString() {
return "contacts [age=" + age + ", state=" + state + ", firstname=" + firstname + ", lastname=" + lastname
+ "]";
}
}

I don't have enough rep to comment but I feel like it could be your sc.nextInt() statement. try to call sc.close() before you return I and see if that solves your problem.

Related

Edit and Update ArrayList in Java

I am trying to update myArray list by allowing the user to change their first and last name while keeping other information in the arraylist the same.
the code follows
public void editStudentID(int findStudentId) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() != findStudentId) {
continue;
}
System.out.println("Found a profile containing information for " + findStudentId + ":");
System.out.println("What would you like to change in your profile?");
System.out.println("1.First Name");
System.out.println("2.Last Name");
int decision = scanner.nextInt();
switch (decision) {
case 1:
System.out.println("Enter a new first name to continue");
String newFirstName = scanner.next();//need to find a way to update this in my arraylist
break;
case 2:
System.out.println("Enter a new last name to continue");
String newLastName = scanner.next();//this as well
break;
}
return;
}
System.out.println(" Id not found ");
}
this is my Student class where I only wrote final for only my id and dob to not be changed by the user
public class Student {
private final int id;
private String firstName;
private String lastName;
private final String dob;
public Student(int id, String firstName, String lastName, String dob) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
}
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getDob() {
return dob;
}
public static Student createStudentID(int id, String firstName, String lastName, String dob) {
return new Student(id, firstName, lastName, dob);
}
}
First, you need to make you Student class mutable, but supplying a couple of "setters" which will allow you to change the first and last name properties, for example
public class Student {
//...
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Then in you editStudentID method, you simply update the required record, for example
public void editStudentID(int findStudentId) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() != findStudentId) {
continue;
}
System.out.println("Found a profile containing information for " + findStudentId + ":");
System.out.println("What would you like to change in your profile?");
System.out.println("1.First Name");
System.out.println("2.Last Name");
int decision = scanner.nextInt();
switch (decision) {
case 1:
System.out.println("Enter a new first name to continue");
String newFirstName = scanner.next();//need to find a way to update this in my arraylist
students.get(i).setFirstName(newFirstName);
break;
case 2:
System.out.println("Enter a new last name to continue");
String newLastName = scanner.next();//this as well
students.get(i).setLastName(newFirstName);
break;
}
return;
}
System.out.println(" Id not found ");
}

Trouble completing a Java ArrayList sorting program that asks user how to sort ArrayList

My code is within a package and divided into two separate .java file files. It prints a list of options for how the ArrayList can be sorted, which the user can select by entering the right number. However, for some reason it does not print any sorted list after I input, well anything. Can anyone help?
Here is my custom Object class, Contact.java:
package Sorter;
import java.util.Comparator;
public class Contact {
private String firstName;
private String lastName;
private String state;
private Integer age;
public Contact(String firstName, String lastName, String state, Integer age) {
this.firstName = firstName;
this.lastName = lastName;
this.state = state;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Integer getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static Comparator<Contact> lastNameComparator = new Comparator<Contact>() {
public int compare(Contact s1, Contact s2) {
String contactLastName1 = s1.getLastName().toUpperCase();
String contactLastName2 = s2.getLastName().toUpperCase();
return contactLastName1.compareTo(contactLastName2);
}
};
public static Comparator<Contact> stateComparator = new Comparator<Contact>() {
public int compare(Contact s1, Contact s2) {
String state1 = s1.getState().toUpperCase();
String state2 = s2.getState().toUpperCase();
return state1.compareTo(state2);
}
};
public static Comparator<Contact> ageComparator = new Comparator<Contact>() {
public int compare(Contact s1, Contact s2) {
int age1 = s1.getAge();
int age2 = s2.getAge();
return age1 - age2;
}
};
#Override
public String toString() {
return ("First Name: " + firstName + ", Last Name: " + lastName + ", State: " + state + ", Age: " + age);
}
}
And here is my Sort.java:
package Sorter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class TestSortOptions {
public static void main(String[] args) {
ArrayList<Contact> contacts = initializeContactsArray();
promptForOption(contacts);
}
private static ArrayList<Contact> initializeContactsArray() {
ArrayList<Contact> contacts = new ArrayList<Contact>();
contacts.add(new Contact("Joe", "Jones", "IL", 35));
contacts.add(new Contact("Bill", "Barnes", "OH", 62));
contacts.add(new Contact("Ida", "Know", "FL", 23));
contacts.add(new Contact("Adam", "Ant", "MI", 14));
contacts.add(new Contact("Jane", "Doe", "CA", 41));
return contacts;
}
private static void promptForOption(ArrayList<Contact> contacts) {
Scanner input = new Scanner(System.in);
System.out.println("Options \nSort by Last Name: [1] " + "\nSort by Home State: [2] "
+ "\nSort by Age: [3] " + "\nExit Application: [0] " + "\n\nPlease enter your choice: ");
String answer = input.next();
if (answer == "1") {
Collections.sort(contacts, Contact.lastNameComparator);
for (Contact contact : contacts) {
System.out.println(contact);
}
if (answer == "2") {
Collections.sort(contacts, Contact.stateComparator);
for (Contact contact : contacts) {
System.out.println(contact);
}
if (answer == "3") {
Collections.sort(contacts, Contact.ageComparator);
for (Contact contact : contacts) {
System.out.println(contact);
}
if (answer == "0") {
System.exit(0);
}
else {
System.out.println("Invalid Entry");
}
}
}
}
}
}
Your are trying to print contact list after every option. It would be better to call it once. Replace definition of your promptForOption API with the code given below
private static void promptForOption(ArrayList<Contact> contacts) {
Scanner input = new Scanner(System.in);
System.out.println("Options \nSort by Last Name: [1] " + "\nSort by Home State: [2] "
+ "\nSort by Age: [3] " + "\nExit Application: [0] " + "\n\nPlease enter your choice: ");
String answer = input.next();
switch(answer)
{
case "1":Collections.sort(contacts, Contact.lastNameComparator);
break;
case "2":Collections.sort(contacts, Contact.stateComparator);
break;
case "3":Collections.sort(contacts, Contact.ageComparator);
break;
case "4":Collections.sort(contacts, Contact.ageComparator);
break;
case "0":
default: System.out.println("Invalid Entry");
System.exit(0);
}
for (Contact contact : contacts) {
System.out.println(contact);
}
}
You need to also update constructor definition to capture age.
public Contact(String firstName, String lastName, String state, Integer age) {
this.firstName = firstName;
this.lastName = lastName;
this.state = state;
this.age=age;
}
It seems as though you are nesting the if statements when you really shouldn't be. It should be in the format:
if (answer.equals("1")) {
//Do business
} else if (answer.equals("2") {
//Do other business
} else if (answer.equals("3") {
//Do other other business
} else {
//Bad input
}
A switch case can also be used if you would like:
switch(input.next) {
case "1":
//Do business
break;
case "2":
//Do other business
break;
case "3":
//Do other other business
break;
default:
//Bad input
break;
}
Keep in mind the flow of your method now:
If the user inputs "1", then sort in the lastName method and then print in the for-loop. You are then checking if the answer is "2", which it obviously is not because you are still within the "if it is '1'" block (and you aren't taking in any additional input). Remember that when you open an if-block, anything you put inside it will be executed if the condition is true. If you look at your code and reason through the flow, you will see what is flawed about your control statements. To exit with System.exit(0) in your last conditional statement, the answer would have to be 1, 2, 3 and 0.
Also, see Leozeo's answer for the business logic code and refactoring to remove code duplication in each control statement.

AddressBook in Java

I have to create an address book in java. I have gotten stuck in one area. When I add a second address it makes the first one null. I have areas commented out that I haven't gotten to yet so ignore those areas. I am at a loss why the first address turns to null.
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
class Program2 {
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("\nWelcome. Address book is loaded.");
loop: while(true) {
displayOptions();
int choice = s.nextInt();
switch(choice) {
case 1:
System.out.println("**Choice 1**");
AddressBook.display();
break;
case 2:
System.out.println("**Choice 2**");
System.out.print("First Name: ");
String firstName = s.next();
System.out.print("Last Name: ");
String lastName = s.next();
System.out.print("Phone Number: ");
String phone = s.next();
Contact test = new Contact(firstName, lastName, phone);
AddressBook.add(test);
break;
case 3:
System.out.println("**Choice 3**");
break;
case 4:
System.out.println("**Choice 4**");
break;
case 5:
break loop;
}
}
System.out.println("\nAddress book is saved to file.\n");
System.out.println("Good bye.\n");
System.exit(0);
}
private static void displayOptions() {
System.out.println("\nWhat would you like to do?");
System.out.println(" 1) Display all contacts\n" +
" 2) Add a contact\n" +
" 3) Remove a contact\n" +
" 4) Search a contact\n" +
" 5) Exit");
System.out.print("Your choice: ");
}
}
class Contact {
private String firstName;
private String lastName;
private String phone;
public Contact(String firstName, String lastName, String phone) {
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
}
public String getFirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getPhone() {return phone;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public void setLastName(String lastName) {this.lastName = lastName;}
public void setPhone(String phone) {this.phone = phone;}
/*public boolean equals(Object o) {
if (o instanceof Contact) {
Contact contacts = (Contact) o;
return (firstName.equals(contacts.getFirstName()) &&
lastName.equals(contacts.getLastName()));
}
return false;
}*/
public String toString() {
return firstName + " " + lastName + "\t\t" + phone;
}
}
class AddressBook {
public final static int CAPACITY = 100;
static private Contact[] contacts;
static private int count = 0;
static private String addressFile = "address.txt";
static File file = new File(addressFile);
public AddressBook(String addressFile) {
this.addressFile = addressFile;
}
public static boolean add(Contact c) {
contacts = new Contact[CAPACITY];
if (count < CAPACITY) {
contacts[count++] = c;
}
return false;
}
//public boolean remove(fullname) { }
//public Contact search(fullname) { }
public static void display() {
System.out.println("Name\t\t\tPhone Number");
System.out.println("-------------------------------------");
for (int i=0; i<count; i++) {
System.out.println(contacts[i]);
}
System.out.println("-------------------------------------");
}
/*public boolean load() {
try {
Scanner sF = new Scanner(file);
while (s.hasNext()) {
String line = s.nextLine();
System.out.println(line);
}
s.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/*public boolean save() {
try {
FileWriter writer = new FileWriter(addressFile);
writer.write();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}*/
//public boolean contains(String firstName, String lastName) {
// return this.contacts.contains(firstName, lastName);
//}
}
Your add method overwrites the contacts array, so each time it is called, the references to the previous Contacts are lost :
public static boolean add(Contact c) {
contacts = new Contact[CAPACITY]; // remove this line
if (count < CAPACITY) {
contacts[count++] = c;
}
return false;
}
Instead of the removed line, initialize the contacts array only once :
static private Contact[] contacts = new Contact[CAPACITY];

JAVA: Modify, Delete, List an arraylist addressbook

Be kind, i am learning.
I am creating a addressbook and I need the added names to go into an arraylist. The problem I am having is with modifying, deleting and listing all in arraylist. How do I go about this?
Here is my class file:
import java.text.SimpleDateFormat;
import java.text.DecimalFormat;
import java.util.*;
public class AddressBook {
private static int totalNumber;
public static int getTotal() {
//Returns total number of employees
return totalNumber;
}
private Date lastModified;
private String fullname;
private String address;
private String city;
private String state;
private String zip;
private String phone;
public AddressBook() {
super();
}
/*public AddressBook(Date lastModified, String fullname, String address, String city, String state, String zip, String phone, int month, int day, int year) {
this.fullname = fullname;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
this.phone = phone;
GregorianCalendar calendar = new GregorianCalendar(year, month-1, day );
this.lastModified = calendar.getTime();
}*/
public AddressBook(String fullname, String address, String city, String state, String zip, String phone) {
this.fullname = fullname;
this.address = address;
this.city = city;
this.state = state;
this.zip = zip;
this.phone = phone;
}
public Date getLastModified() {
return lastModified;
}
public void setLastModified(int month, int day, int year) {
month = 00;
day = 00;
year = 0000;
return;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#Override
public String toString() {
return "Employee [name=" + this.fullname + ", Address=" + this.address + ", City="
+ this.city + ", state=" + this.state + ", zip=" + this.zip
+ ", phone=" + this.phone + "]";
}
}
Here is the test file:
import java.util.*;
public class testAddressBook {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
boolean switcher = true;
do {
System.out.println("\n\tAddress Book Menu");
System.out.println("\n\t\tEnter A to (A)dd Person ");
System.out.println("\t\tEnter D to (D)elete Person");
System.out.println("\t\tEnter M to (M)odify Person");
System.out.println("\t\tEnter S to (S)earch Address Book ");
System.out.println("\t\tEnter L to (L)ist ALL (sorted) ");
System.out.println("\t\tEnter Q to Quit");
System.out.print("\n\tPlease enter your choice: ");
char choice = sc.nextLine().toUpperCase().charAt(0);
while ((choice != 'A') && (choice != 'D') && (choice != 'M') && (choice != 'S') && (choice != 'L')&& (choice != 'Q')) {
System.out.println("Invalid choice! Please select (A)dd, (D)elete, (M)odify, (S)earch, (L)ist or (Q)uit: ");
choice = sc.nextLine().toUpperCase().charAt(0);
}
AddressBook newPerson = new AddressBook();
ArrayList<AddressBook> person = new ArrayList<>();
switch (choice) {
case 'A' :
System.out.println("\nTo add a person, follow the prompts.");
System.out.print("\nEnter Fullname: ");
newPerson.setFullname(sc.nextLine());
System.out.print("Enter Address: ");
newPerson.setAddress(sc.nextLine());
System.out.print("Enter City: ");
newPerson.setCity(sc.nextLine());
System.out.print("Enter State: ");
newPerson.setState(sc.nextLine());
System.out.print("Enter Zip: ");
newPerson.setZip(sc.nextLine());
System.out.print("Enter Phone Number: ");
newPerson.setPhone(sc.nextLine());
person.add(new AddressBook(newPerson.getFullname(), newPerson.getAddress(), newPerson.getCity(), newPerson.getState(), newPerson.getZip(), newPerson.getPhone()));
System.out.println(person.get(0));
System.out.println("\nYou have successfully added a new person!");
break;
case 'D' :
break;
case 'M' :
break;
case 'S' :
break;
case 'L' :
break;
case 'Q' :
switcher = false;
System.exit(0);
break;
default:
}
}
while (switcher != false);
}}
Here is your ArrayList java doc.
Here is some information on the for-loop
Look at.
get()
add()
remove()
person.get(0) is the actually your AddressBook object. You will be able to modify that entry using that
Hope this gives enough hints to get you started.
Beginner tip: Just remember to keep your steps small. Once you are able to create a single entry, modify, then delete it. Do it for two. Notice the duplicate code... and then program it with the loop
Some errors in what you have so far:
AddressBook newPerson = new AddressBook();
ArrayList<AddressBook> person = new ArrayList<>();
// ... adding values to your newPerson
person.add(new AddressBook(newPerson.getFullname(), newPerson.getAddress(), newPerson.getCity(), newPerson.getState(), newPerson.getZip(), newPerson.getPhone()));
You are populating your person. Then creating a new person with the same values of the populated person. You could simply pass your original person into the arraylist
person.add(newPerson);
There are multiple suggestions for you:
Use meaningful names. For example ArrayList<AddressBook> should have been named listOfAddressBook etc.
You can directly add the AddressBook object to list: I mean:
person.add(newPerson) and not person.add(new AddressBook(newPerson.getFullname(), newPerson.getAddress(), newPerson.getCity(), newPerson.getState(), newPerson.getZip(), newPerson.getPhone())); And again there is a confusion that object is of type AddressBook but name is newPerson.
There are methods to remove an item or modify an item in ArrayList and it is better to read about them to improve your learning rather than asking for help. I encourage you to read about them in JLS.
Also you can declare your list as:
List<AddressBook> person = new ArrayList<>(); so go and find out why this ie better than your approach.

How to search for an element in an array? and How to add variables with declared methods into an array list?

I have 2 major troubles (that I'm aware of) with this program. Firstly, I don't know how to get FinalGrade and LetterGrade into the array. Secondly, I don't know how to use last name and first name to search for a student in the array. Let me know if you find other problems with my program. Thanks
This is the 1st class
package student;
public class Person {
protected String FirstName, LastName;
//Constructor
public Person(String FirstName, String LastName) {
this.FirstName = FirstName;
this.LastName = LastName;
}
//Getters
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return LastName;
}
//Setters
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
}
This is the 2nd class:
package student;
import java.util.ArrayList;
import java.util.Scanner;
public class Student extends Person{
private int HomeworkAve, QuizAve, ProjectAve, TestAve;
private double FinalGrade;
private String LetterGrade;
//Constructor for the averages
public Student(int HomeworkAve, int QuizAve, int ProjectAve, int TestAve, String FirstName, String LastName)
{
super(FirstName, LastName);
this.HomeworkAve = HomeworkAve;
this.QuizAve = QuizAve;
this.ProjectAve = ProjectAve;
this.TestAve = TestAve;
}
//Method to calculate final grade and letter grade
//Final grade calculation
public double CalcGrade (int HomeworkAve, int QuizAve, int ProjectAve, int TestAve)
{
FinalGrade = (double)(0.15*HomeworkAve + 0.05*QuizAve + 0.4 * ProjectAve + 0.4*TestAve);
return FinalGrade;
}
//Letter grade calculation
public String CalcGrade ( double FinalGrade)
{
if ( FinalGrade >= 90.00)
LetterGrade="A";
else if(FinalGrade >= 80.00)
LetterGrade="B";
else if(FinalGrade>=70.00)
LetterGrade="C";
else if(FinalGrade>=60.00)
LetterGrade="D";
else LetterGrade="F";
return LetterGrade;
}
public String getFullName (String FirstName,String LastName)
{
String str1 = FirstName;
String str2 = LastName;
String FullName = str1+","+str2;
return FullName;
}
public Student(int HomeworkAve, int QuizAve, int ProjectAve, int TestAve, double FinalGrade, String LetterGrade, String FirstName, String LastName) {
super(FirstName, LastName);
this.HomeworkAve = HomeworkAve;
this.QuizAve = QuizAve;
this.ProjectAve = ProjectAve;
this.TestAve = TestAve;
this.FinalGrade = FinalGrade;
this.LetterGrade = LetterGrade;
}
//Setters for this student class
public void setHomeworkAve(int HomeworkAve) {
this.HomeworkAve = HomeworkAve;
}
public void setQuizAve(int QuizAve) {
this.QuizAve = QuizAve;
}
public void setProjectAve(int ProjectAve) {
this.ProjectAve = ProjectAve;
}
public void setTestAve(int TestAve) {
this.TestAve = TestAve;
}
public void setFinalGrade(int FinalGrade) {
this.FinalGrade = FinalGrade;
}
public void setLetterGrade(String LetterGrade) {
this.LetterGrade = LetterGrade;
}
//Getters for this student class
public int getHomeworkAve() {
return HomeworkAve;
}
public int getQuizAve() {
return QuizAve;
}
public int getProjectAve() {
return ProjectAve;
}
public int getTestAve() {
return TestAve;
}
public double getFinalGrade() {
return FinalGrade;
}
public String getLetterGrade() {
return LetterGrade;
}
public void DisplayGrade (){
System.out.println(FirstName+" "+LastName+"/nFinal Grade: "+FinalGrade+"/nLetter Grade: "+ LetterGrade);
}
public static void main(String[] args){
Scanner oScan = new Scanner(System.in);
Scanner iScan = new Scanner(System.in);
boolean bContinue = true;
int iChoice;
ArrayList<Student> students = new ArrayList<>();
while (bContinue == true)
{
//The menu
System.out.println("1. New Class List");
System.out.println("2. Search for a Student");
System.out.println("3. Exit");
System.out.println("Choose an item");
iChoice = iScan.nextInt();
//The 1st case: when the user wants to enter the new list
if (iChoice == 1){
System.out.println("Enter the number of students");
int numberOfStudents = iScan.nextInt();
for(int iCount = 0;iCount < numberOfStudents;){
System.out.println("Enter the name for Student " + ++iCount);
System.out.println("Enter First Name");
String FirstName = oScan.nextLine();
System.out.println();
System.out.println("Enter Last Name");
String LastName = oScan.nextLine();
System.out.println();
System.out.println("Enter Homework Average");
int HomeworkAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Quiz Average");
int QuizAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Project Average");
int ProjectAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Test Average");
int TestAve = iScan.nextInt();
System.out.println();
How to get FinalGrade and LetterGrade??
Student hobbit = new Student(HomeworkAve,QuizAve, ProjectAve,TestAve,FirstName, LastName);
students.add(hobbit);
}
}
//The 2nd case: when the user wants to search for a student
else if (iChoice == 2)
{
System.out.println("Enter First Name");
String FirstName = oScan.nextLine();
System.out.println();
System.out.println("Enter Last Name");
String LastName = oScan.nextLine();
System.out.println();
Here is my revised code to find the student but I don't know how to print the array after I found it
int i = 0;
for (Student student : students) {
if (FirstName != null & LastName != null);{
if (student.getFirstName().equals(FirstName) && student.getLastName().equals(LastName)) {
System.out.println(students.get(i)); //this doesn't work
break;
}
i++;
}
}
//The 3r case: when the user wants to exit
else if (iChoice == 3)
{
bContinue = false;
}
}
}
}
You have an ArrayList of type Student and you are doing indexOf on a variable of type String. You will have to traverse the entire ArrayList and then do a comparison to find out if the student name mathces. Sample code:
int i = 0;
for (Student student : students) {
// Add null checks if first/last name can be null
if (student.getFirstName().equals(firstName) && student.getLastName().equals(lastName)) {
System.out.println("Found student at " + i);
break;
}
i++;
}
FinalGrade and LetterGrade are variables in each object, I think you are mistaken about the concept of an Array/ArrayList. The ArrayList only holds each Student object, not the variable in each object. You can go through each student and get their finalGrade and letterGrade with the get* functions. Before doing this, you should make a call to CalcGrade methods so the grades are calculated.

Categories