How to stop on duplicate entry (Java) - java

I have a simple code that asks a user to input items and stores them into an array. I would like to make it so the program stops running when the last entry is the same as the first.
so for example this would stop the program because Cookie it both the first item in the array and the last. But it's also ok to have duplicates with in the array like "Sugar" in this example:
Enter the item: Cookie
Enter the item: Sugar
Enter the item: Milk
Enter the item: Sugar
Enter the item: Salt
Enter the item: Cookie
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
//Decide the number of items
int numOfItems = 20;
//Create a string array to store the names of your items
String arrayOfNames[] = new String[numOfItems];
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter Item " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
}
//Now show your items's name one by one
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Item # " + (i+1) + " : ");
System.out.print(arrayOfNames[i] + "\n");
}
}
}
Thanks for your help

You can do this by adding a simple if-condition with equals() method. you need do add following if-condition.
if(Temp.equals(arrayOfNames[0])) // readed Temp equals to first element.
Try this code:-
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
//Decide the number of items
int numOfItems = 20,maxItems=0; // total items may vary
//Create a string array to store the names of your items
String arrayOfNames[] = new String[numOfItems];
String Temp=""; // for temporary storage
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter Item " + (i+1) + " : ");
Temp= scan.nextLine();
if(Temp.equals(arrayOfNames[0])){
maxItems=i;
break;
}
else{
arrayOfNames[i]=Temp;
}
}
//Now show your items's name one by one
for (int i = 0; i < maxItems; i++) {
System.out.print("Item # " + (i+1) + " : ");
System.out.print(arrayOfNames[i] + "\n");
}
}
}
Output :-
Enter Item 1 : Cookie
Enter Item 2 : Sugar
Enter Item 3 : milk
Enter Item 4 : Sugar
Enter Item 5 : Salt
Enter Item 6 : Cookie
Item # 1 : Cookie
Item # 2 : Sugar
Item # 3 : milk
Item # 4 : Sugar
Item # 5 : Salt

If you don't know the number of items will be entered by the user then this code will be helpful,
import java.util.*;
public class MyClass {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
while(true)
{
System.out.print("Enter name:");
String temp = sc.next();
if(al.isEmpty() != true)
{
if(temp.equals(al.get(0)))
break;
}
al.add(temp);
}
for(int i = 0;i<al.size();i++)
{
System.out.println(al.get(i));
}
}
}

More sophisticated OO Program Example:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Grocery {
List<String> basket; // list of items in the basket
//constructor of Grocery with number of items provided
public Grocery(int numberOfItems) {
basket = new ArrayList<>(numberOfItems); // initialize basket
}
/**
* Add item to basket only if it is not similar to the first item
* return true if succeeded otherwise return false if it's duplicate
* #param item
* #return
*/
public boolean addItem(String item) {
if(basket.size()==0) return basket.add(item);
if(!basket.get(0).equals(item)) {
return basket.add(item);
}
return false;
}
/**
* Remove specific item in the basket
* or all items by name if "all" is true
* #param item
*/
public void removeItem(String item, boolean all) {
if(all) {
for(String i : basket) {
if(i.equals(item)) {
basket.remove(i);
}
}
}else {
basket.remove(item);
}
}
// method to empty the basket
public void emptyBasket() {
basket.clear();
}
/**
* Override toString() to provide your own
* textual representation of the basket
*/
#Override
public String toString() {
String s = "";
for(int i=0; i<basket.size(); i++) {
s += "Item #" + (i+1) + " : " + basket.get(i) + "\n";
}
return s;
}
// TEST
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
//Decide the number of items
int numOfItems=0;
System.out.print("Enter How Many Items: ");
try {
numOfItems = Integer.parseInt(scan.nextLine().trim());
}catch(NumberFormatException e) {
System.out.print("Number of items you entered is invalid!");
System.exit(0);
}
Grocery grocery = new Grocery(numOfItems);
for (int i = 0; i < numOfItems; i++) {
System.out.print("Enter Item " + (i+1) + " : ");
if(!grocery.addItem(scan.nextLine())) {
System.out.println("First Item Duplicate Detected!");
//break;
System.exit(0);
};
}
scan.close();
System.out.println(grocery.toString());
}
}
Test

Sounds to me like you should be able to do a if statement in here to find out if array[0] = array[i]
if (i > 0 && (arrayOfNames[0] == arrayOfNames[i])) {
// do something
}

Simply add a condition that if the current element matches first element, then break out of the for loop.
String first=null;
for (int i = 0; i < arrayOfNames.length; i++) {
System.out.print("Enter Item " + (i+1) + " : ");
arrayOfNames[i] = scan.nextLine();
if (i==0){
first=arrayOfNames[i];
}else{
if(first==arrayOfNames[i]){break;}
}
}

Just change your for loop condition to:
for (int i = 0; i == 0 || arrayOfNames[i] != arrayOfNames[0]; i++)

Related

Java: Both if and else statements run

I am trying to refector a 2D array project to include a search method to clean up the code in my main method. However, when I enter a valid name it can find the first row of data but will also print the else statement. If I enter a valid name for second row it will sometimes return it after printing the else statement.
I've tried rewriting the code, creating a return variable for the method, using a nested loop, modifying the return array value.
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("==== Family Affair ====");
System.out.println("How many members will you add?");
int number = scan.nextInt(); scan.nextLine();//scan.nextLine() ad hoc scan fix
//2D Array number of rows by scan/number input
String[][] familyData = new String[number][2];
//for loop captures input column data for each row
//nested loop created duplicate output
for (int i = 0; i < familyData.length; i++) {
System.out.print("\tName: ");
familyData[i][0] = scan.nextLine();
System.out.print("\tState: ");
familyData[i][1] = scan.nextLine();
System.out.println(" ");
}
System.out.println(" ");//extra space
printData(familyData);//call printData() method
findData(familyData);//call findData() method
}
public static void printData(String[][] data) {
for (int i = 0; i < data.length; i++) {
System.out.print("\tName: " + data[i][0] + " ");
System.out.print("\tState: " + data[i][1] + " ");
System.out.println(" ");
}
}
public static String[] findData(String[][] data) {
System.out.println("SEARCH...");
System.out.println("First Name: ");
String name = scan.nextLine();
String[] resultData = new String[0];
for (int i = 0; i < data.length; i++) {
if (name.equals(data[i][0])) {
System.out.println("--- Search Results ---");
System.out.println("\tName: " + data[i][0]);
System.out.println("\tState: " + data[i][1]);
}else {
System.out.println("Nothing found. Try Again");
System.out.println("First Name: ");
name = scan.nextLine();
}
}
return resultData; //returned as String[] results = findData(param);
}
Let me suggest the use of List<>
import java.util.ArrayList;
import java.util.List;
private static List<String[]> findData(String[][] source, String search)
{
final List<String[]> data = new ArrayList<>();
for (String[] array : source)
{
if (search.equals(array[0]))
{
data.add(array);
}
}
return data;
}
And here is an example of use
public static void main(String args[])
{
String[][] familyData = new String[2][2];
familyData[0][0] = "Sulabha";
familyData[0][1] = "Married";
familyData[1][0] = "Bertram";
familyData[1][1] = "Single";
List<String[]> data = findData(familyData, "Sulabha");
if (data.size() == 0)
{
System.out.println("Nothing found.");
}
else
{
for (String[] item : data)
{
System.out.println("--- Search Results ---");
System.out.println("\tName: " + item[0]);
System.out.println("\tState: " + item[1]);
}
}
}

Method to Find ArrayList Index to Where the Object Will be Added

I have an ArrayList that is being filled with customer information using a Customer class. In my addCustomerRecord method, I am calling findAddIndex within the addCustomerRecord method so the data entered will be sorted prior to displaying the data. Here is my code and do not mind the fileWhatever method, I don't use it.
public class CustomerDemo
{
//arrayList of customer objects
public static ArrayList<Customer> customerAL = new ArrayList<>();
public static void main (String[] args)
{
//to hold menu choice
String menuChoice = "";
Scanner kb = new Scanner(System.in);
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
//loop priming read
menuChoice = kb.nextLine();
//make input case insensitive
menuChoice = menuChoice.toLowerCase();
do
{
if(menuChoice.equals("a"))
addCustomerRecord(kb);
else if(menuChoice.equals("d"))
{
displayCustomerRecords();
}
else if(menuChoice.equals("q"))
{
System.out.println("Program exiting..");
System.exit(0);
}
else
{
System.out.println("incorrect entry. Please re-enter a valid entry: \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}while(menuChoice.equals("a") || menuChoice.equals("d") || menuChoice.equals("q"));
kb.close();
}
/* public static void displayCustomerRecords()
{
System.out.println();
for (int i = 0; i < customerAL.size(); ++i)
{
System.out.printf("%-15s", customerAL.get(i).getLastName());
System.out.printf("%-15s", customerAL.get(i).getFirstName());
System.out.printf("%-6s", customerAL.get(i).getCustID());
System.out.printf("%15s\n", customerAL.get(i).getPhoneNumber());
}
System.out.println();
}
/**
* prompts to enter customer data and mutator methods called
* with a Scanner object passed as an argument to set data
* #param location index position of where the element will be added.
* #param kb a Scanner object to accept input
*/
public static void addCustomerRecord(Scanner kb)
{
Customer currentCustomerMemoryAddress = new Customer();
System.out.println("Enter first name: \n");
String fName = kb.nextLine();
currentCustomerMemoryAddress.setFirstName(fName);
System.out.println("Enter last name: \n");
String lName = kb.nextLine();
currentCustomerMemoryAddress.setLastName(lName);
System.out.println("Enter customer phone number: \n");
String pNum = kb.nextLine();
currentCustomerMemoryAddress.setPhoneNumber(pNum);
System.out.println("Enter customer ID number: \n");
String ID = kb.nextLine();
currentCustomerMemoryAddress.setCustID(ID);
int addLocation = findAddLocation(currentCustomerMemoryAddress);
customerAL.add(addLocation, currentCustomerMemoryAddress);
currentCustomerMemoryAddress = null;
}
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(int i = 0; i < customerAL.size(); i++)
{
//Stumped here
}
}
else
return location;
return location;
}
}
It looks like you are reinventing the wheel here William
Replace your code for displayCustomerRecords with this:
public static void displayCustomerRecords()
{
System.out.println();
customerAL.stream().map(c -> String.format("%-15s%-15s%-6s%15s\n",
c.getLastName(), c.getFirstName(), c.getCustID(), c.getPhoneNumber()))
.sorted()
.forEach(System.out::print);
System.out.println();
}
Update
Taking into account your comment you can replace your findAddLocationmethod by the following:
private static Comparator<Customer> comparator = Comparator.comparing(Customer::getLastName)
.thenComparing(Customer::getFirstName)
.thenComparing(Customer::getCustID)
.thenComparing(Customer::getPhoneNumber);
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(Customer customerInList : customerAL)
{
if(comparator.compare(customerInList, cust) > 0) {
break;
}
location++;
}
}
return location;
}
We are traversing the array using Java's enhanced for-loop and comparing the objects using a Java 8 declared comparator (which I believe is the key to this assignment).
It would be a good idea if you could look into the Comparable interface and implement it in your Customer class. That way you could simply do a simple call to customerInList.compareTo(cust) to compare both objects.
As already stated, this is not a good practice and shouldn't be used in production code.

Java: sorting/arranging arrays based on user input

How can I sort this array based on user input? While using a constructor, I am returning values to the create the output. What I'd like to do is after receiving how the user would like to arrange his/her inputs, I'd like to perform something like an Arrays.sort(books[x].getBook());
But this does not work. Is there a way to arrange the returned values for each input? The following is the error I receive upon using the code below within each if statement, although getBooks() is very well in existence:
Error log
LibraryBookSort.java:56: error: cannot find symbol
Arrays.sort(books[x].getBooks());
^
symbol: method getBooks()
location: class LibraryBook
1 error
Code
public class LibraryBookSort {
public static void main(String[] args) {
LibraryBook[] books = new LibraryBook[5];
for (int x = 0; x < 5; x++) {
books[x] = new LibraryBook();
}
Scanner input = new Scanner(System.in);
for (int x = 0; x < 5; x++) {
// Get title
System.out.print("Enter the title of a book: ");
String title = input.nextLine();
books[x].setBook(title);
// Get author
System.out.print("Enter the author of this book: ");
String author = input.nextLine();
books[x].setAuthor(title);
// Get page count
System.out.print("Enter the number of pages for this book: ");
int pages = input.nextInt();
books[x].setPages(pages);
input.nextLine();
}
System.out.println("How would you like to organize your values?");
System.out.println("Sort by title > Enter 1: ");
System.out.println("Sort by author's last name > Enter 2: ");
System.out.print("Sort by page count > Enter 3: ");
int sortBy = input.nextInt();
// Sort by title
if(sortBy == 1) {
//????;
}
// Sort by author
else if(sortBy == 2) {
//????;
}
// Sort by page count
else if(sortBy == 3) {
//????;
}
// Print sorted array >> Use of constructor
for(int x = 0; x < 5; x++) {
System.out.println();
System.out.println("Book ");
System.out.println("Title: " + books[x].getBook());
System.out.println("Author: " + books[x].getAuthor());
System.out.println("Page Count: " + books[x].getPages());
}}}
The following will arrange my inputs using a comparator. However, the question remains, is there another approach to sorting this data outside of using a comparator?
class TitleComparator implements Comparator {
public int compare(Object book1, Object book2) {
String title1 = ((LibraryBook) book1).getBook();
String title2 = ((LibraryBook) book2).getBook();
return title1.compareTo(title2);
}}
I tried to add like this and it is working. Store the books inside the collection. So that you can make use of Collections.sort function and Comparator.
LibraryBookSort.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class LibraryBookSort {
private static ArrayList<LibraryBook> list;
public static void main(String[] args) {
LibraryBook[] books = new LibraryBook[5];
for (int x = 0; x < 5; x++) {
books[x] = new LibraryBook();
}
Scanner input = new Scanner(System.in);
list = new ArrayList<LibraryBook>();
for (int x = 0; x < 5; x++) {
// Get title
System.out.print("Enter the title of a book: ");
String title = input.nextLine();
books[x].setBook(title);
// Get author
System.out.print("Enter the author of this book: ");
String author = input.nextLine();
books[x].setAuthor(title);
// Get page count
System.out.print("Enter the number of pages for this book: ");
int pages = input.nextInt();
books[x].setPages(pages);
list.add(books[x]);
input.nextLine();
}
System.out.println("How would you like to organize your values?");
System.out.println("Sort by title > Enter 1: ");
System.out.println("Sort by author's last name > Enter 2: ");
System.out.print("Sort by page count > Enter 3: ");
int sortBy = input.nextInt();
// Sort by title
if(sortBy == 1) {
Collections.sort(list,new TitleComparator());
}
// Sort by author
else if(sortBy == 2) {
//????;
}
// Sort by page count
else if(sortBy == 3) {
//????;
}
for(LibraryBook st: list){
System.out.println(st.title+" "+st.author+" "+st.pages);
}
}}
Also added another class TitleComparator.java.
import java.util.Comparator;
public class TitleComparator implements Comparator <LibraryBook>{
#Override
public int compare(LibraryBook arg0, LibraryBook arg1) {
return arg0.title.compareTo(arg1.title);
}
}
This is for sort books based on the title. You can also add PageComparator and AuthorComparator for the other two options.

Error when printing out my object from array

Im having some trouble printing out details ive put into my array. when i run my addBook i out in details of two books, but when i select option 2 from menu, i get a runtime error (outofbounds),
Above is resolved by adding [i] to the printline and changing my loop length.
The problem i am having now if my BookID from my loanbook, its not incrementing.
import java.util.Scanner;
public class library {
static Scanner keyboard = new Scanner(System.in);
static boolean run = true;
public static fiction [] fictionArray = new fiction[2];
public static nonfiction [] nonfictionArray = new nonfiction[2];
public static void main (String[] args){ // main class method
while (run){ // this while statement allows the menu to come up again
int answer = 0; // answer initialized to Zero
boolean isNumber;
do{ // start of validation
System.out.println("1. Add book"); // Menu selections
System.out.println("2. Display the books available for loan");
System.out.println("3. Display the books currently on loan");
System.out.println("4. Make a book loan");
System.out.println("5. Return book ");
System.out.println("6 Write book details to file");
if (keyboard.hasNextInt()){ // I would like to set values to =>1 <=6
answer = keyboard.nextInt(); // this is more validation for the input for menu selection
isNumber = true;
} else { // else if number not entered, it will prompt for the correct input
System.out.print(" You must enter a number from the menu to continue. \n");
isNumber = false;
keyboard.next(); // clears keyboard
}
}
while (!(isNumber)); // while to continue program after the do has completed
switch (answer){ // switch statement - uses answer from the keyboard to select a case
case 1:
addBook(); // adds book
break;
case 2:
for (int i=0; i<5; i++){
if (fictionArray[i] != null){
System.out.println(fictionArray);}
if (nonfictionArray[i] != null){
System.out.println(nonfictionArray);}}
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
}
}
}
static void addBook(){
loanbook [] loanArray = new loanbook[2];
String title,author;
int choice;
for(int x = 0; x < loanArray.length; x++){
System.out.print("Press 1 for Fiction or 2 for Non Fiction: "); // sub menu for fiction and non fiction
choice = keyboard.nextInt();
if (choice == 1){
for(int count = 0; count < fictionArray.length; count++){
System.out.print("Enter title: ");
title= keyboard.nextLine();
title= keyboard.nextLine();
System.out.print("Enter author: ");
author= keyboard.nextLine();
fictionArray[count] = new fiction(title, author);
System.out.println("The book information you entered was : " + fictionArray[count].toString()); // this will show the entry which was inout to the array
count++; }}
else if (choice == 2) {
for(int count = 0; count < nonfictionArray.length; count++){
System.out.print("Enter title: ");
title= keyboard.nextLine();
title= keyboard.nextLine();
System.out.print("Enter author: ");
author= keyboard.nextLine();
nonfictionArray[count] = new nonfiction(title, author);
System.out.println("The book information you entered was : " + nonfictionArray[count].toString()); // this will show the entry which was inout to the array
count++;}}
else{ int noBooks = loanArray.length;
for (int i=0; i<noBooks; i++){
System.out.print(loanArray[x]);
}}}} // addbook
} // Library end
Below is my Superclass , then my subclass
public class loanbook {
private String title,author;
private int bookID;
public loanbook(String pTitle,String pAuthor){
bookID = 0;
title = pTitle;
author = pAuthor;
bookID++;
} // Constructor
public void setTitle(String pTitle){
title = pTitle;
} // setTitle
protected String getTitle(){
return title;
} // getTitle
protected String getAuthor(){
return author;
} // getAuthor
public String toString(){
return "\n BookID: "+ bookID+"\n" + " Title: "+ getTitle()+"\n" +" Author : "+ getAuthor()+ "\n";
}
} // loanbook
My subclasses are the same except for the class name and constructor
public class fiction extends loanbook {
String bookType;
private String getBookType; // Would be fiction
public fiction(String pTitle,String pAuthor){
super(pTitle,pAuthor);
} // constructor
protected void setBookType (String pBookType){
bookType = pBookType;
} // setter for bookType
protected String getBookType(){
return "Fiction";
}
public String toString(){
return super.toString() +" This book is : "+ getBookType();
}
} // class
You've declared your fictionarray and nonfictionarray to be of length 2. However, in your case 2, you are looping 5 times:
for (int i=0; i<5; i++){
if (fictionArray[i] != null){
Change it to 2. It's possible you changed the array length in the declaration, but forgot to change the loop iteration. In that case, you can just use the array's length:
for (int i = 0; i < fictionArray.length; i++) {
Additionally, it looks like you want to print out the specific array element, not the array itself:
System.out.println(fictionArray[i]);
and likewise for nonfictionarray and the nonfiction class.
Two things I see
if (fictionArray[i] != null){
System.out.println(fictionArray);}
if (nonfictionArray[i] != null){
System.out.println(nonfictionArray);}}
You're trying to print the entire array System.out.println(fictionArray). You probably want System.out.println(fictionArray[i])
Also you should set your array sizes to 5 if you want to loop 5 times

Creating a method that searches an Array for a user inputted value, outputs result(s) if any?

I have a program that stores 4 array lists: songName, songArtist, songAlbum & songYear which can be all added to,edited,shuffled and delete by the user. I want to create a method, that when called asks the user to input a string, which then searches the array and prints any corresponding results. For example if I searched the songName array for any song with "The" in the title, they'd output one on each line.
Can anybody help me out with this one? Thanks in advance :)
My Code:
Main Class:
package ca1;
//imports the scanner
import java.util.Scanner;
public class MainClass extends UserInput {
public String nextInt;
public static void main(String[] args) {
//Links to the UserInput class to create an object that stores
//user input
UserInput ui = new UserInput();
//Creates new scanner object
Scanner input = new Scanner(System.in);
//Declares the int "opt" so it can be used in the menu
int opt;
//Calls Methods Class so methods can be used below
Methods methodsFunctions = new Methods();
//initial prompt only displayed when program is first ran
System.out.println("Welcome to your music library");
//Usig a do while loop so that the program keeps running until
//a specific condition is met, in this case it's when 0 is selected.
do
{
//Menu Prompts printed to the screen for the user to select from
System.out.println("........ \n");
System.out.println("Press 0 to Exit\n");
System.out.println("Press 1 to Add a Song\n");
System.out.println("Press 2 to View All Songs\n");
System.out.println("Press 3 to Remove a Song\n");
System.out.println("Press 4 to Edit Song Information\n");
System.out.println("Press 5 to Shuffle Library\n");
System.out.println("Press 6 to Search (by name) \n");
System.out.println("Press 7 to Remove ALL Songs\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("Goodbye!");
}
else if (opt == 1)
{
//This method allows the user to add a song to the library.
//With the format being Title, Artist, Year.
methodsFunctions.addEntry();
}
else if (opt == 2)
{
//This method prints the contents of the Array List to the screen
methodsFunctions.viewAll();
}
else if (opt == 3)
{
//This method allows the user to remove an indiviual song from
//their music library
methodsFunctions.removeOne();
}
else if (opt == 4)
{
//This method allows the user to edit the data of a particular
//and then prints the new value on screen
methodsFunctions.editItem();
}
else if (opt == 5)
{
//This method uses the Collections.shuffle method
//to re-arrange the track list
//song to simulate a music player's shuffle effect.
methodsFunctions.shuffleSongs();
}
else if (opt == 6)
{
methodsFunctions.searchSongs();
}
else if (opt == 7)
{
//This method will clear all contents of the library.
//It will ask the user to confirm their choice.
methodsFunctions.clearAll();
}
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("Incorrect Entry, please try again");
}
} //do-while loop
while (opt > 0);
}
}
Methods Class
package ca1;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Methods extends UserInput
{
Scanner input = new Scanner (System.in);
//Declare array lists
List<String> songName = new ArrayList<>();
List<String> songArtist = new ArrayList<>();
List<String> songAlbum = new ArrayList<>();
List<Integer> songYear = new ArrayList<>();
UserInput ui = new UserInput();
public void clearAll(){
System.out.println("Are you sure?");
System.out.print("1: Yes \n2: No" + "\n");
System.out.print("");
int confirmDelete=input.nextInt();
if (confirmDelete == 1){
songName.clear();
songYear.clear();
System.out.println("Your music library has been cleared");
}
}
public void viewAll(){
System.out.println("\n");
System.out.println("Your Music Library" + "\n" + " Artist - Song - Album (Year) " + "\n");
for (int i = 0; i < songName.size(); i++)
{
int counter=i+1;
System.out.println(counter+": "+songArtist.get(i)+" - "+ songName.get(i)+ " - " + songAlbum.get(i) + " (" +songYear.get(i)+") ");
}
System.out.println("\n");
}
public void addEntry(){
//System.out.print("Enter Name: ");
String newName = ui.getString("Enter the name of the track");
songName.add(newName);
String newArtist = ui.getString("Who performs this track");
songArtist.add(newArtist);
String newAlbum = ui.getString("What album is this track from");
songAlbum.add(newAlbum);
System.out.print("What year was the track released? ");
int newYear=input.nextInt();
songYear.add(newYear);
System.out.println("\n" + "Thank you, " +songName.get(songName.size()-1) + " has been added to the library.");
System.out.println("\n" + "Press 2 to view your library." + "\n");
/*
System.out.println("\n"+songName.get(songName.size()-1));
System.out.println("\n"+songArtist.get(songArtist.size()-1));
System.out.println("\n"+songYear.get(songYear.size()-1));
*/
}
public void removeOne(){
System.out.println(" Which song would you like to delete? (1 to "+songName.size()+")");
viewAll();
int remove=input.nextInt();
if (remove >songName.size()){
System.out.println("Invalid ");
}
else {
remove--;
System.out.println("Are you sure you would like to delete "+songArtist.get(remove)+" - "+songName.get(remove)+ "-" + songAlbum.get(remove) +" (" +songYear.get(remove)+ ") from your music library?");
System.out.print("1: Yes \n2: No" + "\n");
int confirmDelete=input.nextInt();
if (confirmDelete == 1){
songArtist.remove(remove);
songAlbum.remove(remove);
songName.remove(remove);
songYear.remove(remove);
System.out.println(songName.get(remove)+ " has just been removed from your music library");
// viewAll();
}
}
}
public void shuffleSongs(){
//The attributes of the song all get shuffled together because they
//are all linked by the same seed.
long seed = System.nanoTime();
Collections.shuffle(songName, new Random(seed));
Collections.shuffle(songArtist, new Random(seed));
Collections.shuffle(songAlbum, new Random(seed));
Collections.shuffle(songYear, new Random(seed));
System.out.println("Your library is now shuffled" + "\n");
viewAll();
//Shuffles library, then outputs the new library list.
}
public void editItem(){
viewAll();
System.out.println("Choose the song you want to edit (1 to "+songName.size()+")");
//prints out the contents of library with first entry being index 1
//The library is numbered and goes as far as the index of the last entry
int edit=input.nextInt();
if (edit >songName.size()){
System.out.println("Invalid Selection");
//if user selects a number that corresponds to an index that's not
//In the array list, they will be shown an error.
}
else{
edit--;
System.out.println("\n" + "Enter New Track Name: ");
input.nextLine();
String editName=input.nextLine();
songName.set(edit,editName);
//Edits the songName value of the Song object selected
System.out.println("\n" + "Enter New Artist ");
String editArtist=input.nextLine();
songArtist.set(edit,editArtist);
//Edits the songArtist value of the Song object selected
System.out.println("\n" + "Enter New Album ");
String editAlbum=input.nextLine();
songArtist.set(edit,editAlbum);
//Edits the songAlbum value of the Song object selected
System.out.println("\n" + "Enter New Year:");
int editYear;
editYear = input.nextInt();
songYear.set(edit,editYear);
//Edits the songName value of the Song object selected
System.out.print("\n" + "Your changes have been saved:" + "\n");
System.out.print("\n" + "This is your current library");
viewAll();
}
}
public void searchSongs(){
}
}
Everything works, I just want to add the functionality of being able to search.
String to be searched:
String searchString= "the something ok"
Split it into tokens:
String[] tokens = searchString.split("\\s+");
Building a regex pattern to match the said string:
StringBuilder sb = new StringBuilder();
sb.append("(?i)^" + "(?=.*" + tokens[0] + ")");
for (int num = 0; num < tokens.length; num++) {
sb.append("(?=.*" + tokens[num] + ")");
}
Then match each name in your array with that regex patter:
List<String> result = new ArrayList();
for(String i: yourStringArray){
if(i.matches(sb.toString()))
{
result.add(i);
}
}
Then you display the result list:
You can figure out this part your self

Categories

Resources