改进我的搜索方法

时间:2014-10-21 12:28:04

标签: java bluej

我创建了一个程序,允许用户输入Dvd集合或书籍集。

我对我能够实现的目标感到相当满意(对于编程来说仍然相当新)但我对我的搜索方法感到烦恼。

搜索确实有效,并返回用户查找的内容,但它也会打印出之后无法找到的内容。我认为,原因是我编写代码的方式意味着在结束并返回菜单之前读取每个搜索参数。

认为我可能需要使用布尔值或类似方法来满足搜索条件时的循环。

我确信任何有经验的程序员都会对我的代码感到震惊......

搜索方法:

/**
 * Asks user to input Dvd title then compares 
 * with Dvd titles in collection
 * @param none
 * @return none
 */
public void searchDvd()
{
    String temp = ""; // Temporary variable to hold dvd title

    System.out.println ("\nPlease enter Dvd Title (full title) to search for: ");
    temp= Genio.getString();

    if(temp.equals(dvd1.getTitle()))
    {
        clrscr();
        System.out.println("\nDvd is present in collection at location 1 (Dvd 1 in collection):\n\nTitle: "  + dvd1.getTitle() + " \n  Director: "
            + dvd1.getDirector() + " \n  Lead Act: " + dvd1.getLead() + " \n  Run Time: " + dvd1.getRunTime() + " \n  Price: "
            + dvd1.getDvdPrice());
        pressKey();
    }
    if(temp.equals(dvd2.getTitle()))
    {
        clrscr();
        System.out.println("\nDvd is present in collection at location 2 (Dvd 2 in collection):\n\nTitle: " + dvd2.getTitle() + " \n  Director: "
            + dvd2.getDirector() + " \n  Lead Act: " + dvd2.getLead() + " \n  Run Time: " + dvd2.getRunTime() + " \n  Price: "
            + dvd2.getDvdPrice());
        pressKey();
    }
    if(temp.equals(dvd3.getTitle()))
    {
        clrscr();
        System.out.println("\nDvd is present in collection at location 3 (Dvd 3 in collection):\n\nTitle: " + dvd3.getTitle() + " \n  Director: "
            + dvd3.getDirector() + " \n  Lead Act: " + dvd3.getLead() + " \n  Run Time: " + dvd3.getRunTime() + " \n  Price: "
            + dvd3.getDvdPrice());
        pressKey();
    }

    else 
    {
        clrscr();
        System.out.println("\nSorry, there were no Dvd's found with that title to display.\n ");
        pressKey();
    }
}    

集合类(使用main()):

public class Collection
{
//Declare private variables for use with class instances
private Dvd dvd1;
private Dvd dvd2;
private Dvd dvd3;
private Book book1;
private Book book2;
private Book book3;


public Collection()
{
    //array = new int[2];
    //dvd1 = dvd1;
    //dvd2 = dvd2;
    //dvd3 = dvd3;
    dvd1 = new Dvd();
    dvd2 = new Dvd();
    dvd3 = new Dvd();
    book1 = new Book();
    book2 = new Book();
    book3 = new Book();
}


public static void main(String args[])
{    
    //creates an instance of the collection class 
    Collection collection = new Collection();
    collection.menu();
}


public void menu()
{
    //declare the option field
    int option;
    char answer;     
    //start do while loop for the menu
    do
    {
        //display the menu
        clrscr();
        System.out.println("");
        System.out.println("\n\n~#~#~#~#~ DVD COLLECTION MENU ~#~#~#~#~\n\n");
        System.out.println("\n<><><><> DVD's <><><><>\n");
        System.out.println("1: Add (up to 3) Dvd's to Collection");
        System.out.println("2: Display Dvd Collection");
        System.out.println("3: Search Dvd Collection by collection");
        System.out.println("\n<><><><> BOOK's <><><><>\n");
        System.out.println("4: Add (up to 3) Books's to Collection");
        System.out.println("5: Display Book Collection");
        System.out.println("6: Search Book Collection by Title");
        System.out.println("7: Quit program");

        //prompt user to enter a selection
        System.out.println("\nPlease select an option (1 - 7): ");
        //use genio to get the user input
        option=Genio.getInteger();

        // Option 1 allows user to add up to 3 Dvd's to dvd collection
        if (option == 1) 
        { 
            clrscr();
            System.out.println("Enter Dvd 1 details:\n");
            dvd1.setDvdInputs();
            pressKey();
            System.out.println("Enter Dvd 2 details:\n");
            dvd2.setDvdInputs();
            pressKey();
            System.out.println("Enter Dvd 3 details:\n");
            dvd3.setDvdInputs();
            pressKey();
        }
        // Option 2 allows user to display Dvd collection
        if (option == 2)
        {
            clrscr();
            displayDvds();
        }
        // Option 3 allows the user to search the Dvd collection by title
        if (option == 3)
        {
            clrscr();
            searchDvd();
        }
        // Option 4 allows user add books to the book collection
        if (option == 4)
        {
            clrscr();
            System.out.println("Enter Book 1 details:\n");
            book1.setBookInputs();
            pressKey();
            System.out.println("Enter Book 2 details:\n");
            book2.setBookInputs();
            pressKey();
            System.out.println("Enter Book 3 details:\n");
            book3.setBookInputs();
            pressKey();
        }
        //i Option 5 allows the user to display the collection of books
        if (option == 5)
        {
            clrscr();
            displayBooks();
        }
        // Option 6 allows the user to search the Book collection by title
        if (option == 6)
        {
            clrscr();
            searchBook();
        }

    }
    // Option 7 will print a message that tells that the program may be exited
    while (option != 7);
    clrscr();
    System.out.println("You may now close the program. (click cross at top right)");
}


public void displayDvds()
{
    float totalPrice = 0;
    totalPrice = dvd1.getDvdPrice() + dvd2.getDvdPrice() + dvd3.getDvdPrice();
    int totalRunTime = 0;
    totalRunTime = dvd1.getRunTime() + dvd2.getRunTime() + dvd3.getRunTime();

    if (dvd1.getTitle() == "" && dvd1.getDirector() == "" && dvd1.getLead() == "" && dvd1.getRunTime() == 0 && dvd1.getDvdPrice() == 0 && dvd2.getTitle() == "" && 
    dvd2.getDirector() == "" && dvd2.getLead() == "" && dvd2.getRunTime() == 0 && dvd2.getDvdPrice() == 0 && dvd3.getTitle() == "" && dvd3.getDirector() == ""
    && dvd3.getLead() == "" && dvd3.getRunTime() == 0 && dvd3.getDvdPrice() == 0)
    {
        clrscr();
        System.out.println("Sorry, there were no Dvd's in the collection to display.");
        pressKey();
    }
    else  
    {
        clrscr();
        System.out.println(" \nDvd Collection:\n DVD1:\nTitle: " + dvd1.getTitle() + " \nDirector: "
            + dvd1.getDirector() + " \nLead Act: " + dvd1.getLead() + " \nRun Time: " + dvd1.getRunTime() + " \nPrice: £"
            + dvd1.getDvdPrice());

        System.out.println(" \nDvd Collection:\n DVD2:\nTitle: " + dvd2.getTitle() + " \nDirector: "
            + dvd2.getDirector() + " \nLead Act: " + dvd2.getLead() + " \nRun Time: " + dvd2.getRunTime() + " \nPrice: £"
            + dvd2.getDvdPrice());

        System.out.println(" \nDvd Collection:\n DVD3:\nTitle: " + dvd3.getTitle() + " \nDirector: "
            + dvd3.getDirector() + " \nLead Act: " + dvd3.getLead() + " \nRun Time: " + dvd3.getRunTime() + " \nPrice: £"
            + dvd3.getDvdPrice());

        System.out.println(" \nTotal cost of combined Dvd's: £" + totalPrice);

        System.out.println(" \nTotal Run Time of combined Dvd's: " + totalRunTime + " minutes.");
        pressKey();
    }
}


public void searchDvd()
{
    String temp = ""; // Temporary variable to hold dvd title

    System.out.println ("\nPlease enter Dvd Title (full title) to search for: ");
    temp= Genio.getString();

    if(temp.equals(dvd1.getTitle()))
    {
        clrscr();
        System.out.println("\nDvd is present in collection at location 1 (Dvd 1 in collection):\n\nTitle: "  + dvd1.getTitle() + " \n  Director: "
            + dvd1.getDirector() + " \n  Lead Act: " + dvd1.getLead() + " \n  Run Time: " + dvd1.getRunTime() + " \n  Price: "
            + dvd1.getDvdPrice());
        pressKey();
    }
    if(temp.equals(dvd2.getTitle()))
    {
        clrscr();
        System.out.println("\nDvd is present in collection at location 2 (Dvd 2 in collection):\n\nTitle: " + dvd2.getTitle() + " \n  Director: "
            + dvd2.getDirector() + " \n  Lead Act: " + dvd2.getLead() + " \n  Run Time: " + dvd2.getRunTime() + " \n  Price: "
            + dvd2.getDvdPrice());
        pressKey();
    }
    if(temp.equals(dvd3.getTitle()))
    {
        clrscr();
        System.out.println("\nDvd is present in collection at location 3 (Dvd 3 in collection):\n\nTitle: " + dvd3.getTitle() + " \n  Director: "
            + dvd3.getDirector() + " \n  Lead Act: " + dvd3.getLead() + " \n  Run Time: " + dvd3.getRunTime() + " \n  Price: "
            + dvd3.getDvdPrice());
        pressKey();
    }

    else 
    {
        clrscr();
        System.out.println("\nSorry, there were no Dvd's found with that title to display.\n ");
        pressKey();
    }
}    


public void displayBooks()
{
    float totalbPrice = 0;
    totalbPrice = book1.getBookPrice() + book2.getBookPrice() + book3.getBookPrice();
    int totalPages;
    totalPages = book1.getPages() + book2.getPages() + book3.getPages();

    if (book1.getBookTitle() == "" && book1.getAuthor() == "" && book1.getGenre() == "" && book1.getPages() == 0 && book1.getBookPrice() == 0 && book2.getBookTitle() == "" || 
    book2.getAuthor() == "" && book2.getGenre() == "" && book2.getPages() == 0 && book2.getBookPrice() == 0 && book3.getBookTitle() == "" && book3.getAuthor() == ""
    && book3.getGenre() == "" && book3.getPages() == 0 && book3.getBookPrice() == 0)
    {
        clrscr();
        System.out.println("Sorry, there were no Book's in the collection to display.");
        pressKey();
    }
    else  
    {
        clrscr();
        System.out.println(" \nBook Collection:\n BOOK 1: \nTitle: " + book1.getBookTitle() + " \nAuthor: "
            + book1.getAuthor() + " \nGenre: " + book1.getGenre() + " \nPages: " + book1.getPages() + " \nPrice: £"
            + book1.getBookPrice());

        System.out.println(" \nBook Collection:\n BOOK 2: \nTitle: " + book2.getBookTitle() + "  \nAuthor: "
            + book2.getAuthor() + " \nGenre: " + book2.getGenre() + " \nPages: " + book2.getPages() + " \nPrice: £"
            + book2.getBookPrice());

        System.out.println(" \nBook Collection:\n BOOK 3: \nTitle: " + book3.getBookTitle() + " \nAuthor: "
            + book3.getAuthor() + " \nGenre: " + book3.getGenre() + " \nPages: " + book3.getPages() + " \nPrice: £"
            + book3.getBookPrice());

        System.out.println(" \nTotal cost of combined Book's: £" + totalbPrice);

        System.out.println(" \nTotal number of combined book pages: " + totalPages + " pages.");
        pressKey();
    }
}


public void searchBook()
{
    String tempb; // Temporary variable to hold book title

    System.out.println ("\nPlease enter Book Title (full title) to search for: ");
    tempb= Genio.getString();

    if(tempb.equals(book1.getBookTitle()))
    {
        clrscr();
        System.out.println("\nBook is present in collection at location 1 (Book 1 in collection):\n\nTitle: "  + book1.getBookTitle() + " \nAuthor: "
            + book1.getAuthor() + " \nLead Act: " + book1.getGenre() + " \nRun Time: " + book1.getPages() + " \nPrice: "
            + book1.getBookPrice());
        pressKey();
    }
    if(tempb.equals(book2.getBookTitle()))
    {
        clrscr();
        System.out.println("\nBook is present in collection at location 2 (Book 2 in collection):\n\nTitle: "  + book2.getBookTitle() + " \nAuthor: "
            + book2.getAuthor() + " \nLead Act: " + book2.getGenre() + " \nRun Time: " + book2.getPages() + " \nPrice: £"
            + book2.getBookPrice());
        pressKey();
    }
    if(tempb.equals(book3.getBookTitle()))
    {
        clrscr();
        System.out.println("\nBook is present in collection at location 3 (Book 3 in collection):\n\nTitle: "  + book3.getBookTitle() + " \nAuthor: "
            + book3.getAuthor() + " \nLead Act: " + book3.getGenre() + " \nRun Time: " + book3.getPages() + " \nPrice: £"
            + book3.getBookPrice());
        pressKey();
    }
    else
    {
        clrscr();
        System.out.println("\nSorry, there were no Book's found with that title to display.\n ");
        pressKey();
    }
}   


public static void clrscr()
{           
    for ( int i=1;i<=50;i++)
        System.out.println();
}


public static void pressKey()
{
    String s;
    System.out.print("\nPress return to continue : \n");
    s = Genio.getString();
}
} 

Dvd类与此相同):

public class Dvd
{
// instance Dvd variables 
private String dvdTitle = ""; // Title of dvd set to empty
private String dvdDirector = ""; // Director of dvd set to empty
private String dvdLead = ""; // Lead actor/actress of dvd set to empty
private int dvdRunTime = 0; //Dvd run time in minutes
private float dvdPrice = 0; //Value of dvd


public Dvd( )
{
  dvdTitle = ""; 
  dvdDirector = ""; 
  dvdLead = ""; 
  dvdRunTime = 0; 
  dvdPrice = 0;
}


/
public void setDvdInputs()
{
    System.out.println("Please enter the Dvd Title: ");
 dvdTitle=Genio.getString(); 

 System.out.println("Please enter the Dvd Director: ");    
 dvdDirector=Genio.getString();

 System.out.println("Please enter the Dvd Lead Actor/Actress: ");      
 dvdLead=Genio.getString();

 System.out.println("Please enter the Dvd Run Time: ");    
 dvdRunTime=Genio.getInteger(); 

 System.out.println("Please enter the Dvd Cost: ");      
 dvdPrice=Genio.getFloat(); 
}


   public String getTitle(){
     return dvdTitle;
   }

   public String getDirector(){
     return dvdDirector;
   }

   public String getLead(){
     return dvdLead;
   }

   public int getRunTime()
   {
     return dvdRunTime;
   }

   public float getDvdPrice()
   {
     return dvdPrice;
   }      
}

书类:

public class Book
{
// instance Dvd variables 
private String bookTitle = ""; // Title of dvd set to empty
private String bookAuthor = ""; // Director of dvd set to empty
private String bookGenre = ""; // Lead actor/actress of dvd set to empty
private int bookPages = 0; //Dvd run time in minutes
private float bookPrice = 0; //Value of dvd


public Book( )
{
  bookTitle = ""; 
  bookAuthor = ""; 
  bookGenre = ""; 
  bookPages = 0; 
  bookPrice = 0;
}


public void setBookInputs()
{
    System.out.println("Please enter the Book Title: ");
 bookTitle=Genio.getString();

 System.out.println("Please enter the Book Author: ");    
 bookAuthor=Genio.getString();

 System.out.println("Please enter the Book Genre: ");      
 bookGenre=Genio.getString();

 System.out.println("Please enter the Book Page Number: ");    
 bookPages=Genio.getInteger(); //should be dvdRunTime = Genio.getDouble();

 System.out.println("Please enter the Book Cost: ");      
 bookPrice=Genio.getFloat(); //should be dvdPrice = Genio.getFloat();
}

   public String getBookTitle(){
     return bookTitle;
   }

   public String getAuthor(){
     return bookAuthor;
   }

   public String getGenre(){
     return bookGenre;
   }

   public int getPages()
   {
     return bookPages;
   }

   public float getBookPrice()
   {
     return bookPrice;
   }      
}

Genio(用户输入)类:

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Genio
{


public Genio()
{
}



private static String getStr() 
{
    String inputLine = "";
    BufferedReader reader = 
        new BufferedReader(new InputStreamReader(System.in));
    try 
    {
        inputLine = reader.readLine();
    }

    catch(Exception exc) 
    {
        System.out.println ("There was an error during reading: "
                            + exc.getMessage());
    }
    return inputLine;
}


public static int getInteger()
{
    int temp=0;
    boolean OK = false;

    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do 
    {
        try
        {
            temp = Integer.parseInt(keyboard.readLine());
            OK = true;
        }

        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException) 
            {
                System.out.print("Integer value needed: ");
            }
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);
    return(temp);
 }


public static float getFloat()
{
    float temp=0;
    boolean OK = false;

    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do 
    {
        try
        {
            temp = Float.parseFloat(keyboard.readLine());
            OK = true;
        }


        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException) 
            {
                System.out.print("Number needed: ");
            } 
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);

    return(temp);
 }

public static double getDouble()
{
    double temp=0;
    boolean OK = false;
    BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
    do 
    {
        try
        {
            temp = Double.parseDouble(keyboard.readLine());
            OK = true;
        }

        catch (Exception eRef)
        {
            if (eRef instanceof NumberFormatException) 
            {
                System.out.print("Number needed: ");
            }
            else
            {
                System.out.println("Please report this error: "+eRef.toString());
            }
        }

    } while(OK == false);

    return(temp);
 }



 public static char getCharacter()
 {
     String tempStr="";
     char temp=' ';
     boolean OK = false;
     do 
     {
         try
         {
             tempStr = getStr();
             temp = tempStr.charAt(0);
             OK = true;
         }

         catch (Exception eRef)
         {
             if (eRef instanceof StringIndexOutOfBoundsException)
             {
                 // means nothing was entered so prompt ...
                 System.out.print("Enter a character: ");
             }            
             else 
             {
                 System.out.println("Please report this error: "+eRef.toString());
             }
         }

     } while(OK == false);

     return(temp);
 }



 public static String getString()
 {
    String temp="";
    try
    {
        temp = getStr();
    }
    catch (Exception eRef)
    {
        System.out.println("Please report this error: "+eRef.toString());
    }
    return(temp);
 }     
}

4 个答案:

答案 0 :(得分:4)

您的问题是由于单独if statements造成的。

if(something) {
}
if(somethingElse) // This is separate from the one above.

您可以使用else if链接它们。

if(something) {
}
else if(somethingelse) {
}
else {
     System.out.println("Sorry, none could be found");
}

或者如果您希望代码更高效并且您正在使用JDK7 +,则可以使用switch ..

switch(input) {
    case "Something":
         // Do something
         break;
    default:
        System.out.println("Sorry, none could be found");
        break;
}

最后,如果要保持完全相同的if结构,则可以使用boolean值。

if(something)
{
    found = true;
}

if(!found)
{
    System.out.println("Sorry, none could be found");
}

为了完整起见,我已经添加了最后一个,但我不推荐它。使用前两个选项之一。

答案 1 :(得分:1)

如果没有找到任何标题,您只想说没有找到DVD。如果相反,你应该使用else。现在你只是检查第三个标题是否找不到,然后显示没有找到,即使找到其中一个标题。这些都应该是其他的:

public void searchDvd()
{
    String temp = ""; // Temporary variable to hold dvd title

    System.out.println ("\nPlease enter Dvd Title (full title) to search for: ");
    temp= Genio.getString();

    if(temp.equals(dvd1.getTitle()))
    {
        clrscr();
        System.out.println("\nDvd is present in collection at location 1 (Dvd 1 in collection):\n\nTitle: "  + dvd1.getTitle() + " \n  Director: "
            + dvd1.getDirector() + " \n  Lead Act: " + dvd1.getLead() + " \n  Run Time: " + dvd1.getRunTime() + " \n  Price: "
            + dvd1.getDvdPrice());
        pressKey();
    }
    else if(temp.equals(dvd2.getTitle()))
    {
        clrscr();
        System.out.println("\nDvd is present in collection at location 2 (Dvd 2 in collection):\n\nTitle: " + dvd2.getTitle() + " \n  Director: "
            + dvd2.getDirector() + " \n  Lead Act: " + dvd2.getLead() + " \n  Run Time: " + dvd2.getRunTime() + " \n  Price: "
            + dvd2.getDvdPrice());
        pressKey();
    }
    else if(temp.equals(dvd3.getTitle()))
    {
        clrscr();
        System.out.println("\nDvd is present in collection at location 3 (Dvd 3 in collection):\n\nTitle: " + dvd3.getTitle() + " \n  Director: "
            + dvd3.getDirector() + " \n  Lead Act: " + dvd3.getLead() + " \n  Run Time: " + dvd3.getRunTime() + " \n  Price: "
            + dvd3.getDvdPrice());
        pressKey();
    }

    else 
    {
        clrscr();
        System.out.println("\nSorry, there were no Dvd's found with that title to display.\n ");
        pressKey();
    }
}   

答案 2 :(得分:1)

将DVD放入“收藏”或List(例如ArrayList)并使用for循环。

for (DVD dvd : dvds)
{
    if (dvd.getTitle().equals(temp))
    {
       // display logic
       break;
    }
}

答案 3 :(得分:1)

在您的搜索代码中,使用2 If语句后跟If-else

您可能打算使用complet if-elseif-else或case语句 即

if(temp.equals(dvd1.getTitle())){
//do something}
elseif(temp.equals(dvd2.getTitle())){
//do somthing else}
elseif(temp.equals(dvd3.getTitle())){
//do something as well}
else{
//do the default behaviour

在你的代码中,如果第一个if匹配你会得到dvd返回但是(假设dvd 3不匹配)最后的其他

 else 
    {
        clrscr();
        System.out.println("\nSorry, there were no Dvd's found with that title to display.\n ");
        pressKey();
    }

除非搜索匹配dvd3

,否则这将始终为真