While Loop in program not working as expected and gets stuck - java

I am a beginner and would appreciate some advice. I am writing a program where an airport worker and input plane information and then an airport user can print this information out. The program should keep asking the user which option should be selected until the user types 'x' to exit the program.
Look at the while loop under the startAirplanePanel() method.
Here is my UserInterface class:
import java.util.HashMap;
import java.util.Scanner;
import java.util.ArrayList;
public class UserInterface {
private Flights fly;
private Scanner reader = new Scanner(System.in);
public UserInterface(){
this.fly = new Flights();
this.reader = reader;
}
public void startAirplanePanel(){
System.out.println("Airport panel");
System.out.println("---------------");
System.out.println();
System.out.println();
while(true){
System.out.println("Choose operation: ");
System.out.println("[1] Add airplane");
System.out.println("[2] Add flight");
System.out.println("[x] Exit");
String input = reader.nextLine();
if(input.equals("x")){
break;
}
if(Integer.parseInt(input) == 1){
addPlane();
} if(Integer.parseInt(input) == 2){
addFlight();
}
}
System.out.println("Flight service ");
System.out.println("--------------");
System.out.println();
System.out.println();
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("[x] Print Quit");
if(reader.equals("x")){
break;
}
if(Integer.parseInt(reader.nextLine()) == 1){
printPlane();
}
if(Integer.parseInt(reader.nextLine()) == 2){
printFlight();
}
if(Integer.parseInt(reader.nextLine()) == 3){
printPlaneInfo();
}
}
}
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());
fly.planeMap(id,capacity);
}
public void addFlight(){
System.out.println("Give plane ID: ");
String id = reader.nextLine();
System.out.println("Give departure airport code: ");
String departure = reader.nextLine();
System.out.println("Give destination airport code: ");
String destination = reader.nextLine();
fly.flightMap(id,departure,destination);
}
public void printPlane(){
for(int i = 0; i < fly.planeList().size(); i++){
System.out.println(fly.planeList().get(i));
}
}
public void printFlight(){
for(int i = 0; i < fly.flightList().size(); i++){
System.out.println(fly.flightList().get(i));
}
}
public void printPlaneInfo(){
System.out.print("Give plane ID: ");
String id = reader.nextLine();
System.out.println(id + " (" + fly.planeInfo(id) + ")");
}
}
Here is the code for the Flights class, which contains the methods:
import java.util.HashMap;
import java.util.ArrayList;
public class Flights {
public HashMap<String,Integer> plane = new HashMap<String,Integer>();
public HashMap<String,String> flight = new HashMap<String,String>();
public Flights(){
this.plane = plane;
this.flight = flight;
}
public void planeMap(String id, Integer capacity){
plane.put(id, capacity);
}
public void flightMap(String id, String departure, String destination){
String flight1 = departure + "-" + destination;
flight.put(id, flight1);
}
public ArrayList planeList(){
ArrayList<String> keylist = new ArrayList<String>(plane.keySet());
ArrayList<Integer> valuelist = new ArrayList<Integer>(plane.values());
ArrayList<String> newlist = new ArrayList<String>();
for(int i = 0 ; i < keylist.size() ; i++){
newlist.add(keylist.get(i) + " (" + valuelist.get(i) + "ppl)");
}
return newlist;
}
public ArrayList flightList(){
ArrayList<String> keylist = new ArrayList<String>(flight.keySet());
ArrayList<String> valuelist = new ArrayList<String>(flight.values());
ArrayList<String> newlist = new ArrayList<String>();
for(int i = 0; i < keylist.size(); i++){
newlist.add(keylist.get(i) + " (" + plane.containsKey(keylist.get(i)) + "ppl) " + "(" + valuelist.get(i) + ")");
}
return newlist;
}
public int planeInfo(String id){
if(plane.containsKey(id)){
return plane.get(id);
}
return 0;
}
}
And here is the output:
Airport panel
---------------
Choose operation:
[1] Add airplane
[2] Add flight
[x] Exit
1
Give plane ID:
GA-HAS
Give plane capacity:
33
Choose operation:
[1] Add airplane
[2] Add flight
[x] Exit
x
Flight service
--------------
Choose operation:
[1] Print planes
[2] Print flights
[3] Print plane info
[x] Print Quit
1
GA-HAS (33ppl)
The 2nd While loop should keep asking the user to choose an operation, for example, after typing in 1 and the system prints "GA-HAS (33ppl)", it should ask the user again for "Choose operation: [1] print planes ... [3] Print Quit]. But the while loop just stops there and I can't find the reason why.
Please advise. Thank you!

Your while loop hasn't stopped, it's waiting for input.
You call nextLine in each of your if conditions which means the program is waiting for more input. It won't continue until it gets it.
You got it right with your first while loop. Accept one input at the top of the loop, and then compare it as necessary.

Related

Updating specific part of Arraylist string?

I am making a program where the person inputs multiple values and the Arraylist stores it as a single string with option 1. Option two allows you to change a specific part of that string from "Complete" to "Incomplete" and vice-versa but only if the status part of the String is one of the two. I am getting the warning "Result of 'String.replace()' is ignored" and the part of the string isn't updating. Any help would be appreciated!
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Array listObj = new Array();
Scanner userinput = new Scanner(System.in);
int arraysize = (listObj.list.size());
int power = 1;
while (power < 2) {
System.out.println("To-Do List / What would you like to do?");
System.out.println("1 = Add Task / 2 = Mark Task as Done / 3 = Remove Task / 4 = Edit Task / 5 = Display Tasks / 6 = Exit");
int selection = userinput.nextInt();
if (selection == 1) {
for (int i = 0; i <= arraysize; i++) {
String title;
String date;
String status;
String description;
String id;
System.out.print("Enter Title: ");
title = userinput.next();
System.out.print("Enter Due Date: ");
date = userinput.next();
System.out.print("Enter Status (Complete or Incomplete): ");
status = userinput.next();
System.out.print("Enter Description: ");
description = userinput.next();
listObj.list.add(title + " " + date + " " + status + " " + description);
System.out.println();
listObj.list.forEach(System.out::println);
System.out.println();
}
}
if (selection == 2) {
int idinput;
System.out.println("Enter Project ID to Toggle Complete/Incomplete: ");
idinput = (userinput.nextInt()-1);
System.out.println();
System.out.println(listObj.list.get(idinput));
System.out.println();
System.out.println("What is the status of this assignment?: ");
String toggleselect = userinput.next();
if (toggleselect.equals("Incomplete")) {
listObj.list.get(idinput).replace("Incomplete", "Complete");
} else if (toggleselect.equals("Complete")) {
listObj.list.get(idinput).replace("Complete", "Incomplete");
} else {
System.out.println("Status is not Complete/Incomplete");
}
System.out.println();
listObj.list.forEach(System.out::println);
System.out.println();
}
}
}
}
import java.util.ArrayList;
public class Array {
ArrayList<String> list = new ArrayList<String>();
public ArrayList<String> getList() {
return list;
}
}`your text`
public String replace(char searchChar, char newChar)
demands a String to output to, as you can see by the return type. In this case use
public E set(int index, E element)
from the ArrayList library,
with E return type being your ArrayList,
and E element being your call
listObj.list.get(idinput).replace("Complete", "Incomplete");
So,
listObj.list.get(idinput).replace("Complete", "Incomplete");
becomes
listObj.list.set(idinput, listObj.list.get(idinput).replace("Complete", "Incomplete"));
Also, why are you creating a class called Array that just encapsulates an ArrayList in it?

Printing out elements at certain indexes in vectors in Java

This is probably very basic stuff, but I am not too sure how I should ask questions because I am very new to this, so here goes.
I am practicing vectors and what we can do to them. I have prompted the user for the elements of the vectors (per my directions) among other things successfully. For my next step, I have to "print out the element at index i in each of the two vectors." I was given the methods which I am supposed to use, but the explanations I saw of them were very unclear. Here they are:
Object get (int which)
Object remove (int which)
set (int index, object element)
How would I get the system output to be the element at the index i?
package vectorusage;
import java.util.*;
public class VectorUsage {
public static void main(String[] args) {
Vector a = new Vector ();
Vector b = new Vector ();
System.out.println (a);
System.out.println (b);
Scanner input = new Scanner(System.in);
String first;
System.out.print("Please enter 4 strings.");
first = input.next();
a.add (first);
String second;
second = input.next();
a.add (second);
String third;
third = input.next();
a.add (third);
String fourth;
fourth = input.next();
a.add (fourth);
String fifth;
System.out.print("Please enter 4 more strings.");
fifth = input.next();
b.add (fifth);
String sixth;
sixth = input.next();
b.add (sixth);
String seventh;
seventh = input.next();
b.add (seventh);
String eighth;
eighth = input.next();
b.add (eighth);
System.out.println("Vector a is size " + (a.size()) + " and contains: " + (a));
System.out.println("Vector b is size " + (b.size()) + " and contains: " + (b));
int i;
System.out.println("Please enter an integer.");
i = input.nextInt();
System.out.println("Element at index " + i + " in Vector a is: " + ;
Avoid using vectors, they are deprishiated. Use ArrayList instead.
Using a for loop you can simplify your code like below,
(Please note, this code does not validate user input or do error handling)
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
System.out.println("Please enter 8 strings.");
for(int i = 1; i <= 8; i++) {
System.out.print("Please enter strings #" + i + ": ");
numbers.add(input.nextInt());
}
for(int j = 0; j < numbers.size(); j++) {
System.out.println("Number at index " + j + " is " + numbers.get(j));
}
}
}
I usually use a mix of while and for loop. The while loop is used to add the user input into the vector. The for loop prints out the elements of the vector using index i. I've set it to print all the elements of the vector but you can modify it by using if conditions. Here's my code, hope it helps!
import java.util.*;
import java.io.*;
public class VectorUsage {
public static void main(String[]args) {
Scanner input=new Scanner(System.in);
Vector a=new Vector();
int count =0;
while(count<4)
{
System.out.print("Enter a string: ");
a.addElement(input.nextLine());
count++;
}
for(int i=0;i<a.size();i++)
{
System.out.println(a.elementAt(i));
}
Vector b=new Vector();
int count1=0;
while(count1<4)
{
System.out.print("Enter a string: ");
b.addElement(input.nextLine());
count1++;
}
for(int i=0;i<b.size();i++)
{
System.out.println(b.elementAt(i));
}
}
}

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;
}
}

Any other codes for this type of output

Is there any other coding or code format for this kind of output? I would like to ask for your help again. Thank you in advance! This is about array. I tried this using vector but I don't really get the idea. Please really need help.
import java.io.*;
import java.util.ArrayList;
public class DataArrays
{
public static DataInputStream a = new DataInputStream(System.in);
public static void main(String args[])throws Exception
{
ArrayList<Integer> prodNum = new ArrayList<Integer>(100);
ArrayList<String> prodName = new ArrayList<String>(100);
ArrayList<Integer> prodPrice = new ArrayList<Integer>(100);
ArrayList<Integer> prodPay = new ArrayList<Integer>(100);
for(int x=1;x<=100;x++)
{
System.out.println("1 - Maintenance");
System.out.println("2 - Transaction");
System.out.println("");
System.out.print("Enter code: ");
int code = Integer.parseInt(a.readLine());
System.out.println("");
int y = 1;
if(code==1)
{
System.out.print("") ;
System.out.println("Product number: "+ x);
prodNum.add(x); //this brings 1st input to array element #0 which is not needed
prodNum.add(x);
System.out.print("Product name: ");
String prodname = a.readLine();
prodName.add(prodname); //this brings 1st input to array element #0 which is not needed
prodName.add(prodname);
System.out.print("Price: ");
int prodprice = Integer.parseInt(a.readLine());
prodPrice.add(prodprice); //this brings 1st input to array element #0 which is not needed
prodPrice.add(prodprice);
System.out.print("Payment: ");
int prodpay = Integer.parseInt(a.readLine());
prodPay.add(prodpay); //this brings 1st input to array element #0 which is not needed
prodPay.add(prodpay);
System.out.println("");
System.out.println("Start New Transaction:");
System.out.println("");
}
else if(code==2)
{
System.out.println("Display List of Products-Prices");
System.out.print("Enter product number: ");
int i = Integer.parseInt(a.readLine());
i = prodNum.get(i); //this gets the data stored in the arraylist. Assuming it starts with 1 and above
prodNum.set(1, i);
System.out.println("");
System.out.println("Product name: "+ prodName.get(i));
System.out.println("Product price: "+ prodPrice.get(i));
System.out.println("Product payment: "+ prodPay.get(i));
System.out.println("");
System.out.println("Start New Transaction:");
}
else if(code>=3)
{
System.out.println("Invalid");
System.out.println("Restart");
System.out.println("");
}
else if(code==0)
{
System.out.println("Program will end");
break;
}}}}
Looks like you are either adding products or displaying them.
Instead of maintaing 4 different ArrayLists, use a class Product and maintain 1 list.
class Product {
Integer prodNum;
String prodName;
Integer prodPay;
Integer prodPrice;
}
List<Product> listOfProducts = new ArrayList<Product>();
Also the 4 if blocks for 'code' can be replaced by a switch statement.

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