Clearing the scanner to print out empty string - java

I have a tag maker class that needs to print out two tags. one needs to print out the user input, and then I have to clear the scanner buffer and print out an empty tag right afterwards. as of now, I get two tags that print the original user input.
package stupidtag;
import java.util.Scanner;
public class StupidTag {
String first;
String last;
String org;
String s;
Scanner scanMe = new Scanner(System.in);
public void setFirst(String first){
this.first = first;
}
public void setLast(String last){
this.last = last;
}
public void setOrganization(String org){
this.org = org;
}
void tagMaker() {
s = ("———————NAME TAG———————" + "\n" + "Name: " +
last + ", " + first + "\n" + "Organization: " + org +
"\n"+ "---------------------");
if((first.equals(first)) || (last.equals(last)) || (org.equals(org)))
{
System.out.println(s);
}
else{
System.out.println("Invalid input. Please try again.");
scanMe.nextLine(); // -->important
System.out.println();
}
scanMe.reset();
System.out.println(s);
}
}
}
and here's the tester:
import java.util.Scanner;
public class stupidTagTester {
public static void main(String args[]){
Scanner scanMe = new Scanner( System.in );
StupidTag tag = new StupidTag();
System.out.print("This program will print out a name tag");
System.out.println("for each delegate.");
System.out.println("Please enter first name:");
tag.first = scanMe.nextLine();
System.out.println("Please enter last name:");
tag.last = scanMe.next();
System.out.println("Please enter organization or affilation:");
tag.org = scanMe.next();
tag.tagMaker();
}
}

You are only resetting the scanner. Once you do that, add some code that will clear the fields added as well.
Example:
...
scanMe.reset();
first = "";
last = "";
org = "";
System.out.println(s);
}

Related

ArrayLists (Removing and Changing Elements)

Hello everyone I am an amateur in Java and had some specific questions about a program using ArrayLists. The program is made up of several classes, and its purpose is to add, change, remove, and display friends from a Phone Book. I have the add and display methods done, but I'm having trouble with the remove and change method. I saw a similar case on this site, but it did not help me solve my problems. Any help at all would be much appreciated. This is what I have so far:
package bestfriends;
import java.util.Scanner;
import java.util.ArrayList;
public class BFFHelper
{
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
}
public void addABFF()
{
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();
System.out.println("Enter a nick name: ");
String nickName = keyboard.next();
System.out.println("Enter a phone number: ");
String cellPhone = keyboard.next();
BestFriends aBFF = new BestFriends(firstName, lastName, nickName, cellPhone);
myBFFs.add(aBFF);
}
public void changeABFF()
{
System.out.println("I am in changeBFF");
}
public void displayABFF()
{
System.out.println("My Best Friends Phonebook is: ");
System.out.println(myBFFs);
}
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
{
if(firstName.equalsIgnoreCase(myBFFs.get(i).getFirstName()) && lastName.equalsIgnoreCase(myBFFs.get(i).getLastName()))
{
found = true;
}
else
i++;
}
}
}
That was my Helper Class, for which I'm having trouble with the removeABFF method, and still need to create a changeABFF method from scratch. Next is my main class:
package bestfriends;
import java.util.Scanner;
public class BFFPhoneBook
{
public static void main(String args[])
{
int menuOption = 0;
Scanner keyboard = new Scanner(System.in);
BFFHelper myHelper = new BFFHelper();
do
{
System.out.println("1. Add a Friend");
System.out.println("2. Change a Friend");
System.out.println("3. Remove a Friend");
System.out.println("4. Display a Friend");
System.out.println("5. Exit");
System.out.print("Enter your selection: ");
menuOption = keyboard.nextInt();
switch (menuOption)
{
case 1:
myHelper.addABFF();
break;
case 2:
myHelper.changeABFF();
break;
case 3:
myHelper.removeABFF();
break;
case 4:
myHelper.displayABFF();
break;
case 5:
break;
default:
System.out.println("Invalid option. Enter 1 - 5");
}
} while (menuOption != 5);
}
}
This is my last class:
package bestfriends;
public class BestFriends {
private static int friendNumber = 0;
private int friendIdNumber;
String firstName;
private String lastName;
private String nickName;
private String cellPhoneNumber;
public BestFriends (String aFirstName, String aLastName, String aNickName, String aCellPhone)
{
firstName = aFirstName;
lastName = aLastName;
nickName = aNickName;
cellPhoneNumber = aCellPhone;
friendIdNumber = ++friendNumber;
// friendIdNumber = friendNumber++;
}
public boolean equals(Object aFriend)
{
if (aFriend instanceof BestFriends )
{
BestFriends myFriend = (BestFriends) aFriend;
if (lastName.equals(myFriend.lastName) && firstName.equals(myFriend.firstName))
return true;
else
return false;
}
else
return false;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getNickName()
{
return nickName;
}
public String getCellPhone()
{
return cellPhoneNumber;
}
public int getFriendId()
{
return friendIdNumber;
}
public String toString()
{
return friendIdNumber + ". " + firstName + " (" + nickName + ") " + lastName + "\n" + cellPhoneNumber + "\n";
}
}
To explore and manipulate a arraylist an iterator is used
the object lacks the Setters
declare variables
ArrayList<BestFriends> myBFFs;
Scanner keyboard = new Scanner(System.in);
BestFriends best;
public BFFHelper()
{
myBFFs = new ArrayList<BestFriends>();
best= new BestFriends();
}
Delete
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
String name= keyboard.next().toLowerCase();// entry name to be removed
Iterator<BestFriends> nameIter = myBFFs.iterator(); //manipulate ArrayList
while (nameIter.hasNext()){
best = nameIter.next(); // obtained object list
if (best.getNickName().trim().toLowerCase().equals(name)){ // if equals name
nameIter.remove(best); // remove to arraylist
}
}
}
Update
public void changeABFF()
{
System.out.print("Enter a friend's name to be change: ");
String name= keyboard.next().toLowerCase().trim();//entry name to be update
Iterator<BestFriends> nameIter = myBFFs.iterator();
while (nameIter.hasNext()){
best = nameIter.next();
if (best.getNickName().trim().toLowerCase().equals(name)){// if equals name
best.setNickName("NEW DATE");//update data with new data Setters
....
}
}
}
In your remove method you do not accept any input of the values
public void removeABFF()
{
System.out.print("Enter a friend's name to be removed: ");
int i = 0;
boolean found = false;
while (i < myBFFs.size() && !found)
....
As you are using firstNamer and lastName to find the object you needs these values
System.out.println("Enter a first name: ");
String firstName = keyboard.next();
System.out.println("Enter a last name: ");
String lastName = keyboard.next();

display an entire arraylist in java

I'm still pretty new to java. Am trying to make a program that basically adds contacts to an array list. I have figured everything out as far as creating a new object and setting the name/number. As far as I can tell it's adding it to the array, however I'm not sure how I can display the array? I want to add a snippet of code that would display the array list after you add each contact.
Here is my contact class, not sure if I need the PhoneBook method or not for the array....
public class Contact {
String first; //first name
String last; //last name
String phone; //phone number
String PhoneBook; //array list???
public void PhoneBook(String f, String l, String p) {
first = f;
last = l;
phone = p;
}
public void setFirst(String first) {
this.first = first;
}
public void setLast(String last) {
this.last = last;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Contact makeCopy() {
Contact Contact = new Contact();
Contact.first = this.first;
Contact.last = this.last;
Contact.phone = this.phone;
return Contact;
} //end makeCopy
} //end class Computer
Here is my driver class...
import java.util.Scanner;
import java.util.ArrayList;
public class contactDriver {
public static void main(String[] args) {
Contact Contact = new Contact(); //make default Contact
Contact newContact;
String first; //first name
String last; //last name
String phone; //phone number
String input; //answer to create a new contact
boolean add = true; //boolean to add new contact
Scanner scan = new Scanner(System.in);
Contact.setFirst("Default");
Contact.setLast("Default");
Contact.setPhone("Default");
while (add) {
System.out.println("Would you like to create a new contact? (Y/N)");
input = scan.nextLine();
if (input.equals("Y") || input.equals("y")) {
newContact = Contact.makeCopy();
System.out.println("Enter the contact's first name: ");
first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
last = scan.nextLine();
System.out.println("Enter the contact's phone number: ");
phone = scan.nextLine();
ArrayList < Contact > PhoneBook = new ArrayList();
newContact.setFirst(first);
newContact.setLast(last);
newContact.setPhone(phone);
PhoneBook.add(newContact);
} else {
add = false;
System.out.println("Goodbye!");
break;
}
}
} //end main
} //end Class ComputerDriver
If just for printing, override the toString method of your Contact class, which will be like:
#Override
public String toString() {
return first + " " + last + "; phone number: " + phone;
}
Then, in your main method, print all the contacts by doing:
for (Contact c : phoneBook) {
System.out.println(c);
}
Also, you should create the phoneBook, which is an ArrayList outside of your loop.
Your Contact class should be defined as:
public class Contact {
private String first; // first name
private String last; // last name
private String phone; // phone number
public Contact(String f, String l, String p) {
first = f;
last = l;
phone = p;
}
public String getFirst() {
return first;
}
public String getLast() {
return last;
}
public String getPhone() {
return phone;
}
public Contact makeCopy() {
return new Contact(first, last, phone);
}
#Override
public String toString() {
return first + " " + last + "; phone number: " + phone;
}
}
And your main method should be:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<Contact> phoneBook = new ArrayList<>();
while (true) {
System.out.println("Would you like to create a new contact? (Y/N)");
String input = scan.nextLine();
if (input.equalsIgnoreCase("Y")) {
System.out.println("Enter the contact's first name: ");
String first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
String last = scan.nextLine();
System.out.println("Enter the contact's phone number: ");
String phone = scan.nextLine();
Contact contact = new Contact(first, last, phone);
phoneBook.add(contact);
for (Contact c : phoneBook) {
System.out.println(c);
}
} else {
System.out.println("Goodbye!");
break;
}
}
scan.close();
}
The compiler will give warning, most likely because of this:
String PhoneBook;
when you know that you also have
public void PhoneBook(String f, String l, String p)
and even more another PhoneBook
ArrayList < Contact > PhoneBook = new ArrayList();
try to use another variable name and function name to be safe and make sure they are different especially for
String PhoneBook;
public void PhoneBook(String f, String l, String p)
since they are under same class.
In terms of data structure, you have a wrong concept here. first is, this:
ArrayList < Contact > PhoneBook = new ArrayList();
should be outside the while loop so for whole your application, you will not replace your phone book after looping. to print them, later just use
for(int i = 0; i < phoneBook.size(); i++)
your printing
You just override toString() method of your Contact class, and in main() method, directly call your ArrayList's toString().
Here is my example:
package somepackage;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Inner> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Inner in = new Inner("name" + i, "address" + i);
list.add(in);
}
System.out.println(list.toString());
}
private static class Inner {
private String name;
private String address;
Inner(String name, String address) {
this.name = name;
this.address = address;
}
#Override
public String toString() {
return "name:" + name + ", " + "address: " + address + "\n";
}
}
}
Screen outputs:
[name:name0, address: address0
, name:name1, address: address1
, name:name2, address: address2
, name:name3, address: address3
, name:name4, address: address4
, name:name5, address: address5
, name:name6, address: address6
, name:name7, address: address7
, name:name8, address: address8
, name:name9, address: address9
]
Ok, figured it out thanks to your guys help! I changed the if statement so you can now add a new contact, display the phone book, or quit. I also added phone number validation! Here is the updated code if anyone cares!
import java.util.Scanner;
import java.util.ArrayList;
public class contactDriver {
public static void main(String[] args) {
String first; //first name
String last; //last name
String phone = ""; //phone number
String input; //answer to create a new contact
boolean add = true; //boolean to add new contact
boolean phoneValid; //boolean to validate phone number
Scanner scan = new Scanner(System.in);
ArrayList < Contact > PhoneBook = new ArrayList < > ();
while (add) {
phoneValid = false;
System.out.println("Type (N) to add a new contact, (D) to display your phonebook, or (Q) to quit!");
input = scan.nextLine();
if (input.equalsIgnoreCase("N")) {
System.out.println("Enter the contact's first name: ");
first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
last = scan.nextLine();
while (!phoneValid) {
System.out.println("Enter the contact's phone number: XXX-XXX-XXXX");
phone = scan.nextLine();
if (phone.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) {
phoneValid = true;
break;
} else {
System.out.println("Sorry, I didn't catch that!");
}
}
Contact contact = new Contact(first, last, phone);
PhoneBook.add(contact);
} else if (input.equalsIgnoreCase("Q")) {
add = false;
System.out.println("Goodbye!");
break;
} else if (input.equalsIgnoreCase("D")) {
for (Contact c: PhoneBook) {
System.out.println(c);
}
} else {
System.out.println("Sorry, I didn't catch that!");
}
}
} //end main
} //end Class ComputerDriver
It sounds like you need to create some Getters. Most IDE's will do this for you.
For example, in your contact class add this:
public String getFirst(){ return first; }
Then do that for all of the items you want. When you want to print them out, set up a for each loop in your driver class like this:
for(Contact contact : PhoneBook){
System.out.println("Contact details: " + contact.getFirst() + " " + contact.getLast() + ", Phone #: " + contact.getPhoneNumber());
}
Alternatively, you could also create a method in you contacts class that takes the println contents from above and spits it out. For example:
public void printContactDetails(){ System.out.println("...");}
then in your for each loop call: contact.printContactDetails();

Restaurant Menu: how to efficiently implement a nested loop to collect user input and conduct error checking

I have these two methods which I cant quite figure out the best way to go about their algorithm.
I am writing a program that acts like a restaurant menu and collects user order.
The implementation is,
welcome user and present him with the menu
while the user has not entered 'q', send the user input to a method called getGoodOrderLine(String str)
this method will then check the input for the following,
- First, it must check that a number is present before trying to read it; if there is no number, the entry is an error unless it starts with ‘q’ or ‘Q’, which tells the program to quit.
- then, determine which item the user is asking for by looking at just the first letter. So an input “2 Hello” means 2 hamburgers. the assumption is that if there is a digit in the string, the digit appears before the word, for simplicity
- finally, if the first letter is not (H,C,F or D), print an error message and ask that it be re-entered.
My problem is that, I created a while loop that should loop until the user input is valid, but it doesn't seem to be working, here is my code:
import java.util.*;
public class MenuApp
{
//global variables
public static double HAM = 3.75;
public static double CHEESE = 4.10;
public static double FRIES = 2.50;
public static double DRINKS = 1.75;
public static void main(String [] args)
{
//variables
String order;
double total = 0.0;
boolean stopLoop;
//print welcome message && collect order
welcomeCustomer();
order = collectItem();
order = getGoodOrderLine(order);
stopLoop = order.equalsIgnoreCase("q");
while(!stopLoop)//while user hasnt typed q
{
if(order.equalsIgnoreCase("q"))
{
break;
}
order = getGoodOrderLine(order);
//will add the value of user order to total here if order is valid
//leave loop if useer inputs q
}
//ending program
Date today = new Date();
System.out.println("Date: " + today);
System.out.println("Please pay " + total + "\n");
System.out.println("End of processing");
}
public static void welcomeCustomer()
{
System.out.println("Welcome to QuickieBurger!");
System.out.println("Hamburgers \t\t $" + HAM);
System.out.println("cheeseBurgers\t\t $" + CHEESE);
System.out.println("Fries\t\t\t $" + FRIES);
System.out.println("Drinks\t\t\t $" + DRINKS+"\n");
}
public static String collectItem()
{
String userInput = null;
Scanner kbd = new Scanner(System.in);
System.out.println("Please place your order (e.g., 3 ham). Enter Q to quit.");
userInput = kbd.nextLine();
System.out.println(userInput);
return userInput;
}
public static String getGoodOrderLine(String userInput)
{
String result = "";
boolean pass = false;
if(userInput.equalsIgnoreCase("q"))
{
return userInput;//early exit, return q
}
//check if it has at least a digit first
for(char c: userInput.toCharArray())
{
if(Character.isDigit(c))
{pass = true;}
}
//if it doesn't have a digit || string doesnt begin with a digit
if(!Character.isDigit(userInput.charAt(0)))
{
if(!pass)
System.out.println("Your entry "+ userInput + " should specify a quantity");
else
System.out.println("Your entry "+ userInput + " does not begin with a number");
}
else
{
//do the remaining tests here
}
return result;
}
}
I keep getting null pointer and index out of bounds exceptions when testing for Character.isDigit(userInput.charAt(0));
the problem is you are returning empty string so charAt(0) give error since char array has no elements.and if you want to collect items you need to use a collection type like list and u can't use a array since array has fixed length.and to get price of user input product you need to map prices with product names .so u can use map.but i used 2 arrays which act as a map.check this and it's output.
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.Scanner;
public class myMenu {
public static String names[] = {"HAM", "CHEESE", "FRIES", "DRINKS"};
public static double prices[] = {3.75, 4.10, 2.50, 1.75};
public static ArrayList<List<String>> allitems = new ArrayList<>();
static double total = 0.0;
public static void main(String[] args) {
welcomeCustomer();
collectItem();
}
public static void welcomeCustomer() {
System.out.println("Welcome to QuickieBurger!");
for (int i = 0; i < names.length; i++) {
System.out.println(names[i] + "\t\t\t" + prices[i]);
}
}
public static void collectItem() {
String userInput = "";
Scanner kbd = new Scanner(System.in);
System.out.println("Please place your order (e.g., 3 ham). Enter Q to quit.");
userInput = kbd.nextLine();
while (!getGoodOrderLine(userInput)) {
userInput = kbd.nextLine();
}
}
private static boolean getGoodOrderLine(String userInput) {
if (userInput.equalsIgnoreCase("q")) {
transaction();
} else if (!Character.isDigit(userInput.charAt(0))) {
System.out.println("quesntity should be specified. try again");
return false;
} else {
for (int i = 0; i < names.length; i++) {
String items = names[i];
//get the first charactor from userinput
char c = 0;
for(int z=0;z<userInput.length();z++){
c=userInput.charAt(z);
if(Character.isAlphabetic(c)){
break;
}
}
if (Character.toLowerCase(items.charAt(0)) ==Character.toLowerCase(c)) {
String s="";
int x=0;
while(Character.isDigit(userInput.charAt(x))){
s+=userInput.charAt(x);
x++;
}
int quentity=Integer.parseInt(s);
double pri = prices[i];
double sub = quentity * pri;
total += sub;
ArrayList<String> subitem = new ArrayList<>();
subitem.add(items);
subitem.add(String.valueOf(quentity));
subitem.add(String.valueOf(sub));
allitems.add(subitem);
return false;
}
}
System.out.println("this not a valid food item.try again");
}
return false;
}
private static void transaction() {
//ending program
Date today = new Date();
System.out.println("-------------------------------------");
System.out.println("Date: " + today);
for (List<String> menu : allitems) {
System.out.println(menu.get(0)+" "+menu.get(1)+" = "+menu.get(2));
}
System.out.println("Please pay " + total + "\n");
System.out.println("------------------------------------");
System.out.println("End of processing");
}
}
output>>
Welcome to QuickieBurger!
HAM 3.75
CHEESE 4.1
FRIES 2.5
DRINKS 1.75
Please place your order (e.g., 3 ham). Enter Q to quit.
2 Hello
4 CHEESE
q
-------------------------------------
Date: Sun Nov 02 02:59:56 PST 2014
HAM 2 = 7.5
CHEESE 4 = 16.4
Please pay 23.9
------------------------------------
End of processing
public class MenuApp
{
// global variables
public static double HAM = 3.75;
public static double CHEESE = 4.10;
public static double FRIES = 2.50;
public static double DRINKS = 1.75;
// you need to define errors
public static String noInput = "__MENUAPP_ERROR_1";
public static String invalidInput = "__MENUAPP_ERROR_2";
...
public static String getGoodOrderLine(String userInput)
{
String result = "";
boolean pass = false;
boolean startWithDigit = false;
// add this line to verify the input first
if (userInput == null || userInput.equalsIgnoreCase(""))
{
return MenuApp.noInput ;
}
if(userInput.equalsIgnoreCase("q"))
{
return "q"; // early exit, return q
}
//check if it has at least a digit first
for(char c: userInput.toCharArray())
if(Character.isDigit(c))
pass = true;
startWithDigit = Character.isDigit(userInput.charAt(0));
// if it doesn't have a digit || string doesnt begin with a digit
if(!startWithDigit)
{
if(!pass)
System.out.println("Your entry "+ userInput + " should specify a quantity");
else
System.out.println("Your entry "+ userInput + " does not begin with a number");
return MenuApp.invalidInput;
}
else
{
// do the remaining tests here
}
return result;
}
}

Rearranging a string

So my goal is to rearrange a string that is inputted into the program so that it outputs the same info but in a different order. The input order is firstName middleName, lastName, emailAddress and the intended output is lastName, firstName first letter of middleName .
For example the input
John Jack,Brown,JJB#yahoo.com
would output
Brown, John J .
Here's what I have so far
import java.util.Scanner;
public class NameRearranged {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name like D2L shows them: ");
String entireLine = keyboard.nextLine();
String[] fml = entireLine.split(",");
String newName = fml[0].substring(7);
String newLine = fml[1] + "," + newName + ".";
System.out.println(newLine);
}
public String substring(int endIndex) {
return null;
}
}
I can't figure out how to separate the firstName and middleName so I can substring() the first letter of the middleName followed by a .
This meets your required output.
import java.util.Scanner;
public class NameRearranged {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name like D2L shows them: ");
String entireLine = keyboard.nextLine();
String[] fml = entireLine.split(","); //seperate the string by commas
String[] newName = fml[0].split(" "); //seperates the first element into
//a new array by spaces to hold first and middle name
//this will display the last name (fml[1]) then the first element in
//newName array and finally the first char of the second element in
//newName array to get your desired results.
String newLine = fml[1] + ", " + newName[0] + " "+newName[1].charAt(0)+".";
System.out.println(newLine);
}
}
Check this.
public class NameRearranged {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a name like D2L shows them: ");
System.out.println(rearrangeName(keyboard.nextLine()));
}
public static String rearrangeName(String inputName) {
String[] fml = inputName.split(" |,"); // Separate by space and ,
return fml[2] + ", " + fml[0] + " " + fml[1].charAt(0) + ".";
}
}
You need to delimit the string for spaces as well. And don't forget the alternate "|" character. Try the following.
String[] fml = entireLine.split(" |, ");

How to write contents of an array list to a text file?

I have this basic enough Java program that asks the user to input songs to a music library array list. From there the user can shuffle their songs, delete a song, delete all etc. It's nearly finished, I just have one issue I can't resolve. It happens when I try export the array list to a text file. Instead of the content of the array list, my output would look like this, as opposed to the details the user submitted:
"1: MainClass.SongClass#c137bc9
MainClass.SongClass#c137bc9"
I'll post my code below, I'd really appreciate if someone could point me in the right direction!
My Final Project class which serves as my main class:
package MainClass;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FinalProject extends UserInput {
public String nextInt;
public static void main(String[] args) {
// SongLibrary iTunes; //Object stores the file cars.txt
// iTunes = new SongLibrary("MUSIC LIBRARY.txt");
// songData CLO = iTunes.readFileIntoList();
UserInput ui;
ui = new UserInput();
Scanner input = new Scanner(System.in);
int opt;
//Calls Methods Class so methods can be used below
Menu menuFunctions = new Menu();
//Calls FileReaderTest Class so file can be read
SongLibrary Reader = new SongLibrary();
//initial prompt only displayed when program is first ran
System.out.println("Welcome to your music library!");
do {
//Menu Prompts printed to the screen for the user to select from
System.out.println(" ");
System.out.println("Main Menu:");
System.out.println("........ \n");
System.out.println("Press 0 to Exit");
System.out.println("Press 1 to Add a Song");
System.out.println("Press 2 to View All Songs");
System.out.println("Press 3 to Remove a Song");
System.out.println("Press 4 to Shuffle Library");
System.out.println("Press 5 to Play a Random song");
System.out.println("Press 6 to Remove ALL Songs");
System.out.println("Press 7 to Save Library\n");
//Monitors the next Int the user types
opt = input.nextInt();
//"if" statements
if (opt == 0) {
//This corresponds to the condition of the while loop,
//The program will exit and print "Goodbye!" for the user.
System.out.println(" ");
System.out.println("Goodbye!");
} else if (opt == 1) {
//This method allows the user to add a song to the library.
//With the format being Title, Artist, Year.
System.out.println(" ");
menuFunctions.addEntry();
} else if (opt == 2) {
//This method prints the contents of the Array List to the screen
System.out.println("\n");
menuFunctions.viewAll();
} else if (opt == 3) {
//This method allows the user to remove an indiviual song from
//their music library
System.out.println("\n");
menuFunctions.removeOne();
} else if (opt == 4) {
//This method uses the Collections.shuffle method
//to re-arrange the track list
//song to simulate a music player's shuffle effect.
System.out.println("\n");
menuFunctions.shuffleSongs();
} else if (opt == 5) {
//This method will clear all contents of the library.
//It will ask the user to confirm their choice.
System.out.println("\n");
menuFunctions.randomSong();
} else if (opt == 6) {
//This method will clear all contents of the library.
//It will ask the user to confirm their choice.
System.out.println("\n");
menuFunctions.clearLibrary();
}
else if (opt == 7) {
try {
menuFunctions.saveLibrary();
} catch (FileNotFoundException x) {
System.out.println("File not found. " + x);
}
}
else {
//If the user selects an incorrect number, the console will
//tell the user to try again and the main menu will print again
System.out.println("\n");
System.out.println("Incorrect Entry, please try again");
}
} //do-while loop
while (opt > 0);
}
}
My SongClass class which holds the constructor and Get/Set methods
package MainClass;
public class SongClass {
private int songMinutes;
private int songSeconds;
private String songTitle;
private String songArtist;
private String songAlbum;
private int songYear;
public SongClass(int m, int ss, String t, String art, String al, int y){
songMinutes = m;
songSeconds = ss;
songTitle = t;
songArtist = art;
songAlbum = al;
songYear = y;
}
//GET METHODS
public int getMinutes() {
return songMinutes;
}
public int getSeconds() {
return songMinutes;
}
public String getTitle() { //
return songTitle;
}
public String getArtist() {
return songArtist;
}
public String getAlbum() {
return songAlbum;
}
public int getYear() {
return songYear;
}
//SET METHODS
public void setMinutes(int m){
songMinutes = m;
}
public void setDuration(int ss){
songSeconds = ss;
}
public void setTitle(String t){
songTitle = t;
}
public void setArtist(String art){
songArtist = art;
}
public void setAlbum(String al){
songAlbum = al;
}
public void printSong(){
System.out.println(songMinutes+":"+ songSeconds + " - " + songTitle + " - " + songArtist + " - " +songAlbum + " - "+ "("+songYear+")");
}
}
My menu class which holds most of the methods used in the program
package MainClass;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
public class Menu {
public void add(SongClass s) throws NumberFormatException {
try {
songLibrary.add(s);
} catch (NumberFormatException x) {
}
}
Scanner input = new Scanner(System.in);
UserInput ui = new UserInput();
public ArrayList<SongClass> songLibrary;
public Menu() {
songLibrary = new ArrayList<SongClass>();
}
public void removeOne() throws ArrayIndexOutOfBoundsException {
try {
System.out.println("Which song would you like to delete? (1 of " + songLibrary.size() + ")");
viewAll();
//calls the viewAll method to print current library to screen
int remove = input.nextInt();
//creates an int that corresponds to the nextInt typed.
if (remove > songLibrary.size()) {
System.out.println("Invalid ");
//if the user types a number higher than the highest index of the
//array list, they will be shown an error and return to the menu
}
else {
remove --;
SongClass s = songLibrary.get(remove);
System.out.println("Are you sure you would like to delete the following track from your music library? ");
s.printSong();
//confirms user wants to delete the selected track
System.out.print("1: Yes \n2: No" + "\n");
int confirmDelete = input.nextInt();
//Asks the user to input 1 or 2,
if (confirmDelete == 1) {
songLibrary.remove(remove);
//removes the index of the 4 array lists
System.out.println( "Removed.");
viewAll();
} else if (confirmDelete == 2) {
System.out.println("\n" + "Okay, the song won't be removed");
} else {
System.out.println("\n" + "Invalid option.");
}
}
}
catch (ArrayIndexOutOfBoundsException x) {
System.out.println("Please select an valid entry");
}
}
public void clearLibrary() {
System.out.println("Confirm?");
System.out.print("1: Yes \n2: No" + "\n");
int confirmDelete = input.nextInt();
//if the user types one, this triggers the clear method.
if (confirmDelete == 1) {
songLibrary.clear();
System.out.println("\n" + "Your music library has been cleared" + "/n");
}
}
public void shuffleSongs() {
//The shuffle function shifts the location of all the elements of an
//array list. This mimics the shuffle effect of a Music player
//The attributes of the song all get shuffled together because they
//are all linked by the same seed.
long seed = System.nanoTime();
Collections.shuffle(songLibrary, new Random(seed));
System.out.println("Your library is now shuffled" + "\n");
viewAll();
//Shuffles library, then outputs the new library list.
}
public void viewAll() {
if (songLibrary.isEmpty()) {
System.out.println("Your library is currently empty!");
} else {
System.out.println("Your Music Library" + "\n" + "Duration - Artist - Song - Album -(Year) " + "\n");
for (int i = 0; i < songLibrary.size(); i++) {
SongClass s = songLibrary.get(i);
s.printSong();
}
}
System.out.println("\n");
}
public void randomSong() {
int randomSong = (int) (Math.random() * (songLibrary.size() - 1));
//uses Math.random to generate a random double between 0.0 and 1.0
//it then multiplies it by the size of the array list - 1
//The end result is that a random index of the array list is selected
System.out.println("Now Playing:");
//the selected song randomSong is then outputted
//this changes each time the randomSong method is called
SongClass s = songLibrary.get(randomSong);
s.printSong();
}
public void saveLibrary() throws FileNotFoundException {
try (PrintWriter pw1 = new PrintWriter("MUSIC LIBRARY.txt")) {
File inFile = new File("MUSIC LIBRARY.txt");
Scanner in = new Scanner(inFile);
System.out.println("Your music library has been successfully exported!\n");
pw1.println("Your Music Library");
pw1.println(" ");
pw1.println("Duration - Artist - Song - Album (Year) " + "\n");
pw1.println(" ");
for (int i = 0; i < songLibrary.size(); i++) {
System.out.println("The loop ran this many times");
System.out.println(i);
int counter = i + 1;
pw1.println(counter + ": " + songLibrary.get(i));
}
System.out.println("Loop is over, PrintWriter should close.");
pw1.close();
}
}
public void addEntry() throws NumberFormatException {
try {
int minutes = ui.getInt("How many minutes does this song last?");
int seconds = ui.getInt("How many seconds does this song last?");
String title = ui.getString("What is the title of the track?");
String artist = ui.getString("Who performs the track?");
String album = ui.getString("What album is the track from?");
int year = ui.getInt("What year was the track released?");
System.out.println("Please enter a number:");
System.out.println("\n");
SongClass s = new SongClass(minutes, seconds, title, artist, album, year);
songLibrary.add(s);
System.out.println("Thank you!" + " " + title + " " + "was added to your library:");
} catch (NumberFormatException x) {
System.out.println(" ");
System.out.println("Year/Duration can use numbers only, please try again.");
System.out.println(" ");
}
}
}
And my user input class
package MainClass;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class UserInput{
private Scanner keyboard;
public UserInput() {
this.keyboard = new Scanner(System.in);
}
public String getString(String prompt) {
String line;
System.out.print(prompt + ": ");
line = this.keyboard.nextLine();
return line;
}
public int getInt(String prompt) {
String line;
int num;
System.out.print(prompt + ": ");
line = this.keyboard.nextLine();
num = Integer.parseInt(line);
return num;
}
public Date getDate(String prompt) {
String line;
SimpleDateFormat formatter;
Date date;
System.out.print(prompt + " (dd/MM/yyyy): ");
line = this.keyboard.nextLine();
formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
date = formatter.parse(line);
}
catch (ParseException ex) {
date = null;
}
return date;
}
public boolean getBoolean(String prompt) {
String line;
System.out.print(prompt + "? (Y|N)");
line = this.keyboard.nextLine();
return line.equalsIgnoreCase("Y");
}
}
"1: MainClass.SongClass#c137bc9 MainClass.SongClass#c137bc9"
This is what the default implementation of toString outputs.
You need to override toString in your SongClass:
#Override
public String toString(){
return String.format("%d:%d - %s - %s - %s - (%d)",
songMinutes,songSeconds, songTitle, songArtist , songAlbum, songYear);
}
An alternative (which may be better if you don't want to override toString, because that method is used elsewhere) is to loop over all elements of your list and explicitly format the output by calling appropriate getters (or another method similar to your printSong method).

Categories