Using methods in array list from TUI class - java

I'm trying to access an (add) method in my arrayList class from a TUI class, which will add a user to my arrayList.
This is my TUI class.
import java.util.ArrayList;
import java.util.Scanner;
public class BorrowerTUI
{
private BorrowerList borrowerList;
private Scanner myScanner;
public BorrowerTUI()
{
myScanner = new Scanner(System.in);
BorrowerList borrowerList = new BorrowerList();
}
public void menu()
{
int command = -1;
while (command != 0)
{
displayMenu();
command = getCommand();
execute (command);
}
}
private void displayMenu()
{
System.out.println( "Options are" );
System.out.println( "Enter 1" );
System.out.println( "Enter 2" );
System.out.println( "Enter 3" );
System.out.println( "Enter 4" );
}
private void execute( int command)
{
if ( command == 1)
addBorrower();
else
if ( command == 2 )
getNumberOfBorrowers();
else
if ( command == 3)
quitCommand();
else
if ( command == 4)
quitCommand();
else
if ( command == 5)
quitCommand();
else
System.out.println("Unknown Command");
}
private int getCommand()
{
System.out.print ("Enter command: ");
int command = myScanner.nextInt();
myScanner.nextLine();
return command;
}
public void getNumberOfBorrowers()
{
int command = myScanner.nextInt();
System.out.println("We have" + borrowerList.getNumberOfBorrowers() + "borrowers");
}
public void quitCommand()
{
int command = myScanner.nextInt();
System.out.println("Application Closing");
System.exit(0);
}
public void addBorrower()
{
Borrower borrower = new Borrower();
borrowerList.addBorrower(borrower);
}
}
This is my array list class.
import java.util.ArrayList;
public class BorrowerList
{
private ArrayList<Borrower> borrowers;
public BorrowerList()
{
borrowers = new ArrayList<Borrower>();
}
public void addBorrower(Borrower borrower)
{
borrowers.add(borrower);
}
public int getNumberOfBorrowers()
{
return borrowers.size();
}
public boolean getBorrower(String libraryNumber)
{
for(Borrower borrower : borrowers)
borrower.getLibraryNumber();
return true;
}
public void getBorrower(int borrowerEntry)
{
if (borrowerEntry < 0)
{
System.out.println("Negative entry: " + borrowerEntry);
}
else if (borrowerEntry < getNumberOfBorrowers())
{
Borrower borrower = borrowers.get(borrowerEntry);
borrower.printBorrowerDetails();
}
else
{
System.out.println("No such entry: " + borrowerEntry);
}
}
public void getAllBorrowers()
{
for(Borrower borrower : borrowers)
{
borrower.printBorrowerDetails();
System.out.println();
}
}
public void removeBorrower(int borrowerEntry)
{
if(borrowerEntry < 0)
{
System.out.println("Negative entry :" + borrowerEntry);
}
else if(borrowerEntry < getNumberOfBorrowers())
{
borrowers.remove(borrowerEntry);
}
else
{
System.out.println("No such entry :" + borrowerEntry);
}
}
public boolean removeBorrower(String libraryNumber)
{
int index = 0;
for (Borrower borrower: borrowers)
{
if (libraryNumber.equals(borrower.getLibraryNumber()))
{
borrowers.remove(index);
return true;
}
index++;
}
return false;
}
public int search(String libraryNumber)
{
int index = 0;
for (Borrower borrower : borrowers)
{
if (libraryNumber.equals(borrower.getLibraryNumber()))
{
return index;
}
else
{
index++;
}
}
return -1;
}
}
But for some reason when I try to link this method in my TUI class using the code at the top, it is returning the error: ") expected after 'User'"
Can somebody help, thanks.

It is returning an error because the method addUser is expecting a User object as input. In your call of the function, you gave it the User type as if you were declaring a method. Try passing in just a user object like so:
public void addUser()
{
User user = new User();
userList.addUser(user);
}

Related

How can I delete/not display the nulls?

So my question is how can i Delete/not display the nulls,the excess not founds,and 0's when I run the program, also the last two attributes of the Student201 when 'runned', it displays in reverse order meaning the the nulls or the excess not founds or zeroes are displayed first.
also how can I add students 'predefined'
This is my preferred output or display as much as possible w/o the not found
This is not what I want, the not founds are printed first before the desired output
Main.java
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Student a1=new Student();
//a1.choosy();
Student201 a2 =new Student201();
a2.studinfo();
a2.findstud("2000000001);
}
}
Student201.java
public class Student201 {
Student [] studarray = new Student[13];
int x;
public void studinfo()
{
for (x=0;x<studarray.length;x++) {
studarray[x]= new Student();
}
Student estudyante1 = new Student();
Student estudyante2 = new Student ();
Student estudyante3 = new Student ();
Student estudyante4 = new Student ();
Student estudyante5 = new Student ();
estudyante1.getStudName("Yves Francisco");
estudyante1.getStudNum(2000000001);
estudyante1.getYrLvl(5);
estudyante1.getKors("CpE");
estudyante1.getGender("Male");
estudyante2.getStudName("Lance Eco");
estudyante2.getStudNum(2000000002);
estudyante2.getYrLvl(5);
estudyante2.getKors("CpE");
estudyante2.getGender("Male");
estudyante3.getStudName("Karlos Castillo");
estudyante3.getStudNum(2000000003);
estudyante3.getYrLvl(5);
estudyante3.getKors("CpE");
estudyante3.getGender("Male");
estudyante4.getStudName("Glenn Bordonada");
estudyante4.getStudNum(2000000004);
estudyante4.getYrLvl(4);
estudyante4.getKors("ECE");
estudyante4.getGender("Male");
estudyante5.getStudName("Tim Tolentino");
estudyante5.getStudNum(2000000005);
estudyante5.getYrLvl(4);
estudyante5.getKors("ECE");
estudyante5.getGender("Male");
studarray[0]=estudyante1;
studarray[1]=estudyante2;
studarray[2]=estudyante3;
studarray[3]=estudyante4;
studarray[4]=estudyante5;
}
public void findstud (String query) //String query for searching
{
int ercatch=0;
try{
ercatch=Integer.parseInt(query);
}
catch (NumberFormatException m)
{
}
for (x=0;x<studarray.length;x++)
{
if (query.equalsIgnoreCase(studarray[x].setStudName())) //query.equalsIgnorecase for case sensitive inputs
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender()+"\n");
System.out.println("\n");
}
}
for (x=0;x<studarray.length;x++)
{
if (ercatch == studarray[x].setStudNum()) //Integer.parseInt for int data types
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender());
System.out.println("\n");
}
else if (ercatch != studarray[x].setStudNum())
{
System.out.println("Not Found!");
}
}
for (x=0;x<studarray.length;x++)
{
if (ercatch == studarray[x].setYrLvl())
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender());
System.out.println("\n");
}
else if (ercatch != studarray[x].setYrLvl())
{
System.out.println("Not Found!");
}
}
for (x=0;x<studarray.length;x++)
{
if (query.equalsIgnoreCase(studarray[x].setKors()))
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender());
System.out.println("\n");
}
}
for (x=0;x<studarray.length;x++)
{
if (query.equalsIgnoreCase(studarray[x].setGender()))
{
System.out.println(studarray[x].setStudName()+"\n"+studarray[x].setStudNum()+"\n"+studarray[x].setYrLvl()+"\n"+studarray[x].setKors()+"\n"+studarray[x].setGender());
System.out.println("\n");
}
}
}
public void addstud (String query)
{
}
}
Student.Java
public class Student {
private String StudName;
private int StudNum;
private int YrLvl;
private String Kors;
private String Gender;
//this just for naming convention for the get and set
public void getStudName (String name) {
this.StudName=name;
}
public String setStudName() {
return StudName;
}
public void getStudNum (int numero) {
this.StudNum=numero;
}
public int setStudNum() {
return StudNum;
}
public void getYrLvl (int yrlvl) {
this.YrLvl=yrlvl;
}
public int setYrLvl()
{
return YrLvl;
}
public void getKors (String korse) {
this.Kors=korse;
}
public String setKors() {
return Kors;
}
public void getGender (String sex)
{
this.Gender=sex;
}
public String setGender() {
return Gender;
}
public void choosy() {
System.out.println("Here is the list and the information of the Students \n");
}
/*public static void main(String[] args) {
// TODO Auto-generated method stub
}*/
}
First things first, you have totally mixed up getters and setters, getters should return the value without any parameter, and setters set the field to a vala ue with parameter, like this
public void setStudName (String name) {
this.StudName=name;
}
public String getStudName() {
return StudName;
}
public void setStudNum (int numero) {
this.StudNum=numero;
}
public int getStudNum() {
return StudNum;
}
Since you don't want to display the Not found result, so I remove it and this is your Student201 class.
public class Student201 {
Student[] studarray = new Student[13];
int x;
public void studinfo() {
for (x = 0; x < studarray.length; x++) {
studarray[x] = new Student();
}
Student estudyante1 = new Student();
Student estudyante2 = new Student();
Student estudyante3 = new Student();
Student estudyante4 = new Student();
Student estudyante5 = new Student();
estudyante1.setStudName("Yves Francisco");
estudyante1.setStudNum(2000000001);
estudyante1.setYrLvl(5);
estudyante1.setKors("CpE");
estudyante1.setGender("Male");
estudyante2.setStudName("Lance Eco");
estudyante2.setStudNum(2000000002);
estudyante2.setYrLvl(5);
estudyante2.setKors("CpE");
estudyante2.setGender("Male");
estudyante3.setStudName("Karlos Castillo");
estudyante3.setStudNum(2000000003);
estudyante3.setYrLvl(5);
estudyante3.setKors("CpE");
estudyante3.setGender("Male");
estudyante4.setStudName("Glenn Bordonada");
estudyante4.setStudNum(2000000004);
estudyante4.setYrLvl(4);
estudyante4.setKors("ECE");
estudyante4.setGender("Male");
estudyante5.setStudName("Tim Tolentino");
estudyante5.setStudNum(2000000005);
estudyante5.setYrLvl(4);
estudyante5.setKors("ECE");
estudyante5.setGender("Male");
studarray[0] = estudyante1;
studarray[1] = estudyante2;
studarray[2] = estudyante3;
studarray[3] = estudyante4;
studarray[4] = estudyante5;
}
public void findstud(String query) //String query for searching
{
int ercatch = 0;
try {
ercatch = Integer.parseInt(query);
} catch (NumberFormatException m) {
}
for (x = 0; x < studarray.length; x++) {
if (query.equalsIgnoreCase(studarray[x].getStudName())) //query.equalsIgnorecase for case sensitive inputs
{
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender() + "\n");
System.out.println("\n");
}
}
for (x = 0; x < studarray.length; x++) {
if (ercatch == studarray[x].getStudNum()) //Integer.parseInt for int data types
{
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender());
System.out.println("\n");
}
}
for (x = 0; x < studarray.length; x++) {
if (ercatch == studarray[x].getYrLvl()) {
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender());
System.out.println("\n");
}
}
for (x = 0; x < studarray.length; x++) {
if (query.equalsIgnoreCase(studarray[x].getKors())) {
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender());
System.out.println("\n");
}
}
for (x = 0; x < studarray.length; x++) {
if (query.equalsIgnoreCase(studarray[x].getGender())) {
System.out.println(studarray[x].getStudName() + "\n" + studarray[x].getStudNum() + "\n" + studarray[x].getYrLvl() + "\n" + studarray[x].getKors() + "\n" + studarray[x].getGender());
System.out.println("\n");
}
}
}
public void addstud(String query) {
}
}
how can i Delete/not display the nulls,the excess not founds,and 0's
First, remove this
for (x=0;x<studarray.length;x++) {
studarray[x]= new Student();
}
Then, all the students are null except for those you defined, which you can explicitly ignore them.
for (int x = 0; x < studarray.length; x++) {
Student s = studarray[x];
if (s == null) {
continue; // here
}
// Check all your fields in a single loop
if (query.equalsIgnoreCase(s.getStudName())) {
} else if (Integer.parseInt(query) == s.getStudNum()) {
} else {
System.out.println("Student not found using query " + query);
}
}

Why does my recursive method make my program throw an InvalidClassException?

In my program, I have a FacebookUser class that has an ArrayList of all of that user's friends. All of those friends may also have friends. I am using recursion to get a new ArrayList that contains all of the user's friends and all of the user's friends' friends and so on. I also serialized the FacebookUser class so I can save the data. Without the new recursive method, I can serialize without error and the data persists over executions. With the recursive method, though, I get an InvalidClassException. It shows that the exception is at the line that uses the ObjectInputStream to get the FacebookUser from memory.
I'm not understanding why the new method is causing the exception to be thrown from another method. I believe the problem lies only in the FacebookUser.java class (since getRecommendations is recursive method) but I thought it'd be best to also show the UserAccount.java class since the former extends the latter. Any help will be appreciated. Thank you.
Execution:
Exception in thread "main" java.io.InvalidClassException: FacebookUser; local class incompatible: stream classdesc serialVersionUID = 4110981517967863740, local class serialVersionUID = 5032562666539812166
at java.base/java.io.ObjectStreamClass.initNonProxy(Unknown Source)
at java.base/java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.base/java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.base/java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.base/java.io.ObjectInputStream.readObject0(Unknown Source)
at java.base/java.io.ObjectInputStream.readObject(Unknown Source)
at FacebookUser.readFile(FacebookUser.java:157)
at DriverClass.main(DriverClass.java:12)
FacebookUser.Java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
public class FacebookUser extends UserAccount implements Serializable{
private String passwordHint;
private ArrayList<FacebookUser> friends;
public FacebookUser(String username, String password) {
super(username, password);
friends = new ArrayList<FacebookUser>();
}
#Override
public void getPasswordHelp() {
System.out.println("Password Hint: " + passwordHint);
}
public void getPasswordHelp(String username) {
if (friends.size() == 0) {
System.out.println("There is no user with that username.");
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
friends.get(i).getPasswordHelp();
break;
}
if (i == friends.size() - 1) {
System.out.println("There is no user with that username.");
break;
}
}
}
}
void setPasswordHint(String hint) {
passwordHint = hint;
}
void friend(FacebookUser newFriend) {
if (friends.contains(newFriend)) {
System.out.println("That person is already your friend.");
} else {
friends.add(newFriend);
}
}
void friend(String username) {
Scanner s = new Scanner(System.in);
if (friends.size() == 0) {
System.out.println("Please create a password: ");
String password = s.nextLine();
System.out.println("Please create a password hint: ");
String passHint = s.nextLine();
FacebookUser fbu = new FacebookUser(username, password);
fbu.setPasswordHint(passHint);
friends.add(fbu);
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
System.out.println("That person is already your friend.");
break;
}
if (i == friends.size() - 1) {
System.out.println("Please create a password: ");
String password = s.nextLine();
System.out.println("Please create a password hint: ");
String passHint = s.nextLine();
FacebookUser fbu = new FacebookUser(username, password);
fbu.setPasswordHint(passHint);
friends.add(fbu);
break;
}
}
}
}
void defriend(FacebookUser formerFriend) {
if (friends.contains(formerFriend)) {
friends.remove(formerFriend);
} else {
System.out.println("That person is not your friend.");
}
}
void defriend(String username) {
Scanner s = new Scanner(System.in);
if (friends.size() == 0) {
System.out.println("That person is not your friend.");
} else {
for (int i = 0; i < friends.size(); i++) {
if (friends.get(i).toString().equals(username)) {
System.out.println("Password for " + username + ": ");
String passw = s.nextLine();
if (friends.get(i).getPassword().equals(passw)) {
friends.remove(i);
break;
} else {
System.out.println("Incorrect Password");
break;
}
}
if (i == friends.size() - 1) {
System.out.println("That person is not your friend.");
break;
}
}
}
}
ArrayList<FacebookUser> getRecommendations(FacebookUser friend) {
ArrayList<FacebookUser> recFriends = new ArrayList<FacebookUser>();
for (int i = 0; i < friend.getFriends().size(); i++) {
for (int j = 0; j < recFriends.size(); j++) {
for (int k = 0; k < recFriends.size(); k++) {
if (recFriends.get(j).equals(recFriends.get(k))) {
recFriends.remove(j); // This removes any duplicate friends so there won't be an infinite loop.
break;
}
}
}
recFriends.addAll(friend.getFriends().get(i).getRecommendations(friend)); // This adds the friends' friends' friends and so on into the ArrayList.
}
return recFriends;
}
ArrayList<FacebookUser> getFriends() {
ArrayList<FacebookUser> friendsCopy = new ArrayList<FacebookUser>();
for (int i = 0; i < friends.size(); i++) {
friendsCopy.add(friends.get(i));
}
Collections.sort(friendsCopy, new Comparator<FacebookUser>() {
#Override
public int compare(FacebookUser fb1, FacebookUser fb2) {
return fb1.toString().compareToIgnoreCase(fb2.toString());
}
});
return friendsCopy;
}
public static void writeToFile(FacebookUser facebookUser) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("FacebookUser.bin"));
oos.writeObject(facebookUser); // This saves the data.
}
public static FacebookUser readFile() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("FacebookUser.bin"));
FacebookUser facebookUser = (FacebookUser) ois.readObject(); // This reads in the data which is called in the DriverClass class line 12.
return facebookUser;
}
}
UserAccount.java
import java.io.Serializable;
public abstract class UserAccount implements Serializable{
private String username;
private String password;
private boolean active;
public UserAccount(String username, String password) {
this.username = username;
this.password = password;
active = true;
}
public boolean checkPassword(String password) {
if (password.equals(this.password)) {
return true;
} else {
return false;
}
}
public void deactivateAccount() {
active = false;
}
public String getPassword() {
return password;
}
public String toString() {
return username;
}
public boolean checkActive() {
if (active == true) {
return true;
} else {
return false;
}
}
public abstract void getPasswordHelp();
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserAccount other = (UserAccount) obj;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
}
DriverClass.java
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class DriverClass {
public static void main(String[] args) throws IOException, ClassNotFoundException {
int choice = 0;
String username;
FacebookUser fu0;
try {
fu0 = FacebookUser.readFile();
} catch (FileNotFoundException e) {
fu0 = new FacebookUser("Robert", "password1");
}
while (choice != 5) {
System.out.println(
"1. List Users \n2. Add a User \n3. Delete a User \n4. Get Password Hint \n5. Get Recommendations \n6. Quit");
Scanner s = new Scanner(System.in);
choice = s.nextInt();
switch (choice) {
case 1:
System.out.println(fu0.getFriends());
break;
case 2:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.friend(username);
break;
case 3:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.defriend(username);
break;
case 4:
System.out.println("Username: ");
s.nextLine();
username = s.nextLine();
fu0.getPasswordHelp(username);
break;
case 5:
System.out.println(fu0.getRecommendations(fu0));
break;
case 6:
FacebookUser.writeToFile(fu0);
break;
}
}
}
}
The exception suggests that the SerialVersionUID the JVM generated differs for some instances of the FacebookUser object. If you make your class implement Serializable, it is highly recommended that you explicitly declare the SerialVersionUID variable to avoid exceptions like these.
So in the FacebookUser class you should declare a variable like this:
private static final long serialVersionUID = 42L;
See this answer for more details.

Possible logic issue adding an object to an arraylist

My program has 6 classes so I'm going to try and only post the methods involved with the issue I'm having. I'm trying to add donation objects that get their attributes from reading information from a file. My program wasn't printing out any of the donationList related information so I did a System.out.println(donationList.size()); and it's telling me that there are 0 objects in the list. I've been looking at this for a while and can't figure out where in the process the donation object is failing to be created correctly or added to the arraylist correctly.
This is where I call the method that starts the process.
public static void main(String[] args) {
readAndProcess();
This is the method that starts the process.
public static void readAndProcess() {
final String INPUT_FILENAME = "input/assn2input.txt";
File dataFile = new File(INPUT_FILENAME);
Scanner fileScanner = null;
try {
fileScanner = new Scanner(dataFile);
}catch (FileNotFoundException e) {
System.out.println("File not found exception for file " + e);
System.exit(0);
}
String oneLine;
String [] lineValues;
while(fileScanner.hasNextLine()) {
oneLine = fileScanner.nextLine();
lineValues = oneLine.split(",");
if(lineValues[0].equals("DONOR")) {
if (lineValues[1].equals("ADD") ) {
addDonor(lineValues);
}
else if (lineValues[1].equals("DEL")) {
// call method to delete
}
}
else if ( lineValues[0].equals("Donation")) {
if (lineValues[1].equals("ADD")) {
addDonation(lineValues);
}
else if (lineValues[1].equals("DEL")) {
// call method to delete
}
}
}
}
This is the addDonation method which happens after the readAndProcess method.
public static void addDonation(String [] lineValues) {
Donation donation = new Donation();
setDonationAttributes(donation, lineValues);
if (donorImpl.isIDUnique(donation.getDonorID()) == false &&
donationImpl.isIDUnique(donation.getDonationID()) == true) {
donationImpl.add(donation);
}
else {
System.out.println("ERROR: The Donation either had a non-unique"
+ " donation ID or a unique Donor ID. Was not "
+ "added to list." + donation.toString());
}
}
This is the method that sets the donation object's attributes.
public static Donation setDonationAttributes (Donation donation,
String [] lineValues) {
donation.setDonationID(Integer.parseInt(lineValues[2]));
donation.setDonorID(Integer.parseInt(lineValues[3]));
donation.setDonationDescription(lineValues[4]);
if (donation.checkDescriptionLength() == false) {
System.out.println("ERROR: Donation description is longer "
+ "than 25 characters");
}
donation.setDonationAmount(Double.parseDouble(lineValues[5]));
donation.setDonationDate(lineValues[6]);
if (lineValues[7].equalsIgnoreCase("Y") ) {
donation.setTaxDeductible(true);
}
else {
donation.setTaxDeductible(false);
}
donation.setCheckNumber(Integer.parseInt(lineValues[8]));
if (donation.checkNumberCheck()== false) {
System.out.println("ERROR: Invalid check number is not between 100 "
+ "and 5000: " + lineValues[8]);
}
return donation;
}
This is the method that checks for unique ID for donationID.
public boolean isIDUnique(int donationID) {
int index;
for (index = 0; index < donationList.size(); ++index) {
if (donationID == donationList.get(index).getDonationID() ) {
return false;
}
}
return true;
}
This is the method for checking unique donorID.
public boolean isIDUnique(int donorID) {
int index;
for (index = 0; index < donorList.size(); ++index) {
if (donorID == donorList.get(index).getDonorID() ) {
return false;
}
}
return true;
}
This is the method in the DonationImpl class that adds the object to the arraylist. The instructions for this method told me to set it up as a boolean for whatever reason, I'm not exactly sure why.
public boolean add (Donation donation) {
if (donationList.add(donation)) {
return true;
}
return false;
}
The donationImpl class to show what the arrayList creation looks like.
public class DonationImpl {
// Data Field
private ArrayList<Donation> donationList = new ArrayList<Donation>();
//Getter
public ArrayList<Donation> getDonationList() {return donationList;}
The 1 and 3 in the following examples refer to a donorID. My donorID methods and creation are all working correctly.
Example lines of text:
DONATION,ADD,101,1,Payroll deduction,22.22,07/04/1776,Y,1001
DONATION,ADD,303,3,Anniversary contribution,111.00,07/04/1777,N,2244
You have a typo
else if ( lineValues[0].equals("Donation")) {
should be
else if ( lineValues[0].equals("DONATION")) {

Why am I getting "missing return statement" error in Java even though I have return statement and exception in thread main error in 2nd class?

For example, I am getting the error here- this is just a snippet. I got the error 3 times in 3 different operators.
public boolean delete(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name)) {
directory[i] = null;
return true;
}
else
return false;
}
}
I also have the same error here:
public boolean add(String name) {
if (directory.length == 1024)
return false;
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return false;
else
directory[directorySize++] = name;
return true;
}
}
And then in my second class (the user interface portion), I keep getting this error: Exception in thread "main" java.lang.NoClassDefFoundError: Directory
Here is the entire code for that class:
import java.io.*;
import java.util.*;
public class DirectoryWithObjectDesign {
public static void main(String[] args) throws IOException {
String directoryDataFile = "Directory.txt";
Directory d = new Directory(directoryDataFile);
Scanner stdin = new Scanner(System.in);
System.out.println("Directory Server is Ready!");
System.out.println("Format: command name");
System.out.println("Enter ^Z to end");
while (stdin.hasNext()) {
String command = stdin.next();
String name = stdin.next();
if (command.equalsIgnoreCase("find")) {
if (d.inDirectory(name))
System.out.println(name + " is in the directory");
else
System.out.println(name + " is NOT in the directory");
}
else if (command.equalsIgnoreCase("add")) {
if (d.add(name))
System.out.println(name + " added");
else
System.out.println(name + " cannot add! " + "no more space or already in directory");
}
else if (command.equalsIgnoreCase("delete")) {
if (d.delete(name))
System.out.println(name + " deleted");
else
System.out.println(name + " NOT in directory");
}
else {
System.out.println("bad command, try again");
}
}
}
}
And here is the code for my directory class:
import java.util.*;
import java.io.*;
public class Directory {
//public static void main(String[] args) {
final int maxDirectorySize = 1024;
String directory[] = new String[maxDirectorySize];
int directorySize = 0;
File directoryFile = null;
Scanner directoryDataIn = null;
public Directory(String directoryFileName) {
directoryFile = new File(directoryFileName);
try {
directoryDataIn = new Scanner(directoryFile);
}
catch (FileNotFoundException e) {
System.out.println("File is not found, exiting!" + directoryFileName);
System.exit(0);
}
while (directoryDataIn.hasNext()) {
directory[directorySize++] = directoryDataIn.nextLine();
}
}
public boolean inDirectory(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return true;
else
return false;
}
}
public boolean add(String name) {
if (directory.length == 1024)
return false;
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return false;
else
directory[directorySize++] = name;
return true;
}
}
public boolean delete(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name)) {
directory[i] = null;
return true;
}
else
return false;
}
}
public void closeDirectory() {
directoryDataIn.close();
PrintStream directoryDataOut = null;
try {
directoryDataOut = new PrintStream(directoryFile);
}
catch (FileNotFoundException e) {
System.out.printf("File %s not found, exiting!", directoryFile);
System.exit(0);
}
String originalDirectory[] = {"Mike","Jim","Barry","Cristian","Vincent","Chengjun","susan","ng","serena"};
if (originalDirectory == directory)
System.exit(0);
else
for (int i = 0; i < directorySize; i++)
directoryDataOut.println(directory[i]);
directoryDataOut.close();
}
}
The point is that the compiler can't know if your for loop will be entered at all. Therefore you need a final return after the end of the for loop, too. In other words: any path that can possibly be taken within your method needs a final return statement. One easy way to achieve this ... is to have only one return statement; and put that on the last line of the method. This could look like:
Object getSomething() {
Object rv = null; // rv short for "returnValue"
for (int i=0; i < myArray.length; i++) {
if (whatever) {
rv = godKnowsWhat;
} else {
rv = IdontCare;
}
}
return rv;
}
In your second example, the indenting seems to indicate that you have a return in the else statement
directory[directorySize++] = name;
return true;
But when you look closer, you will realize that there are TWO statements after the else
else
directory[directorySize++] = name;
return true;
So this actually reads like
else
directory[directorySize++] = name;
return true;
Meaning: always put {braces} around all your blocks, even for (supposedly) one-liner then/else lines. That helps to avoid such mistakes, when a one-liner turns into a two-liner (or vice versa ;-)
The "NoClassDefFoundException" means: within the classpath that is specified to java ... there is no class Directory.class
To resolve that, you should study what the java classpath is about; and how to set it correctly.

Adding and sorting elements in array through user input

My program stops after the first element gets into array. Could you help me? Here's the code:
sorry for that
i've made some changes now ArrayQueue is my class where all my methods are implemented
QueueElement is another class that holds the type of element..
i think the problem now is at the ArrayQueue class
import java.io.*;
import java.util.Scanner;
public class QueueTest
{ private static Scanner scan =new Scanner(System.in);
public static void main(String[] args)
{
ArrayQueue queue = new ArrayQueue();
System.out.println("insert :" +
" P: to print the array "+
"S: to sort "+
"E: to empty");
do
{
if (userInput.startsWith("Y")) {
System.out.println("insert the value of element");
int vl = scan.nextInt();
System.out.println("insert the description");
String p = scan.next();
System.out.println("insert true or false");
boolean vlf = scan.nextBoolean();
queue.shtoElement(new QueueElement(vl, p, vlf));
} else if (userInput.startsWith("P")) {
queue.shfaqArray();//display the array
} else if (userInput.startsWith("S")) {
queue.rendit();//sort the array
} else if (userInput.startsWith("E")) {
queue.Empty();//empty array
}
System.out.println("Insert:" + " P: to display the array "
+ " S: to sort array "
+ " E: to empty");
userInput = scan.next();
} while (!userInput.equalsIgnoreCase("exit"));
}
}
here is the class ArrayQueue
public class ArrayQueue implements Queue
{
//build the queue
QueueElement[] tabela= new QueueElement[MADHESIA];
QueueElement element= new QueueElement();
//test if queue is empty
public boolean isEmpty()
{
boolean empty = true;
for(int k =0;k<tabela.length;k++)
{
if(tabela[k] !=null)
empty =false;
break;
}
return empty;
}
public boolean isFull()
{
boolean full=false;
for(int k=0;k<tabela.length;k++)
{
if(tabela[k]!=null)
full=true;
break;
}
return full;
}
//sort the array
public void rendit()
{
QueueElement temp=tabela[0];
for(int i=0;i<tabela.length;i++)
{
for(int j=i+1;j<tabela.length;j++)
if(tabela[j]!=null)
{
if(tabela[j].compareTo(tabela[i])==1)
{
tabela[j]=temp;
tabela[i]=tabela[j];
temp=tabela[i];
}
else
{
nrElementeve++;
}
}
if(tabela[i].getVlefshmeria()==false)
{
hiqElement(i,temp);
}
}
}
// add element into the array
public void shtoElement(QueueElement el)
{
if(isEmpty())
{
tabela[0]=el;
}
else
{
for(int i=0;i<tabela.length;i++)
{
if(tabela[i]!= null && (el.compareTo(tabela[i])==0))
{
System.out.println("element can't be added into array cause it exists !");
}
{
if(isFull())
{
int index=tabela.length;
tabela=rritMadhesine(tabela);
tabela[index]=el;
}
else
{
for(int j=0;j<tabela.length;j++)
{
if(tabela[j]==null)
tabela[j]=el;
break;
}
}
}
}
}
}
//find max of array
public QueueElement gjejMax()
{
QueueElement max = tabela[0];
for (QueueElement element :tabela)
{
if(element.getValue() > max.getValue())
{
max =element;
}
return max;
}
return max;
}
//find min of array
public QueueElement gjejMin()
{
QueueElement min= tabela[0];
for(QueueElement element : tabela)
{
if(element.getValue()< min.getValue())
{
min=element;
}
return min;
}
return min;
}
//remove element from array
public void hiqElement(int indeksi, QueueElement temp)
{
if(tabela.length > 0)
{
if(gjejMax().compareTo(temp)==0 || gjejMin().compareTo(temp)==0)
{
System.out.println("element can't be removed!");
}
else
{
for(int i=indeksi;i<tabela.length;i++)
{
tabela[i]=tabela[i+1];
}
}
nrElementeve--;
}
}
//empty array
public void Empty()
{
tabela= new QueueElement[MADHESIA];
}
//display the array
public void shfaqArray()
{
for(int i=0;i< tabela.length;i++)
{
if(tabela[i]!=null)
{
System.out.println(tabela[i]);
}
else
break;
}
}
//increase the length of array
public static QueueElement [] rritMadhesine(QueueElement[] array){
QueueElement[] tab=new QueueElement[array.length+2];
return tab;
}
private int nrElementeve;
private static final int MADHESIA = 10;
}
Don't know what ArrayQueue and QueueElement are, but...
It seems like you're reading user input then going through a decision tree to decide what to do based on that input. But at each point, you are re-reading the user input:
if(scan.next().startsWith("Y"))
{
System.out.println("Jepni vleren e elem");
vl=scan.nextInt();
System.out.println("Jepni pershkrimin e elem");
p=scan.next();
System.out.println("Jepni vlefshmerine e elem");
vlf=scan.nextBoolean();
queue.shtoElement(new QueueElement(vl,p,vlf));
}
else
{
if(scan.next().startsWith("P"))
queue.shfaqArray();
}
if(scan.next().startsWith("E"))
queue.Empty();
if(scan.next().startsWith("S"))
queue.rendit();
else
{
break;
}
I think you want something more like:
String userInput = scan.next();
if(userInput.startsWith("Y"))
{
System.out.println("Jepni vleren e elem");
vl=scan.nextInt();
System.out.println("Jepni pershkrimin e elem");
p=scan.next();
System.out.println("Jepni vlefshmerine e elem");
vlf=scan.nextBoolean();
queue.shtoElement(new QueueElement(vl,p,vlf));
}
else if(userInput.startsWith("P"))
queue.shfaqArray();
else if(userInput.startsWith("E"))
queue.Empty();
else if(userInput.startsWith("S"))
queue.rendit();
else
{
break;
}
Where you read the user input once (String userInput = scan.next();) and then decide what to do based on the userInput variable and not re-scan each time. Also, it looks like you might be missing a couple of else statements somewhere in the middle there.

Categories

Resources