Reading in from file but not saving to my array - java

I can't get my program to read from a file and populate my array.
This is my StudentAccount class which contains my array.
The array needs to be able to populate from a text file
and also add a Student by using the Scanner class.
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class Student {
// attributes
private StudentAccount[] list; // to hold the accounts
private int numStudents;
// to keep track of the number of accounts in the list
// methods
// the constructor
public Student() {
// size array with parameter
list = new StudentAccount[20];
numStudents = 0;
}
// helper method to find the index of a specified account
private int search(String studentNameIn) {
for (int i = 0; i < numStudents; i++) {
StudentAccount tempAccount = list[i];
// find the account at index i
String tempName = tempAccount.getStudentName();
// get account number
if (tempName.equals(studentNameIn))
// if this is the account we are looking for
{
return i; // return the index
}
}
return -999;
}
// return the total number of accounts in the list
public int getTotal() {
return numStudents;
}
// check if the list is empty
public boolean isEmpty() {
if (numStudents == 0) {
return true; // list is empty
} else {
return false; // list is not empty
}
}
// check if the list is full
public boolean isFull() {
if (numStudents == list.length) {
return true; // list is full
} else {
return false; // list is empty
}
}
// add an item to the array
public boolean add(StudentAccount accountIn) {
if (!isFull()) // check if list is full
{
list[numStudents] = accountIn; // add item
numStudents++; // increment total
return true; // indicate success
} else {
return false; // indicate failure
}
}
// return an account at a particular place in the list
public StudentAccount getItem(int positionIn) {
if (positionIn < 1 || positionIn > numStudents) {
return null; // indicate invalid index
} else {
return list[positionIn - 1];
}
}
// return an account with a particular account number
public StudentAccount getItem(String studentNameIn) {
int index;
index = search(studentNameIn);
if (index == -999) {
return null; // indicate invalid index
} else {
return list[index];
}
}
// remove an account
public boolean remove(String numberIn) {
int index = search(numberIn); // find index of account
if (index == -999) // if no such account
{
return false; // remove was unsuccessful
} else { // overwrite items by shifting other items along
for (int i = index; i <= numStudents - 2; i++) {
list[i] = list[i + 1];
}
numStudents--; // decrement total number of accounts
return true; // remove was successful
}
}
static void writeToFile() {
}
static void readFromFile() {
try {
FileInputStream fstream = new FileInputStream("Students.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br =
new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
in.close();
} catch (Exception e) {
System.out.println("File Not Found");
}
}
}
This is my Student class:
public class StudentAccount {
private String studentName;
private String studentDOB;
private String studentAddress;
private String studentGender;
public final static String MALE = "m";
public final static String FEMALE = "f";
public StudentAccount(String nameIn, String dobIn,
String addressIn, String genderIn) {
this.studentName = nameIn;
this.studentDOB = dobIn;
this.studentAddress = addressIn;
this.studentGender = genderIn;
}
public String getStudentName() {
return studentName;
}
public String getStudentDOB() {
return studentDOB;
}
public String getStudentAddress() {
return studentAddress;
}
public String getStudentGender() {
return studentGender;
}
public static boolean validateGender(String genderIn) {
return (genderIn.toLowerCase().compareTo(MALE) == 0)
|| (genderIn.toLowerCase().compareTo(FEMALE) == 0);
}
}
Finally this is my main class which runs my program.
The method for readFromFile
I need it to read the file one line at a time and save each line as one student record in the array. It reads in from file but doesn't put any data in the array.
public class EnrolmentRegister {
private static String lecturer = "John Smyth";
public static void main(String[] args) {
char choice;
Student newStudent = new Student();
Student.readFromFile();
do {
System.out.println();
System.out.println("1. Add A New Student Account");
System.out.println("2. Remove A Student Account");
System.out.println("3. Get Course Details ");
System.out.println("4. Quit");
System.out.println();
System.out.println("Please Choose One Of The Options Above");
choice = InputScanner.nextChar();
System.out.println();
switch (choice) {
case '1':
option1(newStudent);
break;
case '2':
option2(newStudent);
break;
case '3':
option3(newStudent);
break;
case '4':
break;
default:
System.out.println("Invalid entry");
}
} while (choice != '4');
}
static void option1(Student StudentIn) {
String gender;
System.out.print("Enter Student Name: ");
String studentName = InputScanner.nextString();
System.out.print("Enter Student Date Of Birth: ");
String studentDOB = InputScanner.nextString();
System.out.print("Enter Student Address: ");
String studentAddress = InputScanner.nextString();
do {
System.out.print("Enter Student Gender m/f: ");
gender = InputScanner.nextString();
} while (!StudentAccount.validateGender(gender));
// create new account
StudentAccount account =
new StudentAccount(studentName, studentDOB,
studentAddress, gender);
// add account to list
boolean ok = StudentIn.add(account);
if (!ok) {
System.out.println("The list is full");
} else {
System.out.println("Account created");
}
}
static void option2(Student StudentIn) {
// get account number of account to remove
System.out.print("Enter Student Name: ");
String studentName = InputScanner.nextString();
// delete item if it exists
boolean ok = StudentIn.remove(studentName);
if (!ok) {
System.out.println("No such Student Name");
} else {
System.out.println("Account removed");
}
}
static void option3(Student StudentIn) {
System.out.println("COM 180, " + lecturer);
}
static void option4(Student StudentIn) {
}
static void option5(Student StudentIn) {
}
}
/*When I call the readFromFile method and print it I get each
line of text from the text file but don't know how
to put each line from the file into the array. This is
homework and been at this for days. I know its probably
something simple but I cant work it out. Any help would
be greatly appreciated. Thanks*/

I do not see you declare InputScanner anywhere as scanner:
Scanner InputScanner = new Scanner(new File("fileNameGoesHere"));
Yet you call it multiple times in main:
choice = InputScanner.nextChar();
String studentName = InputScanner.nextString();
Note: do not capitalize variable names since it may be confused with Object types.

Related

How to print elements from linked list

I've got a linked list class with a controller class and a test class which is the main class. The code runs and accepts user input, however when I click to display all team members entered it is empty.
Where have I gone wrong? How do I get all the team members to entered to be displayed?
public class TeamMember {
private LinkedList<TeamMember> teamMembers;
public LinkedList<TeamMember> getTeamMembers() {
return teamMembers;
}
public void setTeamMembers(LinkedList<TeamMember> teamMembers) {
this.teamMembers = teamMembers;
}
private Scanner scan = new Scanner(System.in);
public TeamMember(String name) {
this.teamMembers = new LinkedList<>();
}
}
package com.view;
import com.controller.TeamMemberController;
import com.model.TeamMember;
import java.util.InputMismatchException;
import java.util.Scanner;
public class TeamMemberTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
TeamMemberController teamMemberController = new TeamMemberController();
int userInput;
do {
System.out.println("1. Add a new team member");
System.out.println("2. Find and display a team member");
System.out.println("3. Remove a team member");
System.out.println("4. Display all team members");
System.out.println("0. Quit");
//Validate user input
try {
userInput = scan.nextInt();
scan.nextLine();
} catch (InputMismatchException e) {
//if anything other than an integer is entered.
//The "scan.nextLine" fix above will not be triggered.
//It has to appear in the catch as well.
scan.nextLine();
userInput = 5;
}
switch (userInput) {
case 0:
userInput = teamMemberController.quit();
break;
case 1:
System.out.println("**********\n" + teamMemberController.addTeamMember());
break;
case 2:
System.out.println("**********\n" + teamMemberController.findTeamMember());
break;
case 3:
System.out.println("**********\n" + teamMemberController.removeTeamMember());
break;
case 4:
teamMemberController.displayAllTeamMembers();
break;
default:
System.out.println("*** Please Make another selection ***");
System.out.println("");
break;
}
} while (userInput != 0);
}
}
package com.controller;
import com.model.TeamMember;
import java.util.LinkedList;
import java.util.Scanner;
public class TeamMemberController {
private TeamMember teamMember;
public TeamMemberController() {
String name = null;
this.teamMember = new TeamMember(name);
}
Scanner scan = new Scanner(System.in);
public String addTeamMember() {
System.out.println("To go back press 0");
String name = null;
boolean keepLooping = true;
//get team member linked list
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//user enters name
while (keepLooping) {
System.out.println("Enter team member name");
//project names MUST be UNIQUE
name = scan.nextLine();
if (name.equals("0")) {
return "team member not added";
}
if (!this.checkIfTeamMemberNameExists(name)) {
keepLooping = false;
} else {
System.out.println("Team Member already exists");
System.out.println("");
}
}
//add team member to collection
teamMembers.add(new TeamMember(name));
teamMember.setTeamMembers(teamMembers);
//returns true when a team member has been successfully added
return "Name: " + name + "\n--Added--";
}
public String findTeamMember() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//if the company has no team members no need to continue
if (teamMembers.isEmpty()) {
return "Sorry no team members";
}
//get here company must have team members
System.out.println("Enter team member name");
String name = scan.nextLine();
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(name)) {
return "Name: " + t.getTeamMembers();
}
}
return "Team member not found";
}
public String removeTeamMember() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
System.out.println("Enter name of team member to remove");
System.out.println("Enter 0 to exit");
String projectToRemove = scan.nextLine();
boolean removed = false;
if (projectToRemove.equals("0")) {
return "No project removed";
}
//check existing team member names against the user input one
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(removeTeamMember())) {
teamMembers.remove(t);
removed = true;
}
}
if (removed) {
teamMember.setTeamMembers(teamMembers);
} else
return "No team member found";
return removeTeamMember() + " has successfully been removed";
}
public void displayAllTeamMembers() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
if (teamMembers.isEmpty()) {
System.out.println("Company has not added any team members");
return;
}
System.out.format(" Name%n");
for (TeamMember t : teamMembers) {
System.out.println(t.getTeamMembers() + " ");
}
}
public int quit() {
System.out.println("Are you sure you want to quit? y/n");
String userResponse = scan.nextLine();
boolean loop = true;
while (loop) {
if (userResponse.equalsIgnoreCase("y")) {
System.out.println("Program ending");
return 0;
} else if (userResponse.equalsIgnoreCase("n"))
return 5;
}
return 0;
}
public boolean checkIfTeamMemberNameExists(String name) {
//get team member linked list
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
//if a team member with the same name already exists return true
if (!teamMembers.isEmpty()) {
for (TeamMember t : teamMembers) {
if (t.getTeamMembers().equals(name)) {
return true;
}
}
}
return false;
}
}
This is the output I'm getting. How do I get it to print the names entered?
[1]: https://i.stack.imgur.com/FVhVm.png
The first problem is that TeamMembers don't remember the names you give them. Add a field for the name, and a method to retrieve it:
private String name;
public TeamMember(String name) {
this.name = name;
this.teamMembers = new LinkedList<>();
}
public String getName() {
return name;
}
The second problem is that displayAllTeamMembers does not display the "name" of the team member. There was no way it could have done it because the team members didn't even have a name, but now they do.
public void displayAllTeamMembers() {
LinkedList<TeamMember> teamMembers = teamMember.getTeamMembers();
if (teamMembers.isEmpty()) {
System.out.println("Company has not added any team members");
return;
}
System.out.format(" Name%n");
for (TeamMember t : teamMembers) {
System.out.println(t.getName());
}
}
A third possible problem is that each individual "team member" has a list of team members. That just seems confusing to me and makes me wonder if you have misread the instructions for this exercise.
Below is the minimum code change required to make your code work. But I would suggest to follow design patterns before if you a build a working prod ready system around this code.
public class TeamMember {
private static LinkedList<TeamMember> teamMembers;
public LinkedList<TeamMember> getTeamMembers() {
return teamMembers;
}
public void setTeamMembers(LinkedList<TeamMember> teamMembers) {
teamMembers = teamMembers;
}
private Scanner scan = new Scanner(System.in);
public TeamMember(String name) {
if(teamMembers==null) {
teamMembers = new LinkedList<>();
}
}
}

EDIT (judge harshly): My display() method won't display and I'm not sure why

I recently posted a question in regards to my display() method only displaying certain objects, and was able to correct that with some feedback I received earlier in regards to my toString() method. However, I had to change my idNum to an int, and now my displayMethod() won't display at all. I tried retracing my steps and am unsure what happened.
The object array that is supposed to hold an identification number, a sales amount, and the persons name. However, when I display the array, nothing is displaying. I've tried the for loop, enhanced for loop and tried just a system.out.print invoking the get() methods.
I don't know if it has something to do with my displayDatabase() method, the way I am using my Scanner variable (USER_INPUT) to set the data entered, or something to do with my constructors.
My constructor looks like this:
==================================================
public class Salesperson
{
private String salesName;
private int salesID;
private double annualSales;
public Salesperson(String salesName, int salesIDNum, double yearlySales)
{
this.salesName = salesName;
salesID = salesIDNum;
annualSales = yearlySales;
}
public String getSalesName()
{
return salesName;
}
public void setSalesName(String salesName)
{
this.salesName = salesName;
}
public double getSalesID()
{
return salesID;
}
public void setSalesID(int salesIDNum)
{
salesID = salesIDNum;
}
public double getAnnualSales()
{
return annualSales;
}
public void setAnnualSales(double yearlySales)
{
annualSales = yearlySales;
}
#Override
public String toString()
{
return String.format("%s-%-10s%-10.2f", salesName,
salesID, annualSales);
}
}
And my code for application looks like this:
import java.util.Arrays;
import java.util.Scanner;
public class CreateSalesperson
{
private static final Scanner USER_INPUT = new Scanner(System.in);
private static final int UPPER_SIZE_LIMIT = 20;
private static final int LOWER_SIZE_LIMIT = 0;
private static Salesperson[] salesStaffInDatabase = new
Salesperson[20];
private static int numOfSalesPpl = 0;
private static boolean loop = true;
public static void main(String[] args)
{
String selection;
selection = programMenu();
String response;
while(loop)
switch(selection)
{
case "A":
if(numOfSalesPpl == UPPER_SIZE_LIMIT)
{
System.out.print("Database has reached capacity.");
System.out.print(" Please delete a record before ");
System.out.println("adding to the database.");
}
else
{
addRecord();
}
break;
case "a":
if(numOfSalesPpl == UPPER_SIZE_LIMIT)
{
System.out.print("Database has reached capacity.");
System.out.print(" Please delete a record before ");
System.out.println("adding to the database.");
}
else
{
addRecord();
}
break;
case "C":
if(numOfSalesPpl == LOWER_SIZE_LIMIT)
{
System.out.print("Database is empty. ");
System.out.print("Please add a record.");
}
else
{
changeRecord();
}
break;
case "c":
if(numOfSalesPpl == LOWER_SIZE_LIMIT)
{
System.out.print("Database is empty. ");
System.out.print("Please add a record.");
}
else
{
changeRecord();
}
break;
case "E":
System.out.print("You Are Leaving Database");
loop = false;
break;
case "e":
System.out.print("You Are Leaving Database");
loop = false;
break;
}
}
public static void changeRecord()
{
String idNum;
String salesName;
double salesAmount;
String response;
System.out.print("Enter Sales ID: ");
idNum = USER_INPUT.nextLine();
if(isValidID(idNum))
{
int searchResult = Arrays.binarySearch(salesStaffInDatabase, idNum);
System.out.println(salesStaffInDatabase[searchResult]);
}
else
{
System.out.println("Invalid Sales ID");
}
}
public static boolean isValidID(String idNum)
{
boolean isValid= false;
for(int val = 0;val < numOfSalesPpl && !isValid; ++val)
{
if(salesStaffInDatabase[val].equals(idNum))
{
isValid = true;
}
}
return isValid;
}
public static void addRecord()
{
int idNum;
String salesName;
double salesAmount;
String idNo;
String response;
do
{
System.out.print("Please enter sales ID: ");
idNum = USER_INPUT.nextInt();
idNo = Integer.toString(idNum);
if(idNo.length() != 8)
System.out.println("Sales ID must be 8 digits long: ");
}
while(idNo.length() < 8 || idNo.length() > 8);
System.out.print("Name: ");
salesName = USER_INPUT.nextLine();
USER_INPUT.nextLine();
System.out.print("Sales Amount: ");
salesAmount = Double.parseDouble(USER_INPUT.nextLine());
salesStaffInDatabase[numOfSalesPpl] = new
Salesperson(salesName,idNum,salesAmount);
salesStaffInDatabase[numOfSalesPpl].setSalesName(salesName);
salesStaffInDatabase[numOfSalesPpl].setSalesID(idNum);
salesStaffInDatabase[numOfSalesPpl].setAnnualSales(salesAmount);
System.out.print("Do you want to display database Y/N?: ");
response = USER_INPUT.nextLine();
while(response.equalsIgnoreCase("Y")||response.equalsIgnoreCase("yes"))
{
displayDatabase();
}
}
public static void displayDatabase()
{
for(int val=0;val < numOfSalesPpl; val++)
{
System.out.println(salesStaffInDatabase[val]);
}
}
public static String programMenu()
{
String selection;
do
{
System.out.println("(A)dd a Record");
System.out.println("(C)hange a Record");
System.out.println("(E)xit Database");
System.out.print("Enter selection: ");
selection = USER_INPUT.nextLine();
}
while(!selection.equalsIgnoreCase("a") &&
!selection.equalsIgnoreCase("c")
&& !selection.equalsIgnoreCase("e"));
return selection;
}
}
=================================================================
In Java, whenever you want to display an object as string, you must override the toString() method.
The code that you posted, the Salesperson's toString() method returns only the salesID and anualSales. If you want to display another attribute, you must place it in the toString() method.
If you want to display the first name on the beginning of the output, you can do:
#Override public String toString() {
return String.format("%s - %-10s%-10.2f", salesFirstName, salesID, annualSales);
}
edit the toString()method in Salesperson class :
#Override
public String toString() {
return "Salesperson{" +
"salesFirstName='" + salesFirstName + '\'' +
", salesLastName='" + salesLastName + '\'' +
", salesID='" + salesID + '\'' +
", annualSales=" + String.format("%-10.2f", annualSales)+
'}';
}

Java Queue, Dequeue and Printing All Values Within The Queued/Dequeued List

Hello I think I'm really having a hard time with this part. I'm making a program that accepts a value from the user a first name and last name, and then Queues it (CASE1). Then is able to dequeue it (CASE2) and finally show everything on the list. There are no errors on the IDE, but I cant get the result that I want, At CASE 2 it throws the exception error, means that the list that gets passed to it is empty. At CASE 3 no values are shown. How do I fix this?
import java.util.*;
import java.util.Iterator;
class Customer2 {
public String lastName;
public String firstName;
public Customer2() {
}
public Customer2(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}
class HourlyCustomer2 extends Customer2 {
public double hourlyRate;
public HourlyCustomer2(String last, String first) {
super(last, first);
}
}
class Queue1<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
// return a Customer2 with null values if empty? (up to you)
return list.remove(0);
}
public E isNotEnd(){
return list.getLast();
}
public boolean hasItems() {
return !list.isEmpty();
}
public boolean isEmpty() {
return list.isEmpty();
}
public Iterator<E> iterator() {
return list.iterator();
}
public E removeFirst() {
return list.removeFirst();
}
public E getFirst() {
return list.getFirst();
}
public int size() {
return list.size();
}
public boolean hasNext() {
return false;
}
public void addItems(Queue1<? extends E> q) {
while (q.hasNext()) list.addLast(q.dequeue());
}
}
public class something {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input1;
String input2;
int choice = 1000;
Queue1<Customer2> empList;
empList = new Queue1<Customer2>();
Queue1<HourlyCustomer2> hList;
hList = new Queue1<HourlyCustomer2>();
do {
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("3,View queue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try {
choice = sc.nextInt();
switch(choice) {
case 1:
System.out.println("\nPlease enter last name: ");
input1 = sc.next();
System.out.println("\nPlease enter first name: ");
input2 = sc.next();
hList.enqueue(new HourlyCustomer2(input1, input2));
empList.addItems(hList);
System.out.println("\n"+(input2 + " " + input1) + " is successful queued");
break;
case 2:
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else
{
System.out.println("\nDequeued customer: " +empList.getFirst());
empList.removeFirst();
}
System.out.println("\nNext customer in queue: " +empList.getFirst()+"\n");
break;
case 3:
System.out.println("\nThe Customer's names are: \n");
Iterator<Customer2> it = empList.iterator();
while (it.hasNext()) {
System.out.println("\nThe customers' names are: \n");
}
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e) {
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
} while(choice != 0);
}
}
Look at your custom queue; you forgot to put the logic in your hasNext method. It will always return false. Therefore your addItems loop will never add any items to the queue.
If you need a hint towards how to do the hasNext(), my recommendation is to look at the size of your list and make a simple comparison.
public boolean hasNext() {
return false;
}
public void addItems(Queue1<? extends E> q) {
while (q.hasNext()) list.addLast(q.dequeue());
}
PS: I noticed that your code also shows the next in line. You might want to check if it's empty or hasNext() before that to not get a crash if the list was empty after that dequeuing.

Why am I getting an exception main "thread" error?

I have created two classes (and two interfaces) and then a main code. I just debugged the main code because I was getting an error that was preventing my code from working properly. I know that the problem in my Project03.java file is in line 29 and the line is input = userInput.nextLine(); . The error is:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1585)
at Project03.main(Project03.java:29)
Why is the error coming up and how can I prevent it? Thank you!
The codes are below:
SimpleMusicTrack.java
import java.util.Scanner;
import java.lang.Object;
public class SimpleMusicTrack implements PlayListTrack {
private String name;
private String artist;
private String albumName;
// Convenience constructor for unit testing
public SimpleMusicTrack(String name, String artist, String album) {
this.name = name;
this.artist = artist;
this.albumName = album;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getArtist() {
return this.artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getAlbum() {
return this.albumName;
}
public void setAlbum(String album) {
this.albumName = album;
}
public boolean getNextTrack(Scanner infile) {
if (infile == null)
return false;
while (infile.hasNext()) {
this.setName(infile.nextLine());
this.setArtist(infile.nextLine());
this.setAlbum(infile.nextLine());
return true;
}
return false;
}
public boolean equals(Object obj) {
boolean songInfo;
if (obj instanceof MusicTrack) {
MusicTrack name1 = (MusicTrack) obj;
if (this.name.equals(name1.getName())
&& this.artist.equals(name1.getArtist())
&& this.albumName.equals(name1.getArtist())) {
songInfo = true;
} else {
songInfo = false;
}
} else {
songInfo = false;
}
return songInfo;
}
public String toString() {
String allSongInfo;
allSongInfo = this.artist + " / " + this.name;
return allSongInfo;
}
}
PlayListTrack.java
import java.util.Scanner;
public interface PlayListTrack {
public String getName();
public void setName(String name);
public String getArtist();
public void setArtist(String artist);
public String getAlbum();
public void setAlbum(String album);
public boolean getNextTrack(Scanner infile);
// Attempts to read a play list track entry from a Scanner object
// Sets the values in the object to the values given in
// the file
// If it successfully loads the track, return true
// otherwise, return false
}
SimplePlayList.java
import java.util.*;
import java.util.Queue;
public class SimplePlayList implements PlayList {
Queue<PlayListTrack> queue;
public SimplePlayList(Scanner in) {
queue = new LinkedList<PlayListTrack>();
readFile(in);
}
public void readFile(Scanner in) {
Scanner inScanner = new Scanner(System.in);
Queue<PlayListTrack> queue = new LinkedList<PlayListTrack>();
while (in.hasNext()) {
queue.add(new SimpleMusicTrack(in.nextLine(), in.nextLine(), in
.nextLine()));
}
inScanner.close();
}
public PlayListTrack getNextTrack() {
while (!queue.isEmpty()) {
queue.remove();
}
return queue.peek();
}
public PlayListTrack peekAtNextTrack() {
while (!queue.isEmpty()) {
queue.peek();
}
return queue.peek();
}
public void addTrack(PlayListTrack track) {
while (!queue.isEmpty()) {
queue.add(track);
}
}
public boolean isEmpty() {
while (!queue.isEmpty()) {
return false;
}
return true;
}
}
PlayList.java
public interface PlayList {
public PlayListTrack getNextTrack();
// Removes track from PlayList and returns it to the caller
// Should return a null value if the PlayList is empty
public PlayListTrack peekAtNextTrack();
// Returns next entry to the caller, but leaves it in the list
public void addTrack(PlayListTrack track);
// Adds this track to the play list in the appropriate order
public boolean isEmpty();
// Returns true if the play list is empty
}
Project03.java
import java.io.File;
import java.io.*;
import java.util.Scanner;
public class Project03 {
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.print("Enter database filename: ");
String fileName = userInput.nextLine();
try {
File file = new File(fileName);
Scanner musicList = new Scanner(file);
String input = "P";
PlayList playList = new SimplePlayList(musicList);
while (!"Q".equalsIgnoreCase(input)) {
if ("A".equalsIgnoreCase(input)) {
displayAddTrackOption(userInput, playList);
input = "";
} else {
displayNextSong(playList);
System.out.print("> ");
input = userInput.nextLine();
}
}
displayRemainingTracks(playList);
} catch (FileNotFoundException e) {
System.out.println("Sorry, could not find your file");
}
}
private static void displayRemainingTracks(PlayList playList) {
System.out
.println("Tracks remaining in play list------------------------------------------------------------");
if (!playList.isEmpty()) {
boolean hasAnotherTrack = true;
int lineNumber = 1;
while (hasAnotherTrack) {
MusicTrack currentTrackToPlay = (MusicTrack) playList
.getNextTrack();
if (currentTrackToPlay != null) {
System.out.printf("%d - %s / %s / %s\n", lineNumber,
currentTrackToPlay.getName(),
currentTrackToPlay.getArtist(),
currentTrackToPlay.getAlbum());
lineNumber++;
} else
hasAnotherTrack = false;
}
} else
System.out.println("No tracks remaining");
}
private static void displayAddTrackOption(Scanner userInput,
PlayList playList) {
String title, artist, album, confirmation;
System.out.print("Track name: ");
title = userInput.nextLine();
System.out.print("Artist name: ");
artist = userInput.nextLine();
System.out.print("Album name: ");
album = userInput.nextLine();
System.out.println("New Track: " + title);
System.out.println("Artist: " + artist);
System.out.println("Album: " + album);
System.out.print("Are you sure you want to add this track [y/n]? ");
confirmation = userInput.nextLine();
if ("Y".equalsIgnoreCase(confirmation)) {
playList.addTrack((PlayListTrack) new SimpleMusicTrack(title,
artist, album));
}
}
private static void displayNextSong(PlayList playList) {
MusicTrack currentMusicTrackToPlay;
MusicTrack nextMusicTrackToPlay;
currentMusicTrackToPlay = (MusicTrack) playList.getNextTrack();
nextMusicTrackToPlay = (MusicTrack) playList.peekAtNextTrack();
if (currentMusicTrackToPlay != null) {
System.out.println("Currently playing: "
+ currentMusicTrackToPlay.getName() + " / "
+ currentMusicTrackToPlay.getArtist());
} else {
System.out.println("Currently playing: No Song Playing");
}
if (nextMusicTrackToPlay != null) {
System.out.println("Next track to play: "
+ nextMusicTrackToPlay.getName() + " / "
+ nextMusicTrackToPlay.getArtist());
} else {
System.out.println("Play list is empty, no more tracks");
}
System.out.println("[P]lay next track");
System.out.println("[A]dd a new track");
System.out.println("[Q]uit");
}
}
You're using two Scanner's on the same stream (System.in). The first being userInput in the main method of your Project03 class. The second being inScanner in the readFile method of your SimplePlayList class:
public void readFile(Scanner in) {
Scanner inScanner = new Scanner(System.in); // <-- remove this line
Queue<PlayListTrack> queue = new LinkedList<PlayListTrack>();
while (in.hasNext()) {
queue.add(new SimpleMusicTrack(in.nextLine(), in.nextLine(), in
.nextLine()));
}
inScanner.close(); // <--- remove this line
}
Using multiple scanners on the same stream is the underlying problem. Scanners can (and will) consume the stream - this may (will) lead to unexpected side-effects. Best not to do it.
If the input is closed, then the input [...] is closed for everyone - and that's not much fun for anyone.
"Details" on why multiple scanners are bad: Do not create multiple buffered wrappers on an InputStream
- from user166390's answer on How to use multiple Scanner objects on System.in?

Printing a separate String from the same Object

I asked this question but the way I worded it was considered a duplicate which was not similar. I am trying to print a separate String for my printAllFlights method which prints all of the user entered information. My other methods print just fine. Here is the output I am trying to achieve.
Choose action:
[1] Print planes
[2] Print flights
[3] Print plane info
[x] Quit
> 2
HA-LOL (42 ppl) (HEL-BAL)
HA-LOL (42 ppl) (BAL-HEL)
How my code is now I get the output null(0) (HEL-BAL). How can i change it to reflect the correct output. Any help would be appreciated.
public class Airport {
private String planeId;
private int capacity;
private String dest;
private String dep;
public Airport(String planeId,int capacity){
this.planeId= planeId;
this.capacity = capacity;
}
public Airport(String planeId, String dep, String dest){
this.dest= dest;
this.dep= dep;
}
public String getPlaneId(){
return this.planeId;
}
public void setPlaneId(String planeId){
this.planeId = planeId;
}
public int getCapacity(){
return this.capacity;
}
public void setCapacity(int capacity){
this.capacity = capacity;
}
public String getDestination(){
return this.dest;
}
public void setDestination(String dest){
this.dest = dest;
}
public String getDeparture(){
return this.dep;
}
public void setDeparture(String dep){
this.dep = dep;
}
public String toString(){
return planeId + " (" + capacity + ")";
}
public String secString(){
return planeId + " (" + capacity + ")" + "(" + dest + "-" + dep;
}
}
import java.util.ArrayList;
public class FlightServices {
private ArrayList<Airport> airport;
public FlightServices() {
airport = new ArrayList<Airport>();
}
public void add(String planeId, int capacity) {
airport.add(new Airport(planeId, capacity));
}
public void addFlight(String planeId, String dest, String dep) {
airport.add(new Airport(planeId, dest, dep));
}
public void printAllPlanes() {
for (Airport all : airport) {
System.out.println(all);
}
}
public void printAllFlights() {
for (Airport all : airport) {
System.out.println(all.secString());
}
}
public void printPlanesInfo(String planeId) {
for (Airport info : airport) {
if (planeId.equals(info.getPlaneId())) {
System.out.println(info);
}
}
}
}
import java.util.Scanner;
public class UserInput {
private Scanner reader;
private FlightServices air;
public UserInput(Scanner reader, FlightServices air) {
this.reader = reader;
this.air = air;
}
public void start() {
while (true) {
System.out.println("Choose operation: ");
System.out.println("[1] Add airplane");
System.out.println("[2] Add flight");
System.out.println("[3] Exit");
int input = Integer.parseInt(reader.nextLine());
if (input == 3) {
break;
} else if (input == 1) {
this.addPlane();
} else if (input == 2) {
this.addFlight();
}
}
}
public void addPlane() {
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give plane capacity: ");
int capacity = Integer.parseInt(reader.nextLine());
this.air.add(id, capacity);
}
public void addFlight() {
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give departure airport code: ");
String dep = reader.nextLine();
System.out.println("Give destination airport code: ");
String des = reader.nextLine();
this.air.addFlight(id,dep,des);
}
public void printing() {
while (true) {
System.out.println("Choose operation: ");
System.out.println("[1] Print planes");
System.out.println("[2] Print flights");
System.out.println("[3] Print plane info");
System.out.println("[4] Quit");
int command = Integer.parseInt(reader.nextLine());
if (command == 4) {
break;
} else if (command == 1) {
this.air.printAllPlanes();
} else if (command == 2) {
this.air.printAllFlights();
} else if (command == 3) {
this.addPlaneInfo();
}
}
}
public void addPlaneInfo() {
System.out.println("Give plane ID: ");
String id = reader.nextLine();
this.air.printPlanesInfo(id);
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
FlightServices air = new FlightServices();
UserInput ui = new UserInput(reader,air);
ui.start();
System.out.println("Flight Service");
System.out.println("----------");
ui.printing();
}
}
Ok.
public void add(String planeId, int capacity) {
airport.add(new Airport(planeId, capacity));
}
public void addFlight(String planeId, String dest, String dep) {
airport.add(new Airport(planeId, dest, dep));
}
You're adding some Airportobjects to your airport using addFlight() and others using add(). The ones you add using addFlight() have no capacity values and the ones using add() have no dest or dep. Do you see? Simply making two entries with the same planeId will not combine them in your arraylist. When you try to print, some values will be null depending on how you had added the Airport objects.
EDIT:
One solution i can think of, while changing your code as less as possible-
public void add(String planeId, int capacity) {
int flag=0;
for(Airport air:airport) {
if(air.planeID.equals(planeID)) {
air.capacity=capacity;
flag=1;
}
}
if(flag==0)
airport.add(new Airport(planeId, capacity));
}
And similarly edit your add() function. This way, you can have all relevant fields filled in a single entry.
Of course, a much better idea would be to restructure your classes entirely, but this should work.

Categories

Resources