Basically the program is supposed to create a "round table" of executives, with a chairman who cannot be changed. I kinda sorta almost know what I'm doing and I'm about halfway through my methods for inserting and removing executives, but I just tried to test my code to see how it was going and it gets errors as soon as I input the chairpersons information. Also, I'm not really sure at all how I would go about the removeByCorporation method in the ExecutiveList. I'm almost positive that method is nearly all incorrect and I'm just not how to remove a node in a circular doubly linked list like this.
*No need to help me with the printing methods, I simply haven't gotten to them yet.
tl;dr:
1) Why is it crashing right away?
2) I'm pretty sure my removeByCorporation method is totally wrong. If it is, any suggestions or help on how to fix it?
Here are the two classes I'm having trouble with, if you'd like to see the other ones let me know and I'll post them, but they're 99% getters and setters.
FIRST CLASS
public class ExecutiveList {
private ExecutiveNode chair;
ExecutiveNode cursor;
public ExecutiveList() {
}
public ExecutiveList (Executive chairperson) {
chair.setExecutive(chairperson);
chair.left = chair;
chair.right = chair;
}
public void insertLeftOfChair(Executive exec) {
ExecutiveNode newExec = new ExecutiveNode();
newExec.setExecutive(exec);
chair.setLeft(newExec);
}
public boolean insertRightOfExec (Executive exec, String target) {
cursor = chair;
ExecutiveNode newExec = new ExecutiveNode();
do { cursor = cursor.getLeft();
if (cursor.getExecutive().equals(exec)) {
newExec.setExecutive(exec);
cursor.getRight().setLeft(newExec);
newExec.setLeft(cursor);
newExec.setRight(cursor.getRight());
cursor.setRight(newExec);
return true;
}
else {
return false;
}
} while (cursor.getExecutive().getExecutiveName() != target);
}
public boolean insertLeftOfExec (Executive exec, String target) {
cursor = chair;
ExecutiveNode newExec = new ExecutiveNode();
do { cursor = cursor.getLeft();
if (cursor.getExecutive().equals(exec)) {
newExec.setExecutive(exec);
cursor.getLeft().setRight(newExec);
newExec.setRight(cursor);
newExec.setLeft(cursor.getRight());
cursor.setLeft(newExec);
return true;
}
else {
return false;
}
} while (cursor.getExecutive().getExecutiveName() != target);
}
public boolean removeTargetExec(String name) {
if (chair.equals(name)) {
return false;
}
else {
return false;
}
}
public int removeByCorporation(String corporation) {
int removed = 0;
cursor = chair;
do {
if (cursor.getExecutive().getCompanyName().equals(corporation)) {
cursor.setExecutive(null);
cursor.getLeft();
removed = removed + 1;
}
} while (removed > 0);
return removed;
}
public void printByCorporation(String corporation) {
}
public void printAllClockwise() {
}
public void printAllCounterClockwise() {
}
}
SECOND CLASS
import java.util.Scanner;
public class MeetingManager {
public static void main(String[] args) {
// scanner to read the users input
Scanner input = new Scanner(System.in);
// strings to pass information about the chairperson
String chairpersonName;
String chairpersonCompany;
// strings to pass information about executives other
// than the chairperson
String execName;
String execCompany;
String target;
// holds information on whether on not an operation
// was successful and how many executives were removed
// for the remove by corporation command.
boolean success;
int numRemoved = 0;
// prompts the user for information about the chairperson
// and sets it to an executive object name chairperson
System.out.println("Enter the name of the chairperson: ");
chairpersonName = input.next();
if (chairpersonName.length() < 1) {
System.out.println("Please enter a full name");
}
System.out.println("Enter the company of the chairperson: ");
chairpersonCompany = input.next();
if (chairpersonCompany.length() < 1) {
System.out.println("Please enter a full name");
}
Executive chairperson = new Executive(chairpersonName, chairpersonCompany);
// creates a new ExecutiveList object and passes information
// about the chairperson
ExecutiveList list = new ExecutiveList(chairperson);
// for loop to repeatedly print the menu and take instructions
// from the user until they choose to exit.
for (int i = 1; i > 0; i++) {
ShowMenu();
String option = input.next();
// error message for improper input
if (option.length() > 3) {
System.out.println("You can only enter one option");
}
// insert left of chairperson
else if (option.toUpperCase().equals("ILC")) {
System.out.println("Enter the executives name: ");
execName = input.next();
System.out.println("Enter the executives company: ");
execCompany = input.next();
Executive newGuy = new Executive(execName, execCompany);
list.insertLeftOfChair(newGuy);
System.out.println("Insertion successful.");
}
// insert left of executive
else if (option.toUpperCase().equals("ILE")) {
System.out.println("Enter the executives name: ");
execName = input.next();
System.out.println("Enter the executives company: ");
execCompany = input.next();
Executive newGuy = new Executive(execName, execCompany);
System.out.println("Enter the name of the target executive: ");
target = input.next();
success = list.insertLeftOfExec(newGuy, target);
if (success == true) {
System.out.println("Insertion successful.");
}
else {
System.out.println("The executive could not be inserted.");
}
}
// insert right of executive
else if (option.toUpperCase().equals("IRE")) {
System.out.println("Enter the executives name: ");
execName = input.next();
System.out.println("Enter the executives company: ");
execCompany = input.next();
Executive newGuy = new Executive(execName, execCompany);
System.out.println("Enter the name of the target executive: ");
target = input.next();
success = list.insertRightOfExec(newGuy, target);
if (success) {
System.out.println("Insertion successful.");
}
else {
System.out.println("The executive could not be inserted.");
}
}
// remove target executive
else if (option.toUpperCase().equals("RTE")) {
System.out.println("Enter the name of the executive to remove: ");
execName = input.next();
success = list.removeTargetExec(execName);
if (execName.equals(chairpersonCompany))
list.removeTargetExec(execName);
if (success) {
System.out.println(execName + " has been removed from the meeting.");
}
else {
System.out.println(execName + " could not be found.");
}
}
// remove by corporation
else if (option.toUpperCase().equals("RBC")) {
System.out.println("Enter the name of the corporation to remove: ");
execCompany = input.next();
numRemoved = list.removeByCorporation(execCompany);
if (execCompany.equals(chairperson.getCompanyName())) {
System.out.println("Invalid command: cannot remove all employees from the chairperson's corporation");
}
else if (numRemoved < 1) {
System.out.println("That corporation could not be found and no executives were removed.");
}
else {
System.out.println(numRemoved + " executive(s) from " + execCompany + " have been removed from the meeting.");
}
}
// prints by corporation
else if (option.toUpperCase().equals("PBC")) {
System.out.println("Enter the name of a corporation to display: ");
execCompany = input.next();
list.printByCorporation(execCompany);
}
// prints all counter-clockwise
else if (option.toUpperCase().equals("PCC")) {
list.printAllCounterClockwise();
}
// prints all clockwise
else if (option.toUpperCase().equals("PCL")) {
list.printAllClockwise();
}
else if (option.toUpperCase().equals("EXT")) {
System.out.println("Terminating program...");
break;
}
// Error message
else {
System.out.println("Please select a valid option.");
}
}
}
// displays menu and prompts user for input
public static void ShowMenu() {
System.out.println("\nILC) Insert an executive to the left of the chairperson\nILE) Insert an executive to the left of a given executive\nIRE) Insert an executive to the right of a given executive\nRTE) Remove Target Executive");
System.out.println("RBC) Remove By Corporation\nPBC) Print By Corporation\nPCC) Print all in counter-clockwise order\nPCL) Print all in clockwise order\nEXT) Exit the program\n\nSelect a menu option: ");
}
}
Finally, thank you to anyone who gives any sort of suggestion or advice or actual help in any way shape or form. I know people get angry when they see homework questions for some reason because they think the student is asking them to "do their homework for me", but that's not what I'm doing. I'd simply like any advice or tips, I'm not asking you to just fill in the blanks for me and fix everything (not that I'd be opposed to it :P). Thanks.
In removeByCorporation method , you are just setting the executive to null , but considering this to be a doubly linked list , dont you think you need to set the references of the previous and next executive , so that the doubly linked list doesn't break .
The trick is to make sure that, on EVERY operation, you update the item being changed and the two others which reference it (quite handily in a doubly linked list, the two which reference it are also the two it references).
Check each of your methods, and ensure that in each one you are updating 4 fields per change - two in the subject, and one each in the two that are linked from the subject.
Related
I have an ArrayList that is being filled with customer information using a Customer class. In my addCustomerRecord method, I am calling findAddIndex within the addCustomerRecord method so the data entered will be sorted prior to displaying the data. Here is my code and do not mind the fileWhatever method, I don't use it.
public class CustomerDemo
{
//arrayList of customer objects
public static ArrayList<Customer> customerAL = new ArrayList<>();
public static void main (String[] args)
{
//to hold menu choice
String menuChoice = "";
Scanner kb = new Scanner(System.in);
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
//loop priming read
menuChoice = kb.nextLine();
//make input case insensitive
menuChoice = menuChoice.toLowerCase();
do
{
if(menuChoice.equals("a"))
addCustomerRecord(kb);
else if(menuChoice.equals("d"))
{
displayCustomerRecords();
}
else if(menuChoice.equals("q"))
{
System.out.println("Program exiting..");
System.exit(0);
}
else
{
System.out.println("incorrect entry. Please re-enter a valid entry: \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}while(menuChoice.equals("a") || menuChoice.equals("d") || menuChoice.equals("q"));
kb.close();
}
/* public static void displayCustomerRecords()
{
System.out.println();
for (int i = 0; i < customerAL.size(); ++i)
{
System.out.printf("%-15s", customerAL.get(i).getLastName());
System.out.printf("%-15s", customerAL.get(i).getFirstName());
System.out.printf("%-6s", customerAL.get(i).getCustID());
System.out.printf("%15s\n", customerAL.get(i).getPhoneNumber());
}
System.out.println();
}
/**
* prompts to enter customer data and mutator methods called
* with a Scanner object passed as an argument to set data
* #param location index position of where the element will be added.
* #param kb a Scanner object to accept input
*/
public static void addCustomerRecord(Scanner kb)
{
Customer currentCustomerMemoryAddress = new Customer();
System.out.println("Enter first name: \n");
String fName = kb.nextLine();
currentCustomerMemoryAddress.setFirstName(fName);
System.out.println("Enter last name: \n");
String lName = kb.nextLine();
currentCustomerMemoryAddress.setLastName(lName);
System.out.println("Enter customer phone number: \n");
String pNum = kb.nextLine();
currentCustomerMemoryAddress.setPhoneNumber(pNum);
System.out.println("Enter customer ID number: \n");
String ID = kb.nextLine();
currentCustomerMemoryAddress.setCustID(ID);
int addLocation = findAddLocation(currentCustomerMemoryAddress);
customerAL.add(addLocation, currentCustomerMemoryAddress);
currentCustomerMemoryAddress = null;
}
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(int i = 0; i < customerAL.size(); i++)
{
//Stumped here
}
}
else
return location;
return location;
}
}
It looks like you are reinventing the wheel here William
Replace your code for displayCustomerRecords with this:
public static void displayCustomerRecords()
{
System.out.println();
customerAL.stream().map(c -> String.format("%-15s%-15s%-6s%15s\n",
c.getLastName(), c.getFirstName(), c.getCustID(), c.getPhoneNumber()))
.sorted()
.forEach(System.out::print);
System.out.println();
}
Update
Taking into account your comment you can replace your findAddLocationmethod by the following:
private static Comparator<Customer> comparator = Comparator.comparing(Customer::getLastName)
.thenComparing(Customer::getFirstName)
.thenComparing(Customer::getCustID)
.thenComparing(Customer::getPhoneNumber);
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(Customer customerInList : customerAL)
{
if(comparator.compare(customerInList, cust) > 0) {
break;
}
location++;
}
}
return location;
}
We are traversing the array using Java's enhanced for-loop and comparing the objects using a Java 8 declared comparator (which I believe is the key to this assignment).
It would be a good idea if you could look into the Comparable interface and implement it in your Customer class. That way you could simply do a simple call to customerInList.compareTo(cust) to compare both objects.
As already stated, this is not a good practice and shouldn't be used in production code.
The code was working fine before but getting runtime exception even when no changes were made. The programs purpose is, to be a database for baseball players, which houses a couple of their stats - can be seen in code below. When I run the program now, I get this error
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Assig3.getBatters(Assig3.java:47)
at Assig3.<init>(Assig3.java:62)
at Assig3.main(Assig3.java:248)
This error is not really helping me to solve anything, I am completely lost about, what is the problem which occured overnight . Anyways here is the code, it is split up between three files which receive the data from a fourth plain text file
import java.util.*;
import java.io.*;
// CS 0401 Assignment 3 main program class. Note how this class is set up
// with instance variables and methods. The idea is that the main program is itself an
// object and the methods being called are parts of the object that implement the various
// requirements. I have implemented the initial reading of the data from the file to
// get you started. You must add the menu and all of its required functionality.
// Note that this program WILL NOT COMPILE until you have completed the Batter and BatterDB
// classes to some extent. They do not have to be totally working but all of the methods
// used here must be implemented in order for this code to compile.
public class Assig3
{
private BatterDB theDB;
private Batter currBatter;
private Scanner inScan;
private String fName;
// Note how this method is working. It first reads the number of Batters from the
// file, then for each Batter it gets the names, creates the object, and mutates it
// with the instance methods shown. Finally, it adds the new object to the BatterDB
// object.
public void getBatters(String fName) throws IOException
{
Batter currB;
File inFile = new File(fName);
Scanner inScan = new Scanner(inFile);
int numBatters = inScan.nextInt();
inScan.nextLine();
for (int i = 0; i < numBatters; i++)
{
String first = inScan.nextLine();
String last = inScan.nextLine();
currB = new Batter(first, last);
int ab, h, d, t, hr;
ab = inScan.nextInt(); inScan.nextLine();
currB.setBats(ab);
h = inScan.nextInt(); inScan.nextLine();
currB.setHits(h);
d = inScan.nextInt(); inScan.nextLine();
currB.setDoubles(d);
t = inScan.nextInt(); inScan.nextLine();
currB.setTriples(t);
hr = inScan.nextInt(); inScan.nextLine();
currB.setHR(hr);
theDB.addBatter(currB);
}
}
// Constructor is really where the execution begins. Initialize the
// database (done for you) and then go into the main interactive loop (you
// must add this code).
public Assig3(String fstring) throws IOException
{
Scanner reader = new Scanner(System.in);
fName = fstring;
Batter currB;
theDB = new BatterDB(); // <-- there used to be a 2 in there
getBatters(fName);
System.out.println("The database has been loaded");
System.out.println(theDB.toString());
commandPrompter();
String command = reader.next();
while(!command.equals("8")){
if(command.equals("1")){
System.out.println(theDB.toString());
} else if(command.equals("2")){
System.out.println("First name: ");
String first = reader.next();
System.out.println("Last name: ");
String last = reader.next();
currB = new Batter(first, last);
int ab, h, d, t, hr;
System.out.print("How many times did he bat: ");
ab = reader.nextInt();
currB.setBats(ab);
System.out.println("How many hits: ");
h = reader.nextInt();
if(h>ab || h<0){
while(h>ab || h<0){
System.out.println("Invalid try again: ");
h = reader.nextInt();
}
}
currB.setHits(h);
System.out.println("How many doubles: ");
d = reader.nextInt();
if(d>ab || d<0 || d>h){
while(d>ab || d<0){
System.out.println("Invalid try again: ");
d = reader.nextInt();
}
}
currB.setDoubles(d);
System.out.println("How many triples: ");
t = reader.nextInt();
if(t>ab || t<0 || t>h || (t+d)>h){
while(t>ab || t<0 || t>h || (t+d)>h){
System.out.println("Invalid try again: ");
t = reader.nextInt();
}
}
currB.setTriples(t);
System.out.println("How many Homeruns: ");
hr = reader.nextInt();
if(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
while(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
System.out.println("Invalid try again: ");
hr = reader.nextInt();
}
}
currB.setHR(hr);
theDB.addBatter(currB);
} else if(command.equals("3")){
System.out.println("Player first name: ");
String firstNameSearch = reader.next();
System.out.println("Player last name: ");
String lastNameSearch = reader.next();
currB = theDB.findBatter(firstNameSearch, lastNameSearch);
if(currB == null){
System.out.println("The player you wish to see in not in this database");
} else {
System.out.println(currB.toString());
}
} else if(command.equals("4")){
System.out.println("Player first name: ");
String firstNameSearch = reader.next();
System.out.println("Player last name: ");
String lastNameSearch = reader.next();
currB = theDB.findBatter(firstNameSearch, lastNameSearch);
if(currB == null){
System.out.println("The player you wish to remove in not in this database");
} else {
System.out.println("The player has been removed from the database");
theDB.removeBatter(currB);
}
} else if(command.equals("5")){
System.out.println("Player first name: ");
String firstNameSearch = reader.next();
System.out.println("Player last name: ");
String lastNameSearch = reader.next();
currB = theDB.findBatter(firstNameSearch, lastNameSearch);
if(currB == null){
System.out.println("The player you wish to edit in not in this database");
} else {
int ab, h, d, t, hr;
System.out.print("How many times did he bat: ");
ab = reader.nextInt();
currB.setBats(ab);
System.out.println("How many hits: ");
h = reader.nextInt();
if(h>ab || h<0){
while(h>ab || h<0){
System.out.println("Invalid try again: ");
h = reader.nextInt();
}
}
currB.setHits(h);
System.out.println("How many doubles: ");
d = reader.nextInt();
if(d>ab || d<0 || d>h){
while(d>ab || d<0){
System.out.println("Invalid try again: ");
d = reader.nextInt();
}
}
currB.setDoubles(d);
System.out.println("How many triples: ");
t = reader.nextInt();
if(t>ab || t<0 || t>h || (t+d)>h){
while(t>ab || t<0 || t>h || (t+d)>h){
System.out.println("Invalid try again: ");
t = reader.nextInt();
}
}
currB.setTriples(t);
System.out.println("How many Homeruns: ");
hr = reader.nextInt();
if(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
while(hr>ab || hr<0 || hr>h || (hr+d+t)>h){
System.out.println("Invalid try again: ");
hr = reader.nextInt();
}
}
currB.setHR(hr);
}
} else if(command.equals("6")){
theDB.sortName();
} else if(command.equals("7")){
theDB.sortAve();
} else {
System.out.println("What the heck that was not an option, bye.");
}
commandPrompter();
command = reader.next();
}
theDB.toStringFile();
System.out.println("Thanks for using the DB! Bye.");
}
private void commandPrompter(){
System.out.println("Please choose one of the options below: ");
System.out.println("1) Show the list of players");
System.out.println("2) Add a new player");
System.out.println("3) Search for a player");
System.out.println("4) Remove a player");
System.out.println("5) Update a player");
System.out.println("6) Sort the list alphabetically");
System.out.println("7) Sort the list by batting average");
System.out.println("8) Quit the program [list will be saved]");
}
// Note that the main method here is simply creating an Assig3 object. The
// rest of the execution is done via the constructor and other instance methods
// in the Assig3 class. Note also that this is using a command line argument for
// the name of the file. All of our programs so far have had the "String [] args"
// list in the header -- we are finally using it here to read the file name from the
// command line. That name is then passed into the Assig3 constructor.
public static void main(String [] args) throws IOException
{
Assig3 A3 = new Assig3(args[0]);
}
}
BatterDB:
import java.util.ArrayList;
import java.util.Collections;
import java.util.stream.Collectors;
import java.io.PrintWriter;
// CS 0401 BatterDB class
// This class is a simple database of Batter objects. Note the
// instance variables and methods and read the comments carefully. You minimally
// must implement the methods shown. You may also need to add some private methods.
// To get you started I have implemented the constructor and the addBatter method for you.
public class BatterDB
{
private ArrayList<Batter> theBatters = new ArrayList<Batter>(); // ArrayList of Batters
private int num; // int to store logical size of DB
// Initialize this BatterDB
public BatterDB()
{
num = 0;
}
// Take already created Batter and add it to the DB. This is simply putting
// the new Batter at the end of the array, and incrementing the int to
// indicate that a new movie has been added. If no room is left in the
// array, resize to double the previous size, then add at the end. Note that
// the user never knows that resizing has even occurred, and the resize()
// method is private so it cannot be called by the user.
public void addBatter(Batter b)
{
theBatters.add(b);
num++;
}
// Remove and return the Batter that equals() the argument Batter, or
// return null if the Batter is not found. You should not leave a gap in
// the array, so elements after the removed Batter should be shifted over.
public Batter removeBatter(Batter b)
{
theBatters.remove(b);
return b;
}
// Return logical size of the DB
public int numBatters()
{
return theBatters.size();
}
// Resize the Batter array to that specified by the argument
private void resize(int newsize)
{
//Don't need this now that it's an array list!
}
// Find and return the Batter in the DB matching the first and last
// names provided. Return null if not found.
public Batter findBatter(String fName, String lName)
{
Batter currentB = null;
String fullNameSearch = lName+","+fName;
for(int i=0; i<theBatters.size(); i++){
if(fullNameSearch.toUpperCase().equals(theBatters.get(i).getName().toUpperCase())){
currentB = theBatters.get(i);
}
}
return currentB;
//change
}
// Sort the DB alphabetically using the getName() method of Batters for
// comparison
public void sortName()
{
int j;
for ( j = 0; j < theBatters.size()-1; j++)
{
if ( theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j+1).getName()) > 0 )
{ // ascending sort
Collections.swap(theBatters, j, j+1);
j=0;
}
if ( theBatters.get(j).getName().compareToIgnoreCase(theBatters.get(j+1).getName()) > 0 )
{ // ascending sort
Collections.swap(theBatters, j, j+1);
j=0;
}
}
}
// Sort the DB from high to low using the getAve() method of Batters for
// comparison
public void sortAve()
{
int j;
for ( j = 0; j < theBatters.size()-1; j++)
{
if ((theBatters.get(j+1).getAve() - theBatters.get(j).getAve()) > 0 )
{ // ascending sort
Collections.swap(theBatters, j, j+1);
j=0;
}
if ((theBatters.get(j+1).getAve() - theBatters.get(j).getAve()) > 0 )
{ // ascending sort
Collections.swap(theBatters, j, j+1);
j=0;
}
}
}
// Return a formatted string containing all of the Batters' info. Note
// that to do this you should call the toString() method for each Batter in
// the DB.
public String toString()
{
return theBatters.stream().map(b -> b.toString()).collect(Collectors.joining("\n"));
}
// Similar to the method above, but now we are not formatting the
// string, so we can write the data to the file.
public void toStringFile()
{
try{
PrintWriter writer = new PrintWriter("batters.txt", "UTF-8");
writer.println(theBatters.size());
for(int i=0; i<theBatters.size(); i++){
String[] parts = theBatters.get(i).getName().split(",");
String fName= parts[1];
String lName = parts[0];
writer.println(fName);
writer.println(lName);
writer.println(theBatters.get(i).getAtBats());
writer.println(theBatters.get(i).getHits());
writer.println(theBatters.get(i).getDoubles());
writer.println(theBatters.get(i).getTriples());
writer.println(theBatters.get(i).getHomeRuns());
}
writer.close();
} catch (Exception e) {
System.out.println("Did not work, sorry :(");
}
}
}
Batter:
public class Batter {
private String firstName;
private String lastName;
private int atBats;
private int hits;
private int doubles;
private int triples;
private int homeRuns;
public Batter(String fName, String lName){
firstName = fName;
lastName = lName;
}
public void setBats(int batCount){
atBats = batCount;
}
public void setHits(int hitCount){
hits = hitCount;
}
public void setDoubles(int doubleCount){
doubles = doubleCount;
}
public void setTriples(int tripleCount){
triples = tripleCount;
}
public void setHR(int homeRunCount){
homeRuns = homeRunCount;
}
public double getAve(){
double one = this.hits;
double two = this.atBats;
double average = (one / two);
return average;
}
public int getAtBats(){
return this.atBats;
}
public int getHits(){
return this.hits;
}
public int getDoubles(){
return this.doubles;
}
public int getTriples(){
return this.triples;
}
public int getHomeRuns(){
return this.homeRuns;
}
public String getName(){
String fullName = this.lastName + "," + this.firstName;
return fullName;
}
public boolean equals(){
return true;
}
public String toString(){
return "Player: "+getName()+"\nAt Bats: "+this.atBats+"\nHits: "+this.hits+"\nDoubles: "+this.doubles+"\nTriples: "+this.triples+"\nHome Runs: "+this.homeRuns;
}
}
batters.txt (text file):
5
Cannot
Hit
635
155
12
7
6
Major
Hitter
610
290
50
25
65
The
Hulk
650
300
0
0
300
Iron
Man
700
600
300
0
300
Herb
Weaselman
600
200
20
15
30
Error :
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at Assig3.getBatters(Assig3.java:47)
at Assig3.<init>(Assig3.java:62)
at Assig3.main(Assig3.java:248)
Description :
NoSuchElementException mean whatever your code is trying to read is not there
mean there is no element which you are trying to read.
At line 47 i.e hr = inScan.nextInt(); inScan.nextLine();
your code is trying to read an int and nextline
but there is no next line in your source file
which basically will happen in the last iteration of your loop
Reason is when your code reach your last file entry i.e 30 then
hr = inScan.nextInt(); inScan.nextLine();
//^^^ this will read 30
// but ^^^ there is no next line and hence the exception
Solution : either use hasNextLine or add nextline by using an enter at the end of the file
hr = inScan.nextInt();
if(inScan.hasNextLine())
inScan.nextLine();
or you can manipulate file then simply add an empty line in your file at the end using enter (which i don't recommend)
I'm a student working on a project, and I have a method takes a Person, adds it to the array (Admits[]) and writes the array to file. The method currently does not do this, as the numSoFar value does not increase and the person is not saved to the array. (either that or i made a mistake in my tester class) I put coding of both classes below, and hope someone can point me in the direction of what i am doing wrong. As this is a school project please try not to be too specific actually, just tell me some suggestions as to why my coding may not work. I don't want to pass off someone else's work as my own; i just need a new set of eyes to see what I haven't.
Coding in my Database class
//adds a Person to the Database
public void addPerson(Person admit)
{
for(int i = 0; i < numSoFar; i++)//i = -1 when admit's alpabetical spot in Database has been located
{
if((i == numSoFar-1) || (i == numSoFar))//there is no Person in this index, so this is the end of the database
{
Admits[i] = admit;
numSoFar = numSoFar + 1;
}
else
{
if(Admits[i].getLN().compareTo(admit.getLN()) == -1)//last name comes before last name of Person at index i
{
Person current= Admits[i];
Admits[i] = admit;
while(i <= numSoFar)
{
Person next = Admits[i+1];
Admits[i+1] = current;
current = next;
i++;
}
numSoFar++;
}
else
{
if(Admits[i].getLN().equalsIgnoreCase(admit.getLN()))//admit and Person at index i have the same last name
{
if(Admits[i].getFN().compareTo(admit.getFN()) == -1)
{
Person current= Admits[i];
Admits[i] = admit;
while(i < numSoFar)
{
Person next = Admits[i+1];
Admits[i+1] = current;
current = next;
i++;
}
numSoFar++;
}
else
{
if(Admits[i].getFN().equalsIgnoreCase(admit.getFN())) //admit and Person at index i are the same person
{
Scanner in = new Scanner(System.in);
System.out.println("There is already a person with this name in the database.");
int c = 0;
while(c != 1 || c != 2)
{
System.out.println("If you would like to keep that person, enter '1', and if you would like to replace him/her with the person entered, enter 2.");
if(c == 2)
{
Admits[i] = admit;
}
}
}
}
}
}
}
}
this.writeToFile();
}
This is the coding to add a new person in my tester (i stopped after case 1
Person[] Admits = new Person[5000];
Database dB = new Database(Admits);
dB.fillFromFile();//fills array with info from text file
Scanner in = new Scanner(System.in);
String c = "0";
System.out.println("Hello, and thank you for using the Notre Dame admitted students friend-finder");
while(!c.equals("6")) //Menu for user to traverse, is exited when user enters a 6
{
System.out.println("Please pick the desired action from one of the options below and enter its number.");
System.out.println(" 1: Enter info for a new admitted student and check matches");
System.out.println(" 2: Change info for an admitted student already in the database");
System.out.println(" 3: Delete an admitted student from the database");
System.out.println(" 4: Log in as an admitted student to check matches");
System.out.println(" 5: View contact info for a certain person in the database");
System.out.println(" 6: Exit the program");
c = in.next();
switch(c)
{
case "1": //create new student and check matches
System.out.println("Enter your first name:");
String firstName = in.next();
System.out.println("Enter your last name:");
String lastName = in.next();
System.out.println("Enter your gender:");
String gen = in.next();
Person p = new Person(lastName, firstName, gen);
//String chracteristics
System.out.println("Are you an a. introvert or b. extrovert? (enter a or b):");
String traitIntroExtro = in.next();
while(!(traitIntroExtro.equalsIgnoreCase("a") || traitIntroExtro.equalsIgnoreCase("b")))
{
System.out.println("Invalid choice.Please re-enter your choice:");
traitIntroExtro = in.next();
}
if(traitIntroExtro.equalsIgnoreCase("a"))
{
p.setTraitIntroExtro("Introvert");
}
else
{
p.setTraitIntroExtro("Extrovert");
}
There above coding is basically repeated with different variables, but as there are many i will cut to the end of case 1
//facebook url to contact matches with
System.out.println("Please enter the url of your facebook profile page:");
String url = in.next();
p.setFacebookUrl(url);
dB.addPerson(p);
p.fillMatches(dB);
boolean first = dB.first();
if(first == true)//the database only has one person in it
{
System.out.println("You are currently the only person in the database.");
}
else//the database has atleast one person in it
{
System.out.println("Your top 2 most compatible people currently in the data base are:");
System.out.println(p.getMatches().getHead().getPerson() + ", who can be found at " + p.getMatches().getHead().getPerson().getFacebookUrl());
if(dB.getNumSoFar() == 2)
{
System.out.println("This is the only other person in the database.");
}
else
{
System.out.println(p.getMatches().getHead().getNextNode().getPerson() + ", who can be found at " + p.getMatches().getHead().getNextNode().getPerson().getFacebookUrl());
}
}
break;
Let's take a look at the case you're adding a Person to the end of the array (as you would if there were no entries yet):
for(int i = 0; i < numSoFar; i++)
{
if((i == numSoFar-1) || (i == numSoFar))
{
Admits[i] = admit;
numSoFar = numSoFar + 1;
}
else
{ /* doesn't matter */ }
}
Your for loop is never going to exit: if i = numSoFar-1, then each iteration of the for loop will increment both i and numSoFar by 1 and as such i < numSoFar will always be true.
Also, a comment mentions that i will be -1. I don't see any place where you assign i other than by deceleration and increment, so how could it ever be -1?
Finally, once you've got a working version I'd suggest posting your code over at the Code Review Stack Exchange. There are some non-functional issues out of scope for here on Stack Overflow that I'd point out there (such as the else { if (...) {...} } vs else if (...) {...} mentioned in the comments).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have this issue where I can populate a LinkedList with objects which I can manipulate later in this shop system I am designing. The problem is that when I populate the list with more than one Object and then search for that object in the List; my program will tell me that the object I am looking for doesn't exist even though I can list the contents of the list and it will show.
Any help would be appreciated.
import java.io.*;
import java.util.*;
public class Sales extends addVideoGame implements java.io.Serializable{
private static LinkedList<VideoGames> sellGame = new LinkedList<>();
private static String searchTerm;
private static int searchQ;
public static void sellItem(){
sellGame = games;
int listLength = sellGame.size();
searchTerm = IBIO.inputString("What item would you like to sell: ");
for(VideoGames v : sellGame){
if(v.getTitle().contains(searchTerm)){
IBIO.output("Item found: " + searchTerm);
searchQ = v.getQuantity();
IBIO.output("Available Quantity: " + searchQ);
int sellQ = IBIO.inputInt("How much of this item would you like to sell: ");
if(sellQ > searchQ){
IBIO.output("The amount you have specified is greater than the \ncurrent stock.");
sellItem();
} else {
searchQ = searchQ - sellQ;
v.setQuantity(searchQ);
double sellP;
sellP = sellQ * v.getPrice();
IBIO.output("£"+sellP);
String confirm = IBIO.input("This is the price you are selling these items for. Type 'Yes' to complete the order or 'No' to reject it. ");
if(confirm.equalsIgnoreCase("Yes")){
IBIO.output("Order complete!");
try{
int receiptCount = 0;
PrintWriter receipt = new PrintWriter("C:\\Users\\Yemi\\Desktop\\TheStore\\receipt"+ receiptCount +".txt");
receipt.println("Item sold: " + v.getTitle());
receipt.println("Quantity sold: " + sellQ);
receipt.close();
receiptCount = receiptCount + 1;
IBIO.output("Receipt saved to: C:\\Users\\Yemi\\Desktop\\TheStore");
} catch(IOException io){
io.printStackTrace();
}
IBIO.output("Thank you for buying from Gamers Avenue UK!");
} else if(confirm.equalsIgnoreCase("No") && TheStore.privilege){
AccessMenus.adminMenu();
} else {
AccessMenus.userMenu();
}
if(TheStore.privilege){
AccessMenus.adminMenu();
} else {
AccessMenus.userMenu();
}
}
} else {
IBIO.output("The item you are looking for does not exist.");
sellItem();
}
}
}
}
Here are the classes used to navigate the program if anyone needs them:
public class TheStore {
static String password; //Variable created to hold and check the value of password against the correct value.
public static boolean privilege = false; //Variable created to distinguish the difference between a normal user and a user with administrator privileges.
public static void main(String[] args) {
IBIO.output("Welcome to Gamers Avenue UK!");
IBIO.output("Please make sure that you enter the correct password for your given privileges.");
password = IBIO.inputString("Enter password: ");
if(password.equalsIgnoreCase("admin")){ //Checks the entered value against the correct value.
privilege = true; //Sets global boolean value to true, so that admin access is granted.
IBIO.output(" ");
AccessMenus.adminMenu();//If password is correct, loads admin menu.
} else if(password.equalsIgnoreCase("user")){
privilege = false; //Keeps admin access off, so that unauthorised changes cannot be made.
IBIO.output(" ");
AccessMenus.userMenu();//If correct, loads user menu.
} else {
IBIO.output("The password is incorrect. Exiting program.");
System.exit(1); //If an incorrect password is entered, the program will close.
} //close else
}//close main
}//close class TheStore
Access Menus:
public class AccessMenus{
public static int choice;//Variable which will hold the value, which corresponds to an action depending on what value is entered.
public AccessMenus(){ //Null argument constructor, to set values to 0.
AccessMenus.choice = 0;
}
public AccessMenus(int c){ //Single argument constructor.
AccessMenus.choice = c;
}
public static void userMenu(){
IBIO.output("1: Sell a product.");
IBIO.output("2: Register a customer in the Loyalty programme.");
IBIO.output("3: Stock check.");
IBIO.output("4: Log out.");
IBIO.output(" ");
IBIO.output("Please make your choice: ");
choice = IBIO.inputInt();
if(choice == 1){
Sales.sellItem();
} else if(choice == 2){
CustomerRandom.customerMenu();
} else if(choice == 3){
StockCheck.checkStock();
} else if(choice == 4){
IBIO.output("Logging out.");
System.exit(1);
} else {
IBIO.output("Invalid choice. Returning to menu.");
userMenu(); //If the value entered does not correspond to any action, the program will treat it as invalid and return to the menu.
}//close else
}//close userMenu
public static void adminMenu(){
IBIO.output("1: Sell a product.");
IBIO.output("2: Go the Videogame management menu.");
IBIO.output("3: Stock check.");
IBIO.output("4: Register a customer in the Loyalty programme.");
IBIO.output("5: Log out.");
IBIO.output(" ");
IBIO.output("Please make your choice: ");
choice = IBIO.inputInt();
if(choice == 1){
Sales.sellItem();
} else if(choice == 2){
addVideoGame.vgMenu();
}else if(choice == 3){
StockCheck.checkStock();
} else if(choice == 4){
CustomerRandom.customerMenu();
} else if(choice == 5){
IBIO.output("Logging out.");
System.exit(1);
} else {
IBIO.output("Invalid input. Returning to menu.");
adminMenu();
} //end else
}//close AdminMenu
}//close AccessMenus
This class is necessary as it allows you to populate the list:
import java.util.*;
import java.io.*;
public class addVideoGame extends VideoGames implements java.io.Serializable{
public static VideoGames game = new VideoGames();
public static VideoGames eGame = new VideoGames();
public static LinkedList <VideoGames> games = new LinkedList<>();
public static LinkedList <VideoGames> loadList = new LinkedList<>();
private static int vgChoice = 0;
public static int vgCount = 0;
public static int vgAmount = 0;
public static void vgMenu(){
IBIO.output("WARNING: USING OPTION 4 TO LOAD IN A LOCAL FILE WILL ERASE EVERYTHING CONTAINED IN THE CURRENT LIST. \nSave everything in the current list using option 3 before loading in data.");
IBIO.output("1: Add a new videogame to the list.");
IBIO.output("2: View the contents of the list.");
IBIO.output("3: Save the contents of the list to the local area.");
IBIO.output("4: Load in data from a local file.");
IBIO.output("5: Return to the main menu.");
vgChoice = IBIO.inputInt("Make your choice: ");
if(vgChoice == 1){
vgAmount = IBIO.inputInt("How many games would you like to add to the database?: ");
for(int x = 0; x < vgAmount; x = x + 1){
VideoGames vg = new VideoGames();
vg.setTitle(IBIO.inputString("Enter the title of the game: "));
vg.setPublisher(IBIO.inputString("Enter the publisher of the game: "));
vg.setDeveloper(IBIO.inputString("Enter the developer of the game: "));
vg.setAgeRating(IBIO.inputInt("Enter the age rating of the game: "));
vg.setGenre(IBIO.inputString("Enter the genre of the game: "));
vg.setQuantity(IBIO.inputInt("Enter the available quantity of the game: "));
vg.setPrice(IBIO.inputDouble("Enter the recommended retail price: "));
game = vg;
games.add(vg);
IBIO.output(" ");
}
vgMenu();
} else if(vgChoice == 2){
IBIO.output("Current amount of games in the list: " + games.size());
Iterator itr = games.iterator();
while(itr.hasNext()){
Object g = itr.next();
IBIO.output(g + " ");
}
//System.out.println(Arrays.toString(games.toArray()));
vgMenu();
} else if(vgChoice == 3){
try{
ListIterator output = games.listIterator();
while(output.hasNext()){
Object o = output.next();
FileOutputStream fileOut = new FileOutputStream("C:\\Users\\Yemi\\Desktop\\TheStore\\games.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(game);
out.close();
fileOut.close();
IBIO.output("Data saved to C:\\Users\\Yemi\\Desktop\\TheStore\\games.ser");
}
} catch(IOException io){
io.printStackTrace();
}
vgMenu();
} else if(vgChoice == 4){
eGame = null;
try{
ListIterator input = games.listIterator();
while(input.hasNext()){
Object i = input.next();
FileInputStream fileIn = new FileInputStream("C:\\Users\\Yemi\\Desktop\\TheStore\\games.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
eGame = (VideoGames) in.readObject();
in.close();
fileIn.close();
games.clear();
games.add(eGame);
IBIO.output("Item added to list from local file.");
}
} catch (IOException i){
i.printStackTrace();
return;
} catch(ClassNotFoundException c){
IBIO.output("VideoGames class not found");
c.printStackTrace();;
return;
}
vgMenu();
} else if(vgChoice == 5){
IBIO.output("Returning to main menu: ");
AccessMenus.adminMenu();
}
}
}
Again, any help would be greatly appreciated!
I guess the bug is cause by the else-block inside the loop inside sellItem().
Try this (although still I think you should remove the call to sellItem() inside the final if):
import java.io.*;
import java.util.*;
public class Sales extends addVideoGame implements java.io.Serializable{
private static LinkedList<VideoGames> sellGame = new LinkedList<>();
private static String searchTerm;
private static int searchQ;
public static void sellItem(){
sellGame = games;
int listLength = sellGame.size();
searchTerm = IBIO.inputString("What item would you like to sell: ");
boolean foundItem = false;
for(VideoGames v : sellGame){
if(v.getTitle().contains(searchTerm)){
foundItem = true;
IBIO.output("Item found: " + searchTerm);
searchQ = v.getQuantity();
IBIO.output("Available Quantity: " + searchQ);
int sellQ = IBIO.inputInt("How much of this item would you like to sell: ");
if(sellQ > searchQ){
IBIO.output("The amount you have specified is greater than the \ncurrent stock.");
sellItem();
} else {
searchQ = searchQ - sellQ;
v.setQuantity(searchQ);
double sellP;
sellP = sellQ * v.getPrice();
IBIO.output("£"+sellP);
String confirm = IBIO.input("This is the price you are selling these items for. Type 'Yes' to complete the order or 'No' to reject it. ");
if(confirm.equalsIgnoreCase("Yes")){
IBIO.output("Order complete!");
try{
int receiptCount = 0;
PrintWriter receipt = new PrintWriter("C:\\Users\\Yemi\\Desktop\\TheStore\\receipt"+ receiptCount +".txt");
receipt.println("Item sold: " + v.getTitle());
receipt.println("Quantity sold: " + sellQ);
receipt.close();
receiptCount = receiptCount + 1;
IBIO.output("Receipt saved to: C:\\Users\\Yemi\\Desktop\\TheStore");
} catch(IOException io){
io.printStackTrace();
}
IBIO.output("Thank you for buying from Gamers Avenue UK!");
} else if(confirm.equalsIgnoreCase("No") && TheStore.privilege){
AccessMenus.adminMenu();
} else {
AccessMenus.userMenu();
}
if(TheStore.privilege){
AccessMenus.adminMenu();
} else {
AccessMenus.userMenu();
}
}
break;
}
}
if(!foundItem) {
IBIO.output("The item you are looking for does not exist.");
sellItem();
}
}
}
And while this may work I would generally advise to transform searchTerm into an argument to the function and searchQ to the return value of the function. Doing so increases isolation between concurrent processes and clarifies which parameters are needed for the correct execution of the function.
Im having some trouble printing out details ive put into my array. when i run my addBook i out in details of two books, but when i select option 2 from menu, i get a runtime error (outofbounds),
Above is resolved by adding [i] to the printline and changing my loop length.
The problem i am having now if my BookID from my loanbook, its not incrementing.
import java.util.Scanner;
public class library {
static Scanner keyboard = new Scanner(System.in);
static boolean run = true;
public static fiction [] fictionArray = new fiction[2];
public static nonfiction [] nonfictionArray = new nonfiction[2];
public static void main (String[] args){ // main class method
while (run){ // this while statement allows the menu to come up again
int answer = 0; // answer initialized to Zero
boolean isNumber;
do{ // start of validation
System.out.println("1. Add book"); // Menu selections
System.out.println("2. Display the books available for loan");
System.out.println("3. Display the books currently on loan");
System.out.println("4. Make a book loan");
System.out.println("5. Return book ");
System.out.println("6 Write book details to file");
if (keyboard.hasNextInt()){ // I would like to set values to =>1 <=6
answer = keyboard.nextInt(); // this is more validation for the input for menu selection
isNumber = true;
} else { // else if number not entered, it will prompt for the correct input
System.out.print(" You must enter a number from the menu to continue. \n");
isNumber = false;
keyboard.next(); // clears keyboard
}
}
while (!(isNumber)); // while to continue program after the do has completed
switch (answer){ // switch statement - uses answer from the keyboard to select a case
case 1:
addBook(); // adds book
break;
case 2:
for (int i=0; i<5; i++){
if (fictionArray[i] != null){
System.out.println(fictionArray);}
if (nonfictionArray[i] != null){
System.out.println(nonfictionArray);}}
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
}
}
}
static void addBook(){
loanbook [] loanArray = new loanbook[2];
String title,author;
int choice;
for(int x = 0; x < loanArray.length; x++){
System.out.print("Press 1 for Fiction or 2 for Non Fiction: "); // sub menu for fiction and non fiction
choice = keyboard.nextInt();
if (choice == 1){
for(int count = 0; count < fictionArray.length; count++){
System.out.print("Enter title: ");
title= keyboard.nextLine();
title= keyboard.nextLine();
System.out.print("Enter author: ");
author= keyboard.nextLine();
fictionArray[count] = new fiction(title, author);
System.out.println("The book information you entered was : " + fictionArray[count].toString()); // this will show the entry which was inout to the array
count++; }}
else if (choice == 2) {
for(int count = 0; count < nonfictionArray.length; count++){
System.out.print("Enter title: ");
title= keyboard.nextLine();
title= keyboard.nextLine();
System.out.print("Enter author: ");
author= keyboard.nextLine();
nonfictionArray[count] = new nonfiction(title, author);
System.out.println("The book information you entered was : " + nonfictionArray[count].toString()); // this will show the entry which was inout to the array
count++;}}
else{ int noBooks = loanArray.length;
for (int i=0; i<noBooks; i++){
System.out.print(loanArray[x]);
}}}} // addbook
} // Library end
Below is my Superclass , then my subclass
public class loanbook {
private String title,author;
private int bookID;
public loanbook(String pTitle,String pAuthor){
bookID = 0;
title = pTitle;
author = pAuthor;
bookID++;
} // Constructor
public void setTitle(String pTitle){
title = pTitle;
} // setTitle
protected String getTitle(){
return title;
} // getTitle
protected String getAuthor(){
return author;
} // getAuthor
public String toString(){
return "\n BookID: "+ bookID+"\n" + " Title: "+ getTitle()+"\n" +" Author : "+ getAuthor()+ "\n";
}
} // loanbook
My subclasses are the same except for the class name and constructor
public class fiction extends loanbook {
String bookType;
private String getBookType; // Would be fiction
public fiction(String pTitle,String pAuthor){
super(pTitle,pAuthor);
} // constructor
protected void setBookType (String pBookType){
bookType = pBookType;
} // setter for bookType
protected String getBookType(){
return "Fiction";
}
public String toString(){
return super.toString() +" This book is : "+ getBookType();
}
} // class
You've declared your fictionarray and nonfictionarray to be of length 2. However, in your case 2, you are looping 5 times:
for (int i=0; i<5; i++){
if (fictionArray[i] != null){
Change it to 2. It's possible you changed the array length in the declaration, but forgot to change the loop iteration. In that case, you can just use the array's length:
for (int i = 0; i < fictionArray.length; i++) {
Additionally, it looks like you want to print out the specific array element, not the array itself:
System.out.println(fictionArray[i]);
and likewise for nonfictionarray and the nonfiction class.
Two things I see
if (fictionArray[i] != null){
System.out.println(fictionArray);}
if (nonfictionArray[i] != null){
System.out.println(nonfictionArray);}}
You're trying to print the entire array System.out.println(fictionArray). You probably want System.out.println(fictionArray[i])
Also you should set your array sizes to 5 if you want to loop 5 times