AddressBook in Java - 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];

Related

how to use a do-while loop in a class?

how would I create a do-while loop to verify that the user input contains no special characters. If it does contain special characters, how would I make it restart the loop? In my loop, it still returns the name if it has special characters.
Here is my main:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
UserInterface user = new UserInterface();
System.out.print("Enter first and last name: ");
String userName = input.nextLine();
user.setName(userName);
user.getName();
}
}
Here is my User class:
import java.util.Random;
public class UserInterface {
Random random = new Random();
private String name;
public String getName() {
String specialCharacters = "!#$%&'()*+,-./:;<=>?#[]^_`{|}123456789";
boolean invalidInput = false;
do {
invalidInput = false;
System.out.print("User: " + name + " ID #" + getUserID());
} while(name.contains(specialCharacters));
invalidInput = false;
return name;
}
public void setName(String userName) {
this.name = userName;
}
public int getUserID() {
return random.nextInt(1000);
}
}
use do while loop to verify weather the user name is valid or not.
For validating use:
public static boolean isValidName(String name){
for(char ch : name.toCharArray())
if(!Character.isLetterOrDigit(ch))
return false;
return name.length() != 0;
}
For getting name:
public static String inputName() {
boolean invalidInput = false;
Scanner scan = new Scanner(System.in);
String name = null;
do {
System.out.print("Enter Name : ");
name = scan.nextLine();
//System.out.println("name " +name);
//System.out.print("User: " + name + " ID #" + getUserID());
} while(!isValidName(name));
return name;
}
Main.java
import java.util.Random;
import java.util.Scanner;
class UserInterface {
Random random = new Random();
private String name;
public void setName(String userName) {
this.name = userName;
}
public String getName(){
return name;
}
public int getUserID() {
return random.nextInt(1000);
}
}
public class Main {
public static String inputName() {
boolean invalidInput = false;
Scanner scan = new Scanner(System.in);
String name = null;
do {
System.out.print("Enter Name : ");
name = scan.nextLine();
//System.out.println("name " +name);
//System.out.print("User: " + name + " ID #" + getUserID());
} while(!isValidName(name));
return name;
}
public static boolean isValidName(String name){
for(char ch : name.toCharArray())
if(!Character.isLetterOrDigit(ch))
return false;
return name.length() != 0;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
UserInterface user = new UserInterface();
user.setName(inputName());
System.out.println(user.getName());
}
}
Output:
$ javac Main.java && java Main
Enter Name : Dev Par
Enter Name : DevPar
DevPar

Using an arrayList to create a menu and using a text file as input(bufferedReader)

As you can see below I tried creating a switch case for choices
1. Name
2. Course then Name
3. Year Level then Name
4. Course then Year Level and the Name
5. Exit
I don't know how to use switch case so that I could sort everything according to the menu. I will be using comparable and I am only allowed to edit the method called compareTo. My mind is blank and I got no idea where to start.
20192215
Ang
Bryan
m
BSCS
4
20192200
Santos
Charlie
m
BSIT
2
20192452
Chua
Leah
f
BSIS
4
20190012
Yee
John
m
BSCS
2
These are the inputs from text file
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Vector;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
try {
BufferedReader br = new BufferedReader(new FileReader("c://student.txt"));
char g;
int yl, I;
String ln, fn, id, cors, con;
Student v[] = new Student[4];
Scanner sc= new Scanner(System.in);
boolean en = true;
boolean ent = true;
for(i = 0; i < 4; i++){
id = br.readLine();
ln = br.readLine();
fn = br.readLine();
g = br.readLine().charAt(0);
cors = br.readLine();
yl = Integer.parseInt(br.readLine());
v[i] = new Student(ln, fn, id, cors, g, yl);
}
while(en == true){
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
System.out.println("1. Name");
System.out.println("2. Course then Name");
System.out.println("3. Year Level then Name");
System.out.println("4. Course then Year Level and the Name");
System.out.println("5. Exit");
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
System.out.println("Choose Menu: ");
int choice = sc.nextInt();
switch(choice){
case 1 :
Arrays.sort(v);
display_array(v);
break;
case 2 :
Arrays.sort(v);
display_array(v);
break;
case 3 :
Arrays.sort(v);
display_array(v);
break;
case 4 :
Arrays.sort(v);
display_array(v);
break;
case 5 :
en = false;
System.out.println("\n\n \nTHANK YOU FOR USING THE PROGRAM!!");
break;
}
if(en != false){
System.out.println("Press [Enter key] to continue");
try{
System.in.read();
}catch(Exception e){
e.printStackTrace();
}
}
}
} catch (FileNotFoundException e) {
System.err.println("File not found");
} catch (IOException e) {
System.err.println("Unable to read the file.");
}
}
public static void display_array(Student arr_v[]) throws IOException{
System.out.println("--------------------------------------");
for(int i = 0; i < arr_v.length; i++){
arr_v[i].display();
}
System.out.println("--------------------------------------");
}
}```
```
public class Student implements Comparable {
private String lastname, firstname, studentid, course;
private char gender;
private int yearlevel;
public Student(String ln, String fn, String id, String cors, char g, int yl) {
lastname = ln;
firstname = fn;
studentid = id;
course = cors;
gender = g;
yearlevel = yl;
}
public int compareTo(Object anotherObject) {
Student anotherStudent = (Student) anotherObject;
int compareResult =
this.course.compareTo(anotherStudent.lastname);
if(compare )
return 0;
}
public void display() {
System.out.printf("ID: %-8s Name: %-20s Sex: %c Course: %-8s Year: %d\n", studentid, (lastname + ", " + firstname), gender, course, yearlevel );
}
public void setGender(char gender){
this.gender = gender;
}
public char getGender(){
return gender;
}
public void setLastname(String lastname){
this.lastname = lastname;
}
public String getLastname(){
return lastname;
}
public void setFirstname(String firstname){
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
public void setStudentId(String studentid){
this.studentid = studentid;
}
public String getStudentId(){
return studentid;
}
public void setCourse(String course){
this.course = course;
}
public String getCourse(){
return course;
}
public void setYearLevel(int yearlevel){
this.yearlevel = yearlevel;
}
public int getYearLevel(){
return yearlevel;
}
}```
public final class Student {
private final String id;
private final String firstName;
private final String lastName;
private final char gender;
private final String course;
private final int yearLevel;
public Student(String id, String firstName, String lastName, char gender, String course, int yearLevel) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.gender = Character.toUpperCase(gender);
this.course = course;
this.yearLevel = yearLevel;
}
public void display(PrintStream out) {
out.format("Name : %s, %s\n", lastName, firstName);
out.format("Student ID : %s\n", id);
out.format("Course : %s\n", course);
out.format("Gender : %s\n", gender);
out.format("Year Level : %d\n", yearLevel);
}
}
public static void main(String... args) throws FileNotFoundException {
File file = new File("c://student.txt");
List<Student> students = readStudents(file);
display(students);
}
private static List<Student> readStudents(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
List<Student> students = new ArrayList<>();
while (scan.hasNext()) {
String id = scan.next();
String lastName = scan.next();
String firstName = scan.next();
char gender = scan.next().charAt(0);
String course = scan.next();
int yearLevel = scan.nextInt();
students.add(new Student(id, firstName, lastName, gender, course, yearLevel));
}
return students;
}
}
private static void display(List<Student> students) {
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
System.out.println("1. Name");
System.out.println("2. Course then Name");
System.out.println("3. Year Level then Name");
System.out.println("4. Course then Year Level and the Name");
System.out.println("5. Exit");
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
students.forEach(student -> {
student.display(System.out);
System.out.println();
});
}
All programmers need to learn how to debug their code. If you are using an IDE then I recommend that you learn how to use its debugger.
You have some calls to method readLine() that you do not need. In the below code, I have marked these lines as comments. I also incorporated the methods display_array() and main() into class Student just so everything would be in the one class, but you don't have to do that.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Student {
private String lastname, firstname, studentid, course;
private char gender;
private int yearlevel;
public Student(String id, String ln, String fn, char g, String cors, int yl) {
studentid = id;
lastname = ln;
firstname = fn;
gender = g;
course = cors;
yearlevel = yl;
}
private static void display_array(Student[] v) {
for (Student s : v) {
s.display();
}
}
public void display() {
System.out.println("Name : " + lastname + ", " + firstname);
System.out.println("Student ID: " + studentid);
System.out.println("Course : " + course);
System.out.println("Gender : " + gender);
System.out.println("Year Level: " + yearlevel);
}
public void setGender(char gender){
this.gender = gender;
}
public char getGender(){
return gender;
}
public void setLastname(String lastname){
this.lastname = lastname;
}
public String getLastname(){
return lastname;
}
public void setFirstname(String firstname){
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
public void setStudentId(String studentid){
this.studentid = studentid;
}
public String getStudentId(){
return studentid;
}
public void setCourse(String course){
this.course = course;
}
public String getCourse(){
return course;
}
public void setYearLevel(int yearlevel){
this.yearlevel = yearlevel;
}
public int getYearLevel(){
return yearlevel;
}
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("c:\\student.txt"));) {
char g;
int yl;
int i;
String ln;
String fn;
String id;
String cors;
Student v[] = new Student[Integer.parseInt(br.readLine())];
// br.readLine();
for (i = 0; i < v.length; i++) {
id = br.readLine();
ln = br.readLine();
fn = br.readLine();
// g = (char) br.read();
g = br.readLine().charAt(0);
cors = br.readLine();
yl = Integer.parseInt(br.readLine());
// if ((br.readLine()) != null)
// br.readLine();
v[i] = new Student(id, ln, fn, g, cors, yl);
}
display_array(v);
}
catch (FileNotFoundException e) {
System.err.println("File not found");
}
catch (IOException e) {
System.err.println("Unable to read the file.");
}
}
}
I also changed file student.txt. According to your code, the first line of the file needs to be the number of students in the file. In the sample file in your question, there are four students.
4
20192215
Ang
Bryan
m
BSCS
4
20192200
Santos
Charlie
m
BSIT
2
20192452
Chua
Leah
f
BSIS
4
20190012
Yee
John
m
BSCS
2

How to overwrite a CSV file with new values in Java

I'm trying to edit a player in my code and then update the values in my CSV file that I created but I am not sure about how to write the new values to the file itself. I know what I want to do but just not sure how about to do it. I am editing the amount paid and trying to update it in the file for the player.
Here are my classes:
Main class here
package squashapplication;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
public class SquashMain {
public static String MENU = "Options:\nA) Add player\nS) Show players\n G) Update Amount Paid\nX) Exit";
public static String FILE_NAME = "c:\\cis2232\\players.csv";
public static void main(String[] args) throws IOException {
Files.createDirectories(Paths.get("/cis2232"));
ArrayList<SquashPlayer> theList = new ArrayList();
loadPlayers(theList);
String choice = "";
do{
System.out.println(MENU);
choice = FileUtility.getInput().nextLine().toUpperCase();
switch(choice){
case "A":
SquashPlayer player = new SquashPlayer(true);
theList.add(player);
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(FILE_NAME, true);
bw = new BufferedWriter(fw);
bw.write(player.getCSV(true));
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
if (fw != null) {
fw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
break;
case "S":
System.out.println("Here are the players");
for (SquashPlayer SquashPlayer : theList) {
System.out.println(SquashPlayer);
}
break;
case "G":
System.out.println("Enter ID:");
int input = FileUtility.getInput().nextInt();
FileUtility.getInput().nextLine();
for(SquashPlayer id:theList){
if(id.getId() == input){
System.out.println("Enter in new amount paid:");
int newAmount = FileUtility.getInput().nextInt();
FileUtility.getInput().nextLine();
id.setAmountPaid(newAmount);
}
}
case "X":
System.out.println("Goodbye");
break;
default:
System.out.println("Invalid option");
break;
}
}while (!choice.equalsIgnoreCase("x"));
}
public static void loadPlayers(ArrayList squash){
System.out.println("Loading players from the list!");
int counter = 0;
try{
ArrayList<String> tester = (ArrayList<String>) Files.readAllLines(Paths.get(FILE_NAME));
for(String current:tester){
System.out.println("Loading: "+current);
SquashPlayer temp = new SquashPlayer(current);
squash.add(temp);
counter++;
}
}catch(IOException ex){
System.out.println("Error loading players from file.");
System.out.println(ex.getMessage());
}
System.out.println("Loaded players from file: "+ counter + " players");
}
}
SquashPlayer class here
package squashapplication;
import java.util.Scanner;
/**
*
*/
public class SquashPlayer {
private static int maxRegistrationId;
private int id;
private String name;
private String parentName;
private String phoneNumber;
private String email;
private int amountPaid;
public SquashPlayer() {
}
public SquashPlayer(boolean getFromUser){
System.out.println("Enter Full Name:");
this.name = FileUtility.getInput().nextLine();
System.out.println("Enter Parents name:");
this.parentName = FileUtility.getInput().nextLine();
System.out.println("Enter phone number:");
this.phoneNumber = FileUtility.getInput().nextLine();
System.out.println("Enter e-mail:");
this.email = FileUtility.getInput().nextLine();
System.out.println("Enter amount paid:");
this.amountPaid = FileUtility.getInput().nextInt();
FileUtility.getInput().nextLine();
this.id = ++ maxRegistrationId;
}
public SquashPlayer(int id, String name, int amountPaid , String phoneNumber, String parentName , String email ) {
this.id = id;
this.amountPaid = amountPaid;
this.name = name;
this.parentName = parentName;
this.email = email;
this.phoneNumber = phoneNumber;
}
public SquashPlayer(String[] parts) {
this(Integer.parseInt(parts[0]), parts[1], Integer.parseInt(parts[2]), parts[3],parts[4], parts[5]);
if (Integer.parseInt(parts[0]) > maxRegistrationId) {
maxRegistrationId = Integer.parseInt(parts[0]);
}
}
public SquashPlayer(String csvValues) {
this(csvValues.split(","));
}
public String getCSV() {
return id + "," + name + "," + amountPaid + "," + phoneNumber + "," + email + "," + parentName;
}
public String getCSV(boolean withLineFeed){
if(withLineFeed){
return getCSV()+System.lineSeparator();
}else{
return getCSV();
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAmountPaid() {
return amountPaid;
}
public void setAmountPaid(int amountPaid) {
this.amountPaid = amountPaid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "ID=" +id+ ", Name=" + name + ", email=" + email + ", Phone Number=" + phoneNumber + ", Amount Paid=" + amountPaid + ", Parent's Name: "+parentName;
}
}
This might help,
Instead of fw.write, which I believe that's what you use, use fw.append adding a new line character "\n" at the end.

Searching an ArrayList to change object's value

I've made an ArrayList of players that I want to search through to change the amount they have paid. I want to be able to enter in their ID, then be able to change their amount paid just for that player. I am also writing it to a CSV file but I am not sure how to update that file with the new value. I'm not sure about how to go about doing this.
What I want to do is just update a value in the ArrayList for a specific player based on player input on the registration ID, then I want to update that value in the file.
Here are my 3 classes that I have made: SquashPlayer
package squashapplication;
import java.util.Scanner;
/**
*
* #author Evan
*/
public class SquashPlayer {
private static int maxRegistrationId;
private int id;
private String name;
private String parentName;
private String phoneNumber;
private String email;
private int amountPaid;
public SquashPlayer() {
}
public SquashPlayer(boolean getFromUser){
System.out.println("Enter Full Name:");
this.name = FileUtility.getInput().nextLine();
System.out.println("Enter Parents name:");
this.parentName = FileUtility.getInput().nextLine();
System.out.println("Enter phone number:");
this.phoneNumber = FileUtility.getInput().nextLine();
System.out.println("Enter e-mail:");
this.email = FileUtility.getInput().nextLine();
System.out.println("Enter amount paid:");
this.amountPaid = FileUtility.getInput().nextInt();
FileUtility.getInput().nextLine();
this.id = ++ maxRegistrationId;
}
public SquashPlayer(int id, String name, int amountPaid , String phoneNumber, String parentName , String email ) {
this.id = id;
this.amountPaid = amountPaid;
this.name = name;
this.parentName = parentName;
this.email = email;
this.phoneNumber = phoneNumber;
}
public SquashPlayer(String[] parts) {
this(Integer.parseInt(parts[0]), parts[1], Integer.parseInt(parts[2]), parts[3],parts[4], parts[5]);
if (Integer.parseInt(parts[0]) > maxRegistrationId) {
maxRegistrationId = Integer.parseInt(parts[0]);
}
}
public SquashPlayer(String csvValues) {
this(csvValues.split(","));
}
public String getCSV() {
return id + "," + name + "," + amountPaid + "," + phoneNumber + "," + email + "," + parentName;
}
public String getCSV(boolean withLineFeed){
if(withLineFeed){
return getCSV()+System.lineSeparator();
}else{
return getCSV();
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAmountPaid() {
return amountPaid;
}
public void setAmountPaid(int amountPaid) {
this.amountPaid = amountPaid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "ID=" +id+ ", Name=" + name + ", email=" + email + ", Phone Number=" + phoneNumber + ", Amount Paid=" + amountPaid + ", Parent's Name: "+parentName;
}
}
Here is my main class:
package squashapplication;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
public class SquashMain {
public static String MENU = "Options:\nA) Add player\nS) Show players\n G) Update Amount Paid\nX) Exit";
public static String FILE_NAME = "c:\\cis2232\\players.csv";
public static void main(String[] args) throws IOException {
Files.createDirectories(Paths.get("/cis2232"));
ArrayList<SquashPlayer> theList = new ArrayList();
loadPlayers(theList);
String choice = "";
do{
System.out.println(MENU);
choice = FileUtility.getInput().nextLine().toUpperCase();
switch(choice){
case "A":
SquashPlayer player = new SquashPlayer(true);
theList.add(player);
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(FILE_NAME, true);
bw = new BufferedWriter(fw);
bw.write(player.getCSV(true));
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
if (fw != null) {
fw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
break;
case "S":
System.out.println("Here are the players");
for (SquashPlayer SquashPlayer : theList) {
System.out.println(SquashPlayer);
}
break;
case "G":
case "X":
System.out.println("Goodbye");
break;
default:
System.out.println("Invalid option");
break;
}
}while (!choice.equalsIgnoreCase("x"));
}
public static void loadPlayers(ArrayList squash){
System.out.println("Loading players from the list!");
int counter = 0;
try{
ArrayList<String> tester = (ArrayList<String>) Files.readAllLines(Paths.get(FILE_NAME));
for(String current:tester){
System.out.println("Loading: "+current);
SquashPlayer temp = new SquashPlayer(current);
squash.add(temp);
counter++;
}
}catch(IOException ex){
System.out.println("Error loading players from file.");
System.out.println(ex.getMessage());
}
System.out.println("Loaded players from file: "+ counter + " players");
}
}
And here is where I store my scanner in FileUtility:
package squashapplication;
import java.util.Scanner;
public class FileUtility {
private static Scanner input = new Scanner(System.in);
public static Scanner getInput() {
return input;
}
}

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