I am trying to compare a string which the user enters in case 3 in the ProcessRecords class. I am then trying to compare that string to each last name in the Arraylist and if a record matches the user's input then i want to print it. I am not sure how to accomplish this but I would appreciate any guidance.
import java.util.*;
import java.io.*;
public class ProcessRecords {
public static void AskUser()
throws Exception {
Scanner preference = new Scanner(System.in);
//Creating a new scanner will allow us to gather user input
boolean flag=true;
//I will use this for my while loop
while (flag) {
System.out.println("What type of Search would you like to run?\n 1)Search for all students\n 2) Search for students graduating in a specific year\n 3)Search for students whose last name begins with a certain string\n(4) Exit\n");
int searchType=preference.nextInt();
//This variable will store what type of query the user would like to run
switch(searchType) {
case 1:
System.out.println("Gathering Records for all students\n");
//Query.getAll();
break;
//Call Query Method in the Query Class to return all students in the colletion
case 2: System.out.println("What graduation year would you like to search for? \n");
int yearsearch=preference.nextInt();
Query.getYears(yearsearch);
break;
//Call Query Method to return students who are graduating in the specified year
//Pass the "yearsearch" variable to the Query class
case 3:
System.out.println("What string would you like to search for? \n");
String lstsearch=preference.next();
Query.getLast(lstsearch);
break;
case 4:
System.out.println("You have chosen to exit the program. Thank you!");
flag=false;
break;
default:
System.out.println("Please pick a number between 1 and 4") ;
break;
//Call Query Method in the Query Class to return students who have the string in their last name
//Also I need to pass the "lstsearch" variable to the Query class to search through last names
}
}
}
public List<StudentRecord> studentRecords;
public static void main(String[] args)
throws Exception
{
Scanner input = new Scanner(new File("students.txt"));
//This will import the file
input.nextLine();
//This will skip the headers in the file
System.out.println("Processing file now...");
//Let the user know that the file is being processed
int id;
String last;
String first;
int year;
int i=1;
// Declare variables that we will extract from the file
//Now we will being processing the file with a while loop
List<StudentRecord> studentRecords = new ArrayList<StudentRecord>();
while(input.hasNext())
{
id=input.nextInt();
last=input.next();
first=input.next();
year=input.nextInt();
StudentRecord record = new StudentRecord(id, last, first, year);
studentRecords.add(record);
System.out.println(id + " " + last + " " + first + " " + year + "\n");
}
System.out.println(" You have successfully read and printed from the file!");
for (StudentRecord s : studentRecords)
System.out.println(s.toString());
Query query = new Query(studentRecords);
}
}
+++++++++++++++++++++++++++++++++++
Next Class
import java.util.*;
public class StudentRecord
{
private int id;
private String last;
private String first;
private int year;
public StudentRecord(int id, String last, String first, int year)
{
this.id=id;
this.last=last;
this.first=first;
this.year=year;
}
public String toString()
{
return id + " " + last + " " + first + " " + year;
}
public int getYear()
{
return year;
}
public String getLast()
{
return last;
}
}
+++++++++++++++++++++++++++++++++++
Next Class
import java.util.*;
import java.io.*;
public class Query
{
static List<StudentRecord> records;
public List<StudentRecord> studentRecords;
public Query(List<StudentRecord> records) {
this.records = records;
}
public static void getYears(int yearSearch) {
//I am trying to create a method to get students who are graduating in a specific year.
// I want to call this method in the ProcessRecord SwitchCase Case #2
int count = 0;
System.out.println("ID" +" " +"Last" + " " + "First" + " " + "Year \n");
for(StudentRecord record : records) {
if(record.getYear() == yearSearch) {
System.out.println((record.toString()));
count++;
}
System.out.printf("\n");
}
}
public static void getLast(String lstsearch){
int count =0;
System.out.println("ID" +" " +"Last" + " " + "First" + " " + "Year \n");
int sizes= lstsearch.length();
System.out.println(lstsearch);
for(StudentRecord record : records) {
System.out.println(count);
if(record.getLast() == lstsearch) {
System.out.println((record.toString()));
count++;
}
}
}
public void getAll(){
for (StudentRecord s : studentRecords)
System.out.println(s.toString());
}
}
Once again, I am looking for help searching through the arraylist and if the last name in the array list starts with the string,i.e."g", then I want to print it. Thank you for all of your help!
public static StudentRecord searchRecords(Collection<StudentRecord> records, String lastName)
{
for (StudentRecord record : records)
{
if (lastName.equalsIgnoreCase(record.getLast()))
return record;
}
return null;
}
This will search through your array for the appropriate record. If it exists it returns that record -- otherwise it returns null. If you have such questions in the future you can always consult the appropriate javadoc for some methods you can use to compare objects.
Related
I am working on a text-based adventure game and need some help handling the IndexOutOfBounds exception on the getUserRoomChoice() function. I have an index of 3 on the menu so when the user enters a number > 3, it throws that exception. I tried using a try-catch on the line where it prompts the user to "Select a Number" but it is not catching it.
Here is my main class:
import java.util.Scanner;
public class Game {
private static Room library, throne, study, kitchen;
private static Room currentLocation;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
initialSetupGame();
String reply;
do {
printNextRooms();
int nextRoomIndex = getUserRoomChoice();
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
System.out.print("Would you like to continue? Yes/No: ");
reply = input.nextLine().toLowerCase();
} while ('y' == reply.charAt(0));
goodbye();
}
public static void initialSetupGame() {
// Instantiate room objects of type Room
library = new Room("Library");
throne = new Room("Throne");
study = new Room("Study");
kitchen = new Room("Kitchen");
// Connect the objects to each other
library.addConnectedRoom(throne);
library.addConnectedRoom(study);
library.addConnectedRoom(kitchen);
throne.addConnectedRoom(library);
throne.addConnectedRoom(study);
throne.addConnectedRoom(kitchen);
study.addConnectedRoom(library);
study.addConnectedRoom(throne);
study.addConnectedRoom(kitchen);
kitchen.addConnectedRoom(library);
kitchen.addConnectedRoom(study);
kitchen.addConnectedRoom(throne);
// Welcome message
System.out.println("Welcome to Aether Paradise, "
+ "a game where you can explore"
+ " the the majestic hidden rooms of Aether.");
// Prompt user for a name
Scanner input = new Scanner(System.in);
System.out.print("\nBefore we begin, what is your name? ");
String playerName = input.nextLine();
System.out.print("\n" + playerName +"? Ah yes. The Grand Warden told us"
+ " to expect you. Nice to meet you, " + playerName + "."
+ "\nMy name is King, a member of the Guardian Aethelorian 12"
+ " who protect the sacred rooms of Aether."
+ "\nAs you hold the Warden's signet ring, you have permission"
+ " to enter.\n\nAre you ready to enter? ");
String response = input.nextLine().toLowerCase();
if ('n' == response.charAt(0)) {
System.out.println("Very well then. Goodbye.");
System.exit(0);
}
if ('y' == response.charAt(0)) {
System.out.println("\nA shimmering blue portal appeared! You leap "
+ "inside it and your consciousness slowly fades...");
}
else {
System.out.println("Invalid input. Please try again.");
System.exit(1);
}
// Set the player to start in the library
currentLocation = library;
System.out.print("\nYou have spawned at the library.");
System.out.println(currentLocation.getDescription());
}
public static void printNextRooms() {
// Lists room objects as menu items
System.out.println("Where would you like to go next?");
currentLocation.printListOfNamesOfConnectedRooms();
}
// How to handle the exception when input > index?
public static int getUserRoomChoice() {
Scanner input = new Scanner(System.in);
System.out.print("(Select a number): ");
int choice = input.nextInt();
return choice - 1;
}
public static Room getNextRoom(int index) {
return currentLocation.getConnectedRoom(index);
}
public static void updateRoom(Room newRoom) {
currentLocation = newRoom;
System.out.println(currentLocation.getDescription());
}
public static void goodbye() {
System.out.println("You walk back to the spawn point and jump into"
+ "the portal... \n\nThank you for exploring the hidden rooms "
+ "of Aether Paradise. Until next time.");
}
}
Room Class
import java.util.ArrayList;
public class Room {
// Instance variables
private String name;
private String description;
private ArrayList<Room> connectedRooms;
// Overloaded Constructor
public Room(String roomName) {
this.name = roomName;
this.description = "";
connectedRooms = new ArrayList<>();
}
// Overloaded Constructor
public Room(String roomName, String roomDescription) {
this.name = roomName;
this.description = roomDescription;
connectedRooms = new ArrayList<>();
}
// Get room name
public String getName() {
return name;
}
// Get room description
public String getDescription() {
return description;
}
// Add connected room to the array list
public void addConnectedRoom(Room connectedRoom) {
connectedRooms.add(connectedRoom);
}
// Get the connected room from the linked array
public Room getConnectedRoom(int index) {
if (index > connectedRooms.size()) {
try {
return connectedRooms.get(index);
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
return connectedRooms.get(index);
}
// Get the number of rooms
public int getNumberOfConnectedRooms() {
return connectedRooms.size();
}
// Print the connected rooms to the console
public void printListOfNamesOfConnectedRooms() {
for(int index = 0; index < connectedRooms.size(); index++) {
Room r = connectedRooms.get(index);
String n = r.getName();
System.out.println((index + 1) + ". " + n);
}
}
}
You have to use try-catch in function call of getNextRoom().
Because getNextRoom(nextRoomIndex) is causing the exception. You have to put those two statements in try block.
Change this to
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
this
try{
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
} catch(Exception e){
System.out.println("print something");
}
You must have a closer look to the piece of code, where you try to access the list (or array). That is the part, where the exception is thrown, not when the user enters it. There you have to check, if the given index is larger than the size of your list.
if( index >= list.size()) {
// handle error / print message for user
} else {
// continue normaly
}
In your case, it would probably be in the method getConnectedRoom(int index) in class Room.
Where is your try/catch block for the specific part? anyway, you can use IndexOutOfBound or Custome Exception for it.
1.create a custom Exception Class
class RoomeNotFoundException extends RuntimeException
{
public RoomeNotFoundException(String msg)
{
super(msg);
}
}
add try/catch block for the specific part
public class Game
{
do {
printNextRooms();
int nextRoomIndex = getUserRoomChoice();
if(nextRoomeIndex>3)
{
throw new RoomNotFoundException("No Rooms Available");
}else{
Room nextRoom = getNextRoom(nextRoomIndex);
updateRoom(nextRoom);
System.out.print("Would you like to continue? Yes/No: ");
reply = input.nextLine().toLowerCase();
}
} while ('y' == reply.charAt(0));
}
Or you can use IndexOutOfBoundException instead of RoomNotFoundException
I couldn't really think of how to phrase the question, but I have a fairly simple program that will ask the user to input an element from the periodic table and then will output the symbol, group and atomic mass of that element. Currently it will only accept an input of the name of the element, and I'm trying to make it accept an input of the symbol too, but I don't know how to do that. For example, at the moment if the user inputs "Iron", the program will output correctly, but if they input "Fe" it will not work. I want the input of "Fe" to work as well. I'm very new to Java, so a simple explanation as to how and why would be greatly appreciated.
import java.util.Scanner;
public class PeriodicTable {
public enum Element {
Hydrogen("H", "Nonmetal", "1.008"),
Helium("He", "Noble Gas", "4.003"),
Lithium("Li", "Alkali Metal", "6.941"),
Beryllium("Be", "Alkaline Earth", "9.012"),
Boron("B", "Semimetal", "10.811"),
Carbon("C", "Nonmetal", "12.011"),
//The rest of the periodic table is here, I just removed it for the sake of this post.
private String symbol;
private String group;
private String weight;
private Element(String symbol, String group, String weight) {
this.symbol = symbol;
this.group = group;
this.weight = weight;
}
}
static Element cName = null;
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter the name of an element in the periodic table. ");
do {
String input = reader.nextLine();
try {
cName = Element.valueOf(input.trim().substring(0, 1).toUpperCase() + input.trim().substring(1).toLowerCase());
} catch(IllegalArgumentException e) {
System.out.println("That name is not valid. Please try again. ");
continue;
}
System.out.println("Element: " + cName + " (" + cName.symbol + ")" + "\nGroup: " + cName.group + "\nAtomic Mass: " + cName.weight);
reader.close();
break;
} while (true);
}
}
The collection Element.values() contains all the values of your enum class.
After the user gives input, loop through this collection and check the symbol property to find the element.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
boolean found = false;
do {
System.out.println("Enter the symbol of an element in the periodic table. ");
String input = reader.nextLine().trim();
for (Element e : Element.values()) {
if (e.symbol.equals(input)) {
found = true;
System.out.println("Element: " + e + " (" + e.symbol + ")" + "\nGroup: " + e.group + "\nAtomic Mass: " + e.weight);
}
}
if (!found)
System.out.println("That symbol is not valid. Please try again. ");
} while (!found);
reader.close();
}
I have created a program in JAVA that has menu Options, 1 to 5. Option 4 being "Add student". Where it asks a 4 questions
Questions:
Please Enter student name:
Please Enter student course:
Please Enter student number:
Please Enter student gender:
After user has given these details, It will save into an array and ends the program. I am quite lost on how to save these details into an array.
This is my program where i tried to find a solution myself, But im relatively new to arrays and method myself.
public static void newstudent (String[] name,String[] course,int[] number,String[] gender)
{
}
public static void selection (int option) // Menu
{
switch (option)
{
case 1:
System.out.println("Display Student option");
break;
case 2:
System.out.println("Search Student");
break;
case 3:
System.out.println("Delete Student");
break;
case 4:
//code for adding new student
break;
case 5:
System.out.println("Exited");
break;
default:JOptionPane.showMessageDialog(null, "Invalid option! Please enter in the range from 1 to 5.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
//Start of Menu loop Statement
int option1 ;
do{
String option = JOptionPane.showInputDialog(null,"Enter your option:\n"+"\n"+"1. Display Students\n"+"2. Search Students\n" + "3. Delete Students\n"+"4. Add Students\n"+"5. Exit ","DMIT Students",JOptionPane.QUESTION_MESSAGE);
option1 = Integer.parseInt(option);
selection(option1);
}while(option1 <1 || option1 > 5);
// End of Menu Loop statement
}
}
i tried doing a for loop to add +1 to these array everytime a user inputs all these details but the for loop will be stuck in a infinite loop. Is there any suggestions that i can get? or easier solutions?
You shouldn't use arrays (the way you are using here) in the first place because you don't want to store the details of single student in four different places i.e. arrays. You can define a class Student with all the details you need and then it will be simple to add the details using class instances. Something like -
public class Student
{
private String m_name;
private int m_age;
private String m_course;
private String m_year;
private String m_section;
public Student( String name, int age, String course, String year, String section )
{
m_name = name;
m_age = age;
m_course = course;
m_year = year;
m_section = section;
}
public String getName()
{
return m_name;
}
public int getAge()
{
return m_age;
}
public String getCourse()
{
return m_course;
}
public String getYear()
{
return m_year;
}
public String getSection()
{
return m_section;
}
public String toString()
{
return "name: " + m_name + ", age: " + m_age +
", course: " + m_course + ", year: " + m_year +
", section: " + m_section;
}
public static void main(String[] args)
{
ArrayList<Student> students = new ArrayList<Student>();
Scanner input = new Scanner(System.in);
int menuChoice = 4;
do {
System.out.println("\t\t\tStudent Record Menu");
System.out.println("\t\t1. Add Student\t2. View Students\t3. Search Student\t4. Exit");
try {
System.out.println("Enter a choice: ");
menuChoice = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
continue;
}
if (menuChoice==1)
{
System.out.println("Full name:");
String name = input.nextLine();
int age = -1;
do {
try {
System.out.println("Age:");
age = Integer.parseInt(input.nextLine());
} catch (NumberFormatException e) {
System.out.println("Enter a number!");
continue;
}
} while (age <= 0);
System.out.println("Course:");
String course = input.nextLine();
System.out.println("Year:");
String year = input.nextLine();
System.out.println("Section:");
String section = input.nextLine();
Student student = new Student(name, age, course, year, section);
students.add(student);
} else if (menuChoice==2) {
System.out.println("Students:");
for (Student student : students)
{
System.out.println(student);
}
}
} while (menuChoice<4);
}
}
The above code snippet is referred from here.
Firstly here is my code.
postit.java file
package postit;
import java.util.Scanner;
class Postit {
public static Scanner menu = new Scanner(System.in);
public static void main(String[] args) {
int MenuOption = 0;
NewStorage G = new NewStorage(); // Case 1 Object
while(MenuOption != 3){
System.out.println(
"\n--------Note System-------\n" +
"----------------------------\n" +
"1. Create a Note \n" +
"2. View Notes \n" +
"3. Close Program\n" +
"----------------------------\n");
MenuOption = menu.nextInt();
menu.nextLine();
switch (MenuOption) {
case 1:
G.printinfo();
G.Notestore();
break;
case 2:
G.viewNotes();
G.printNotes();
break;
case 3:
System.out.println("Program is closing");
System.exit(0);
break;
default:
System.out.println("Invalid choice.");
break;
}
}
}
}
NewStorage.java file
package postit;
import java.util.Scanner;
import java.util.ArrayList;
class NewStorage {
ArrayList<Note> NoteArray = new ArrayList<Note>(20);
public void printinfo() {
System.out.println("--- Fill note here ---");
}
public void Notestore() {
System.out.println("Enter the note ID you wish to attach the note with\n\n");
String inputIDnote = Postit.menu.nextLine();
System.out.println("Enter your note\n\n");
String noteDescription = Postit.menu.nextLine();
NoteArray.add(new Note(inputIDnote, noteDescription));
}
public void viewNotes() {
System.out.println("Please enter the number of the note you wish to view.");
int count = 0;
for (int i = 0 ; i < NoteArray.size(); i++) {
System.out.println((count++) + ": " + NoteArray.get(i).inputIDnote);
}
}
public void printNotes(){
int count = Postit.menu.nextInt();
Postit.menu.nextLine();
System.out.println(count + " " + NoteArray.get(count));
}
}
note.java file
package postit;
class Note {
String inputIDnote;
String noteDescription;
public Note(String inputIDnote, String noteDescription) {
this.inputIDnote = inputIDnote;
this.noteDescription = noteDescription;
}
#Override
public String toString() {
return "ID: " + inputIDnote + " \n\nDescription: " + noteDescription;
}
}
So forgive me as I am learning how to write Java so this is one of my first programs, so if you think its badly written then you know why.
As you can see the program can ask the user if they would like to create a note which takes an ID and note itself. Then the user can view the notes created by choosing the number next to the listed note ID's. So when I close the program obviously the ArrayList is wiped. Is there a way to save the notes within the array list even after the program has closed? As I would like to implement an edit feature later so it would be a useful thing to have.
I've implemented a boolean to a kennel system I'm developing in Java and I'm getting an InputMismatchError when loading the data from the file.
I've read through a few times and tried to work it out but the solutions I'm trying aren't working. So far I've:
restructured the read in method (initialise) to read the data in properly and in the correct order, then assign it the newPet (local variable) in the correct order.
I then read through the .txt file (below) and made sure everything corresponded the the correct data, strings are being read as strings, ints as ints etc and that hasn't helped.
Can anybody spot the problem that's through the InputMismatch here?
Here is the error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextBoolean(Unknown Source)
at KennelDemo.initialise(KennelDemo.java:79)
at KennelDemo.main(KennelDemo.java:337)
with line 79 and 337 being:
boolean mutualBoolean = infile.nextBoolean(); //and
demo.initialise();
Main class (apologises for the length)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class KennelDemo {
private String filename; // holds the name of the file
private Kennel kennel; // holds the kennel
private Scanner scan; // so we can read from keyboard
private String tempFileName;
private String dogsFile = "dogs.txt";
private String catsFile = "cats.txt";
/*
* Notice how we can make this private, since we only call from main which
* is in this class. We don't want this class to be used by any other class.
*/
private KennelDemo() {
scan = new Scanner(System.in);
boolean fileCorrect = false;
do {
System.out.print("Which animal are you looking to check into the kennel?: " + "\n");
System.out.println("Dog");
System.out.println("Cat");
tempFileName = scan.next();
if(tempFileName.toLowerCase().equals("dog") || tempFileName.toLowerCase().equals("cat")) {
filename = tempFileName.toLowerCase().equals("dog") ? dogsFile : catsFile;
fileCorrect = true;
}
else {
System.out.println("That is not a valid filename, please enter either 'Dog' or 'cat' in lowercase.");
}
}
while(!fileCorrect);
}
/*
* initialise() method runs from the main and reads from a file
*/
private void initialise() {
kennel = new Kennel();
System.out.println("Using file " + filename);
// Using try-with-resource (see my slides from session 15)
try(FileReader fr = new FileReader(filename);
BufferedReader br = new BufferedReader(fr);
Scanner infile = new Scanner(br)){
String kennelName = infile.nextLine();
int kennelSize = infile.nextInt();
infile.nextLine();
kennel.setCapacity(kennelSize);
int numPets = infile.nextInt();
infile.nextLine();
kennel.setName(kennelName);
for(int i=0; i < numPets; i++){
String PetName = infile.nextLine();
int numOwners = infile.nextInt();
infile.nextLine();
ArrayList<Owner> owners = new ArrayList<>();
for(int oCount=0; oCount < numOwners; oCount++){
String name = infile.nextLine();
String phone = infile.nextLine();
Owner owner = new Owner(name, phone);
owners.add(owner);
}
boolean mutualBoolean = infile.nextBoolean();
infile.nextLine();
String favFood = infile.nextLine();
infile.nextLine();
int feedsPerDay = infile.nextInt();
Pet Pet = new Pet(PetName, owners, mutualBoolean, favFood, feedsPerDay);
kennel.addPet(Pet);
}
} catch (FileNotFoundException e) {
System.err.println("The file: " + " does not exist. Assuming first use and an empty file." +
" If this is not the first use then have you accidentally deleted the file?");
} catch (IOException e) {
System.err.println("An unexpected error occurred when trying to open the file " + filename);
System.err.println(e.getMessage());
}
}
/*
* runMenu() method runs from the main and allows entry of data etc
*/
private void runMenu() {
String response;
do {
printMenu();
System.out.println("What would you like to do:");
scan = new Scanner(System.in);
response = scan.nextLine().toUpperCase();
switch (response) {
case "1":
admitPet();
break;
case "2":
changeKennelName();
break;
case "3":
printPetsWithBones();
break;
case "4":
searchForPet();
break;
case "5":
removePet();
break;
case "6":
setKennelCapacity();
break;
case "7":
printAll();
break;
case "Q":
break;
default:
System.out.println("Try again");
}
} while (!(response.equals("Q")));
}
private void setKennelCapacity() {
// set the boolean to check if the user REALLY wants to change the kennel size. We can never be too careful.
// boolean doContinue = false;
// Turns out the boolean does nothing, go figure.
// Still the error check works perfectly, now just a case of losing the temporary data if the program isn't closed through the menu.
// Kennel currently doesn't save until you use "q" at the menu to save the information. Possible solutions?
// Hello? Is this thing on?
int currentKennelCapacity = kennel.getCapacity();
System.out.println("The current kennel holds " + currentKennelCapacity + ", are you sure you want to change the current kennel size?");
String userWantsToContinue;
userWantsToContinue = scan.nextLine().toUpperCase();
if(userWantsToContinue.equals("Y")){
// doContinue = true;
System.out.print("Please enter the new size of the kennel you'd like: ");
int max = scan.nextInt();
scan.nextLine();
kennel.setCapacity(max);
System.out.println("The new kennel size is " + max + ", we'll now return you to the main menu. Please make sure the quit the program at the end of your session to save any changes. \n");
}
else System.out.println("No problem, we'll return you back to the main menu. \n");
//Duplicate code that caused an error when running through the conditions above, saved in case of future reference.
/* System.out.print("Enter max number of Pets: ");
int max = scan.nextInt();
scan.nextLine();
kennel.setCapacity(max);
*/
}
private void printPetsWithBones() {
Pet[] PetsWithBones = kennel.obtainDogsWhoLikeBones();
System.out.println("Pets with bones: ");
for (Pet d: PetsWithBones){
System.out.println("Pet name: " + d.getName());
}
}
/*
* printAll() method runs from the main and prints status
*/
private void printAll() {
Pet[] allPets = kennel.displayAllPets();
for (Pet p: allPets){
System.out.println("Animal name: " + p.getName());
System.out.println("Original owner(s): " + p.getOriginalOwners());
if(filename.equals(dogsFile)){
System.out.println("Do they like bones? " + Dog.getLikesBones());
}
else if(filename.equals(catsFile)){
System.out.println("Can they share a run? " + Cat.getShareRun());
}
System.out.println("Favourite food: " + p.getFavouriteFood());
System.out.println("Feeds per day: " + p.getFeedsPerDay());
System.out.println("====================================");
}
}
/*
* save() method runs from the main and writes back to file
*/
private void save() {
try(FileWriter fw = new FileWriter(filename);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outfile = new PrintWriter(bw);){
outfile.println(kennel.getName());
outfile.println(kennel.getCapacity());
outfile.println(kennel.getNumOfPets());
Pet[] Pets = kennel.obtainAllPets();
for (Pet d: Pets){
outfile.println(d.getName());
Owner[] owners = d.getOriginalOwners();
outfile.println(owners.length);
for(Owner o: owners){
outfile.println(o.getName());
outfile.println(o.getPhone());
}
// TODO outfile.println(d.getLikesBones());
outfile.println(d.getFeedsPerDay());
outfile.println(d.getFavouriteFood());
}
} catch (IOException e) {
System.err.println("Problem when trying to write to file: " + filename);
}
}
private void removePet() {
System.out.println("which Pet do you want to remove");
String Pettoberemoved;
Pettoberemoved = scan.nextLine();
kennel.removePet(Pettoberemoved);
}
private void searchForPet() {
String allNames = kennel.getName();
System.out.println("Current pet in the kennel: " + allNames + "\n");
System.out.println("Which pet would you like to get the details for?");
String name = scan.nextLine();
Pet Pet = kennel.search(name);
if (Pet != null){
System.out.println(Pet.toString());
} else {
System.out.println("Could not find Pet: " + name);
}
}
private void changeKennelName() {
String name = scan.nextLine();
kennel.setName(name);
}
private void admitPet() {
boolean mutualBoolean = false;
if(filename.equals(dogsFile)){
System.out.println("enter on separate lines: name, owner-name, owner-phone, do they like bones?, favourite food, number of times fed");
}
else if(filename.equals(catsFile)){
System.out.println("enter on separate lines: name, owner-name, owner-phone, can they share a run?, favourite food, number of times fed");
}
String name = scan.nextLine();
ArrayList<Owner> owners = getOwners();
if(filename.equals(dogsFile)){
System.out.println("Does he like bones? (Y/N)");
}
else if(filename.equalsIgnoreCase(catsFile)){
System.out.println("Can the cat share a run? (Y/N)");
}
String booleanCheck;
booleanCheck = scan.nextLine().toUpperCase();
if (booleanCheck.equals("Y")) {
mutualBoolean = true;
}
System.out.println("What is his/her favourite food?");
String fav;
fav = scan.nextLine();
System.out.println("How many times is he/she fed a day? (as a number)");
int numTimes;
numTimes = scan.nextInt(); // This can be improved (InputMismatchException?)
numTimes = scan.nextInt();
Pet newPet = new Pet(name, owners, mutualBoolean, fav, numTimes);
kennel.addPet(newPet);
System.out.println("Pet " + newPet.getName() + " saved.");
// Save when you add new Pet in case the program isn't closed via the correct menu.
// Everything will still save when case "q" is used though.
save();
}
private ArrayList<Owner> getOwners() {
ArrayList<Owner> owners = new ArrayList<Owner>();
String answer;
do {
System.out
.println("Enter on separate lines: owner-name owner-phone");
String ownName = scan.nextLine();
String ownPhone = scan.nextLine();
Owner own = new Owner(ownName, ownPhone);
owners.add(own);
System.out.println("Another owner (Y/N)?");
answer = scan.nextLine().toUpperCase();
} while (!answer.equals("N"));
return owners;
}
private void printMenu() {
if(filename.equals(catsFile)) {
System.out.println("1 - add a new cat ");
System.out.println("2 - set up Kennel name");
System.out.println("4 - search for a cat");
System.out.println("5 - remove a cat");
System.out.println("6 - set kennel capacity");
System.out.println("7 - print all cats");
System.out.println("q - Quit");
}
else if(filename.equals(dogsFile)) {
System.out.println("1 - add a new dog ");
System.out.println("2 - set up Kennel name");
System.out.println("3 - print all dogs who like bones");
System.out.println("4 - search for a dog");
System.out.println("5 - remove a dog");
System.out.println("6 - set kennel capacity");
System.out.println("7 - print all dogs");
System.out.println("q - Quit");
}
}
// /////////////////////////////////////////////////
public static void main(String args[]) {
System.out.println("**********HELLO***********");
KennelDemo demo = new KennelDemo();
demo.initialise();
demo.runMenu();
demo.printAll();
demo.save();
System.out.println("***********GOODBYE**********");
}
}
and here is the .txt file being read from:
DogsRUs // kennel name
20 // capacity
3 // number of pets
Rover //pet name
2 // number of owners
Chris Loftus // first owner
1234 // phone number
Pete Hoskins // second owner
2222 // phone number
1 // boolean for mutualBoolean
biscuits // favourite food
// NOTE: for some reason favFood wasn't being added but it wasn't causing an error at all, it's the boolean that's throwing the input error. Structure above repeats for the data below.
Dinky
1
James Bond
007007
1
Gold fingers
catTest
1
Billy
456789
1
Curry
Clearly the problem is the boolean being read in but I really can't see the solution to it at all unfortunately. When mutualBoolean was likeBones (originally the program was only being used to check dogs in rather than dogs and cats) it was working fine.
Here is the code I've used to inherit for the mutualBoolean that's being used
import java.util.ArrayList;
public class Pet {
protected ArrayList<Owner> originalOwners;
protected boolean mutualBoolean;
protected String petName;
protected String favFood;
protected int foodPerDay;
public Pet(String name, ArrayList<Owner> owners, boolean mutualBoolean, String food, int mealsPerDay) {
petName = name;
this.favFood = food;
this.foodPerDay = mealsPerDay;
originalOwners = new ArrayList<Owner>();
for(Owner o: owners){
Owner copy = new Owner(o.getName(), o.getPhone());
originalOwners.add(copy);
}
this.mutualBoolean = mutualBoolean;
}
public String getName() {
return petName;
}
public void setName(String newName) {
petName = newName;
}
/*protected boolean mutualBoolean() {
return mutualBoolean;
}*/
/**
* Returns a copy of the original owners
* #return A copy of the original owners as an array
*/
public Owner[] getOriginalOwners(){
Owner[] result = new Owner[originalOwners.size()];
result = originalOwners.toArray(result);
return result;
}
/**
* How many times a day to feed the dog
* #param feeds The number of feeds per day
*/
public void setFeedsPerDay(int feeds){
foodPerDay = feeds;
}
/**
* The number of feeds per day the dog is fed
* #return The number of feeds per day
*/
public int getFeedsPerDay(){
return foodPerDay;
}
/**
* What's his favourite food?
* #param food The food he likes
*/
public void setFavouriteFood(String food){
favFood = food;
}
/**
* The food the dog likes to eat
* #return The food
*/
public String getFavouriteFood(){
return favFood;
}
/**
* Note that this only compares equality based on a
* dog's name.
* #param The other dog to compare against.
*/
#Override
public boolean equals(Object obj) { // Generated by Eclipse to be more robust
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Dog other = (Dog) obj;
if (petName == null) {
if (other.petName != null)
return false;
} else if (!petName.equals(other.petName))
return false;
return true;
}
/**
* A basic implementation to just return all the data in string form
*/
public String toString() {
return "Dog name:" + petName + "Original Owner:" + originalOwners + "Favfood:" + favFood
+ "FoodPerDay:" + foodPerDay;
}
}
and the Dog class
import java.util.ArrayList;
public class Dog extends Pet {
public static boolean likesBones;
public Dog(String name, ArrayList<Owner> owners, String food, int mealsPerDay, boolean likeBones) {
super(name, owners, likeBones, food, mealsPerDay);
Dog.likesBones = likeBones;
}
/**
* Does the dog like bones?
* #return true if he does
*/
public static boolean getLikesBones() {
return likesBones;
}
}