I am currently trying to search through a linked list and update the data in a certain node given a String name. I don understand where I am going wrong. I do not receive any error when I run the program but the data that I "update" never changes.
My updateGpa method in my linkedlist class
public void updateGpa(String name, double gpa){
Node<Student> temp = head;
double foundData;
boolean exists = false;
for(int i = 0; (i < size) && !exists; i++){
if(temp.data.getName().equals(name)){
foundData =gpa;
temp.data.setGpa(foundData);
exists = true;
}
temp = getNode(i);
}
}
My main method where I call the updateGpa method
System.out.println("Update a students GPA by entering their name: ");
student = in2.next();
System.out.println("Enter " + student + "'s new GPA: ");
gpa = in1.nextDouble();
studentList.updateGpa(student, gpa);
break;
Student list is my linked list.
I have solved my own problem, unfortunately I have to chalk it up to user error in my main method I have student = in2.next where it should have been in2.nextLine It was only reading in the first name rather than the first and last name so when it was comparing the string in the updateGpa method it would never find a match because the string wasn't exactly equal. Sorry to waste your time but thank you for your input
Related
I created a simple console based student system where basically the program will ask if you want to input name of students or view the list of names you inputted. The flow of the output is as shown below:
*******CONSOLE BASED STUDENT SYSTEM************
1. Input Student Name
2. List of students
Enter the number of choice: 1
Enter number of students to input: 3
****************************************
Student No. 1
Enter full name: Alpha Jones
****************************************
Student No. 2
Enter full name: Beta Jones
****************************************
Student No. 3
Enter full name: Gamma Jones
Do you wish to proceed back to menu?(y/n): y
*******CONSOLE BASED STUDENT SYSTEM************
1. Input Student Name
2. List of students
Enter the number of choice: 2
******LIST OF STUDENTS******
NULL
NULL
NULL
Firstly, I input three new students names Alpha Jones, Beta Jones and Gamma Jones but when I chose to view all names, everything is null. The three names should appear.
Here is the code for Student Class:
public class Student {
private String[] names;
private int numInput;
public Student(){
}
public Student(String[] fullName, int nI){
numInput = nI;
names = new String[nI];
for(int index = 0; index < nI; index++){
names[index] = fullName[index];
}
}
public String[] getList(){
return names;
}
public int getNumStudents(){
return numInput;
}
}
This is where I setup the values that will be passed on from the PracticeOne class, and later on, I will return that value back for display in PracticeOne Class.
Here is the PracticeOne Class(This is where the main method is located):
import java.util.Scanner;
public class PracticeOne {
public static void main(String[]args){
Scanner hold = new Scanner(System.in);
int menuNumChoice;
String response;
do{
System.out.println("******CONSOLE BASED STUDENT SYSTEM******");
System.out.println("1. Input Student Name");
System.out.println("2. List of Students");
System.out.print("Enter the number of choice: ");
menuNumChoice = hold.nextInt();
switch(menuNumChoice){
case 1:
inputStudentName(hold);
break;
case 2:
listStudents();
break;
default:
System.out.println("ERROR 101");
break;
}
System.out.print("Do you wish to proceed?(y/n): ");
response = hold.nextLine();
}while(response.equalsIgnoreCase("y"));
}
public static void inputStudentName(Scanner hold){
int numInput;
System.out.print("Enter number of students to input: ");
numInput = hold.nextInt();
hold.nextLine();
String[] fullName = new String[numInput];
for(int x = 0; x < numInput; x++){
System.out.println("***************************");
System.out.println("Student No. " + (x + 1));
System.out.print("Enter full name: ");
fullName[x] = hold.nextLine();
System.out.println();
}
Student s = new Student(fullName,numInput);
}
public static void listStudents(){
Student s = new Student();
System.out.println("******LIST OF STUDENTS******");
for(int y = 0; y < s.getNumStudents();y++){
System.out.println(s.getList());
}
}
}
Firstly I called an instance of Student in inputStudentName() method, which passes an argument for the fullname and the number of arrays being used, and tries to transfer it to Student class constructor, to get the values from there later on.
In the listStudents method, I tried displaying it by calling the getList() method from Student class to supposedly get back the names that was inputted earlier but everything was NULL. I also tried getting back the number of arrays through the getNumStudents() method but it also failed.
Kindly share some advice on how to work around with this problem or if theres a better way, suggest new things to achieve my goal.
public static void listStudents(){
**Student s = new Student();**
System.out.println("******LIST OF STUDENTS******");
for(int y = 0; y < s.getNumStudents();y++){
System.out.println(s.getList());
}
}
This is your listStudents logic. Instead of using the data you already created, you just create a new instance of Student. It's quite normal that this doesn't contain any information.
In your input method, you also only save the data in a local variable. This means, that once the method is finished, the data is lost.
Add a static List<Student> students = new ArrayList<>(); to your class. At the end of each input method, add the Student object to this list.
In listStudents, don't create a local student, but print the ones you stored in this List.
Based on your current system,first you can create a global variable Student[] or List then at the end of ' input Student Name()' method to save your dat.
Another Way you can use database to save your data,But this is not necessary for your system.
I can't seem to figure out how to print an arrayList<String> to a JTextArea and have tried using both append() and setText(). I have also tried to create a method which prints out the ArrayList through a loop, but it can't be added to the JTextArea because it is not of type String.
An applicant is supposed to take a student profile (name, grade, university selections) and add it to the ArrayList<String> Applicants. This is done through a JButton if it holds true for the following if statement:
if (studentsAverage > 74 && validInput && studentsAverage < 100) {
studentChoices.addAll(uniOptions.getSelectedValuesList());
person = new Student (namePromptTF.getText(), averagePromptTF.getText(),Applicants, studentChoices);
arrayCount++;
numberOfApplicants.setText(arrayCount +"/" +100+"students");
person.printProfile(); //dont need
person.studentProfileSort(); // dont need
displayAllApplicants.append(person.returnProfile());
Applicants.add(person);
The array is passed to a Student object that holds:
private ArrayList<Student> ApplicantArray;
ApplicantArray is then sorted through this method:
void studentProfileSort() {
Student profileLine = null;
int numberOfStudents = ApplicantArray.size();
ArrayList<Student> displayAllSorted = new ArrayList<Student>();
for(int i = 1; i<numberOfStudents - 1; i++){
for(int j = 0; j<(numberOfStudents - i); j++) {
if(ApplicantArray.get(i).getFamilyName().compareTo(ApplicantArray.get(i).getFamilyName())>0){
ApplicantArray.set(j, ApplicantArray.get(i));
}
}
ApplicantArray.get(i).returnProfile();
}
}
Is there a way to have a return statement inside of a loop so that I can change my method to a String type?
At first your sorting algorithm does not seem to work
ApplicantArray.get(i).getFamilyName().compareTo(ApplicantArray.get(i).getFamilyName())
You compare the value with it self and this results always in 0. Even if this would work, in the next line you override the array by setting a value rather than swapping the two values or setting to a new ArrayList.
But if everything works, this is how you could print those students:
StringBuilder b = new StringBuilder();
for (Student student : applicantArray) {
b.append(student + "\n"); // this if you implemented toString() in Student
b.append(student.getFamilyName() + ' ' + student.getFirstName() + "\n"); // or something like this
}
textArea.setText(b.toString());
P.S.: you should never use UpperCamelCase for variables or parameters, use lowerCamelCase instead (e.g. ApplicantArray -> applicantArray)
this is my current code and I am having troubles removing the name and the net and gross information included with the name. Any help would be greatly appreciated
public static int removeName(String[] nameArray,
int[] grossArray, int[] netArray, int counter) {
Scanner keyboard = new Scanner(System.in);
String name;
int nameSearch;
System.out.println("Please enter the name you would like to remove.");
name = keyboard.nextLine();
nameSearch = searchArray(nameArray, name);
if (nameSearch != -1) {
nameArray[nameSearch] = name;
counter--;
} else {
System.out.println("That name is not on the list");
}
return counter;
}
Code runs and gives no errors. When the code runs it just edits the name I type in depending on the case format I use (uppercase/lowercase). I need this code to remove the name and the information associated with it. When removing I also need the list to move up so if I delete Bob for example and Jen is below Bob Jen takes Bob's place since he is deleted. I am not allowed to use array lists.
if (nameSearch != -1) {
nameArray[nameSearch] = name;
counter--;
} else {
System.out.println("That name is not on the list");
}
return counter;
Why are you setting nameArray[nameSearch] to name? Don't you want to remove what's in nameArray[nameSearch]?
If that's what you want to do you could temporarily convert nameArray into an ArrayList and remove what's at the index of nameSearch. Something like this:
List<String> nameArrayList = new ArrayList<String>(Arrays.asList(nameArray));
nameArrayList.remove(nameSearch);
nameArray = nameArrayList.toArray();
If you do this you might as well consider keeping nameArray as an arrayList throughout your function.
I cannot seem to get my saved accounts stored inside my ArrayList. I think the latest one overwrites the oldest one, but I need them all to stack up in the ArrayList.
When I run the program, I create (add to ArrayList) a new Account, say Greg. Then I go on using that account and later on, add another account, say Bob. Then I click on "search for account" and type in Greg, it doesn't find it, but it finds Bob. HOWEVER, if I search for Greg BEFORE I create Bob, it FINDS IT!
Here are the relevant parts of my code:
////////// DECLARATIONS /////////
public static ArrayList dataStore;
public static int index;
dataStore = new ArrayList(10);
index = 0;
/////////////////////////////// ADD NEW ACCOUNT ////////////////////////////////
else if(source.equals("Add new account")) {
//************* Output
accountName = JOptionPane.showInputDialog("Enter the account name: ");
account.setName(accountName);
String strInitialBalance = JOptionPane.showInputDialog("Enter your initial
balance: ");
initialBalance = Double.parseDouble(strInitialBalance);
account.setBalance(initialBalance);
account = new CheckingAccount(initialBalance, accountName);
dataStore.add(index++, account);
}
//////////////////////////////// FIND ACCOUNT /////////////////////////////////
else if(source.equals("Find an account")) {
String str, name;
str = JOptionPane.showInputDialog("Enter the Account name: ");
for (int index = 0; index < dataStore.size(); index++) {
Account datum = (Account)dataStore.get(index);
if (str.equals(datum.getName())) {
name = datum.getName();
textArea.setText("Found Account for " + name);
}
else
textArea.setText("No Accounts found!");
} // for
}
This "account" object they are referring to is a class I have where all the data gets stored. Here is its header:
public class CheckingAccount extends Account implements Serializable {
// ...
// Methods
// ...
}
Here is your original chunk of code.
for (int index = 0; index < dataStore.size(); index++) {
Account datum = (Account)dataStore.get(index);
if (str.equals(datum.getName())) {
name = datum.getName();
textArea.setText("Found Account for " + name);
}
else
textArea.setText("No Accounts found!");
}
I dont think it makes sense to have the else statement inside your for loop, try the code below instead...
boolean found = false;
for (int index = 0; index < dataStore.size(); index++) {
Account datum = (Account)dataStore.get(index);
if (str.equals(datum.getName())) {
name = datum.getName();
textArea.setText("Found Account for " + name);
found = true;
}
}
if(!found){
textArea.setText("No Accounts found!");
}
I think that you don't want the else{} inside the for(...) loop because as you navigate through your data structure, many times, your initial if (str.equals(datum.getName())) statement will fail as you have not found the account yet. However, if you eventually find it, you will meet the if(...) condition and tell the user via textArea that you found the account. Then you set a boolean to true that you found it. If you go through the ENTIRE data structure and have not found it, the boolean will still equal false, and you will meet the condition for the second if which is if(!found) after the for loop, and will tell the user that you have searched the entire data structure and have not found the account.
Also, I think your first else if should look more like the code below (I don't know what the method signatures look like for CheckingAccount so some of this is a guess on actual syntax)
else if(source.equals("Add new account")) {
//************* Output
//use constructor below if you have a default constructor aka no paramaters
CheckingAccount account = new CheckingAccount();
//now that you have object linked to account, you can use setters
accountName = JOptionPane.showInputDialog("Enter the account name: ");
//set the name
account.setName(accountName);
String strInitialBalance = JOptionPane.showInputDialog("Enter your initial
balance: ");
initialBalance = Double.parseDouble(strInitialBalance);
//set the balance
account.setBalance(initialBalance);
//dont make a new object now as you did before..just add the object to your arraylist
dataStore.add(index++, account);
}
I'm making a program that gives you a menu:
1. Show all records.
2. Delete the current record
3. Change the first name in the current record
4. Change the last name in the current record
5. Add a new record
6. Change the phone number in the current record
7. Add a deposit to the current balance in the current record
8. Make a withdrawal from the current record if sufficient funds are available.
9. Select a record from the record list to become the current record.
10. Quit
and a command promt:
Enter a command from the list above (q to quit):
I have 4 Linked Lists:
firstName
lastName
teleNumber
accountBalance
I'm sure you can assume what they contain...
Assume I have already added a new record.
I'm trying to figure out how to make a method that would keep a node selected as I make changes or remove it.
public void numberNine()
{
System.out.println("Enter first name: ");
String fName = keyboard.next();
System.out.println("Enter last name: ");
String lName = keyboard.next();
if(firstName.contains(fName))
{
if(lastName.contains(lName))
{
/*I need to set the current record here.
I also need to print out the current record.
That means I need to find the corresponding
information from the linked lists by checking
the index of the first or last name because
both share the same index position for the
correhlating information of the selected person
for the current record.*/
}
else
{
System.out.println("No matching record found.");
}
}
else
{
System.out.println("No matching record found.");
}
}
The only thing is that I'm not completely familiar with the syntax to perform to get the job done, but from what I've come understand after looking around, I might need a method that looks somewhat like this:
public void currentRecord(String fName, String lName)
{
/*check for index of both fName and lName between the two strings containing
this information until they match up, then select the telenumber and
balance that match the index of the fName and lName and print*/
}
I've understood the explanations I have found, but there hasn't been any syntax with these explanations to assist me in actually achieving this. Could someone please show me how it's done?
private static void searchRecord(String firstName, String lastName) {
boolean recordFound = false;
if(fName.contains(firstName) && lName.contains(lastName)){
int index = -1;
for (String fn : fName) {
index++;
if(fn.equals(firstName)){
String ln = lName.get(index);
if(ln.equals(lastName)){
recordFound = true;
System.out.println("Record Found");
System.out.println("First Name="+ fName.get(index));
System.out.println("Last Name="+ lName.get(index));
System.out.println("Phone="+ phone.get(index));
System.out.println("Balance="+ balance.get(index));
}
}
}
}
if(!recordFound) {
System.out.println("No Record found for first name="+ firstName + " and last name="+lastName);
}
}