Cannot find items from ArrayList? - java

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);
}

Related

How to pass a string array or integer value from a class to another using java?

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.

Updating A node in LinkedList by passing a String

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

Java code that removes items from a text list

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.

To know a class by entering an array value

I have got one string array each in 2 different classes in java.
When I enter a value from any of the arrays, I want to get the class to which that array value belongs.
So how do I get to know the class just by entering an array value?
eg:
import java.io.*;
class Car {
public static void main(String args[]) throws Exception {
System.out.println("The parts of a car are as follows");
for (int i = 1; i <= 5; i++) {
System.out.println(i + str[i]);
}
for (int j = 1; j <= 5; j++) {
System.out.println(j + ch[j]);
}
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Choose and enter any part name to group it under following categories:" + "\n" + "Engine" + "\t" + "\t" + "Bonet");
String part = dis.readLine();
if (part == ch[]) {
System.out.println("Your choosen part is " + part + " and it comes under Engine category");
} else {
System.out.println("Your choosen part is " + part + " and it comes under Bonet category");
}
}
}
class Engine {
String ch[] = {"asd", "fgh"};
}
class Bonet {
String str[] = {"qwe", "rty"};
}
now when a user enters asd i want to display to which class it belongs
I wont give you full code because I believe that creating it yourself will be better for you. Instead here are few facts that you need to take into consideration:
To have access to array stored in other class you would aether have to create instance of that class
Engine engine = new Engine();
engine.ch[0];
or in your case you should probably make your array static
class Engine {
static String ch[] = { "asd", "fgh" };
}
and access it via class name Engine.ch[0]
Arrays are indexed from 0 to arraySize-1
To get size of array you can use its filed length and later use it like
for(int i=0; i<Bonet.str.length; i++){
System.out.println(i+Bonet.str[i]);
}
readLine() from DataInputStream is depracated. Instead you can use nextLine from java.util.Scanner
Scanner scanner = new Scanner(System.in);
//...
String part = scanner.nextLine();
To check if some object is stored in array you will have to iterate over all elements of that array and compare them with your object. Also remember that to compare String objects you should use equals method like part.equals(otherString).
But to make it with less code you can wrap your array into List and use its contains(Object o) method. To wrap array into list you can use asList method from java.util.Arrays class.
if(Arrays.asList(Engine.ch).contains(part)){...
Bare minimum changes to get this to work are as below. Key points:
the contents of Engine and bonet belong to instances of those classes not to car
arrays of size 5 have indicies 0,1,2,3,4, not 1,2,3,4,5
Where going through an array in a loop do not hard code the array size, use .length instead
import java.io.*;
public class Car {
public static void main(String args[]) throws Exception {
System.out.println("The parts of a car are as follows");
Engine engine=new Engine(); //we must create any components we have
Bonet bonet=new Bonet(); //we must create any components we have
for (int i = 0; i <bonet.str.length; i++) {
System.out.println(i +":"+ bonet.str[i]);
}
for (int j = 0; j < engine.ch.length; j++) {
System.out.println(j +":"+ engine.ch[j]);
}
DataInputStream dis = new DataInputStream(System.in);
System.out.println("Choose and enter any part name to group it under following categories:" + "\n" + "Engine" + "\t" + "\t" + "Bonet");
String part = dis.readLine();
boolean isInEngine=false; //assume isn't in engine, try to prove otherwise
for(int i=0;i<engine.ch.length;i++){
if (engine.ch[i].equals(part)){
isInEngine=true;
}
}
if (isInEngine==true) {
System.out.println("Your choosen part is " + part + " and it comes under Engine category");
} else {
System.out.println("Your choosen part is " + part + " and it comes under Bonet category");
}
}
}
class Engine {
String ch[] = {"asd", "fgh"};
}
class Bonet {
String str[] = {"qwe", "rty"};
}
Note; this is far from an optimal solution, ideas to consider:
It is bad practice to refer to the insides of annother class like this, it would be better for each class (engine and bonnet) to include a method .testPart(String string) that would return a boolean as to if it contains the part
The code assumes that if its not in engine it must be in bonet, what if the user enters something crazy
An array list (rather than an array) would allow us to use .contains(String string) rather than using a loop to look though the array
The DataInputStream is no longer supported (note that it appears with a strike through in most IDEs), consider using Scanner scanner = new Scanner(System.in); and then use scanner.nextLine(); to get the line
What if you add a third type of component, better to hold all your parts in an array, then you can easily add annother. An interface (or abstract base class) would promise that all the array contents held the .testPart(String string) and a getName() method; the array/arraylist would be declared as containing the interface/abstract-base-class
You never actually create an instance of Car, which you would do by Car car=new Car();, the Car class could then have methods like car.printOptions(); and car.testComponent(String testString);. The way you're doing it (one long main function) will work fine for small programs, but the bigger your program becomes the harder it will be to work like this. In this case the engine and bonet would be fields of the car class (which logically makes a lot more sense than them just 'hanging around')

How do you keep a node in a linked list selected for editing and/or removal?

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);
}
}

Categories

Resources