集合的BinarySearch无效

时间:2016-11-28 01:05:43

标签: java arrays netbeans binary-search

我是JAVA和Netbeans的新手,这就是我要做的事情:
用户可以在输入框中输入标题CD,然后按“删除”按钮从列表中删除CD。如果集合中不存在CD,则可以在发件箱中显示一条消息,说明这一点 这就是我所做的:

ArrayList <String> songs = new ArrayList();
Collections.addAll(songs, "Metric - Fantasies", "\nBeatles - Abbey Road", "\nPearl Jam - Ten", "\nDoors - Alive", "\nThe Rolling Stones - Gimme Shelter\n");
int remove = Collections.binarySearch(songs, artistinput.getText());
    if (remove < 0)
    {
        output.setText("That CD does not exist in the collection, please try again");
    }
    else if (remove >= 0)
    {
        boolean delete=songs.remove(artistinput.getText());{
    output.setText("Original Songs \n" +delete);

这是该计划中唯一没有想到的部分。这不起作用,因为每次键入歌曲时都会显示output.setText("That CD does not exist in the collection, please try again");,然后按“删除”。任何帮助表示赞赏,并提前感谢您!

3 个答案:

答案 0 :(得分:0)

使用java 8,您可以尝试这种方式:

    List<String> songs = new ArrayList<String>();
    int size = songs.size();
    Collections.addAll(songs, "Metric - Fantasies", "\nBeatles - Abbey Road", "\nPearl Jam - Ten", "\nDoors - Alive", "\nThe Rolling Stones - Gimme Shelter\n");
    songs.removeIf(o->o.equalsIgnoreCase(artistinput.getText()));
    int arSize = songs.size();
    if(size != arSize){
        System.out.println("Original Songs \\n" + (size-arSize));
    }else System.out.println("That CD does not exist in the collection, please try again");

答案 1 :(得分:0)

要使用binarysearch,您必须确保数组有序。你没有对songs进行排序,所以你没有得到预期的结果。我不知道你为什么要为你的歌名添加\n

另一种解决方案是先对数组进行排序。如下:

    ArrayList <String> songs = new ArrayList();
    Collections.addAll(songs, "Metric - Fantasies", "\nBeatles - Abbey Road", "\nPearl Jam - Ten", "\nDoors - Alive", "\nThe Rolling Stones - Gimme Shelter\n");
    Collections.sort(songs);//////sort the songs
   int remove = Collections.binarySearch(songs, artistinput.getText());
   if (remove < 0)
   {
        output.setText("That CD does not exist in the collection, please try again");
   }
  else if (remove >= 0)
  {
       boolean delete=songs.remove(artistinput.getText());{
       output.setText("Original Songs \n" +delete);
  }

答案 2 :(得分:0)

简单快捷的方法。我改变了你的输入和输出系统,但我猜这对你的班级来说很好。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class dumbshit{

public static void main(String args[]){

Scanner scan = new Scanner(System.in);

ArrayList<String> songs = new ArrayList<String>();
songs.add("Metric - Fantasies");
songs.add("Beatles - Abbey Road");
songs.add("Pearl Jam - Ten");
//etc
//this can obviously be done better
Collections.sort(songs);
int index = Collections.binarySearch(songs, scan.nextLine());
    if (index < 0)
    {
        System.out.println("That CD does not exist in the collection, please try again");
    }
    else if (index >= 0)
    {
        songs.remove(index);
        for(int i = 0; i < songs.size(); i++){
            System.out.println( songs.get(i) );
        }
    }
 }
}