0
所以我想爲學校編寫一個程序。它的要點是要製作用戶在其收藏中的CD列表。該程序需要以原始順序(CDS)和按字母排序順序(CDSS)顯示CD列表。信息必須存儲在數組列表中。我也必須使用它能夠添加和刪除程序。爲什麼Collections.binarySearch不能一致地輸出
當我輸入歌曲「Beatles - Abbey Road」時,我認爲它會從collections.binarySearch輸出1,但是它會輸出-1兩次然後輸出1。它似乎適用於其他歌曲。
,因爲它創建了一個錯誤
感謝您的幫助
private void buttonInitializeActionPerformed(java.awt.event.ActionEvent evt) {
//this is where the original songs are added(when the initialize button is pressed)
Collections.addAll(CDS, "Metric - Fantasies", "Beatles - Abbey Road", "Pearl Jam - Ten", "Doors - Alive", "The Rolling Stones - Gimme Shelter");
Collections.addAll(CDSS, "Metric - Fantasies", "Beatles - Abbey Road", "Pearl Jam - Ten", "Doors - Alive", "The Rolling Stones - Gimme Shelter");
//once the initialize button is pressed the other buttong will be able to be enabled
buttonDisplay.setEnabled(true);
buttonRemove.setEnabled(true);
buttonAdd.setEnabled(true);
buttonInitialize.setEnabled(false);
}
private void buttonDisplayActionPerformed(java.awt.event.ActionEvent evt) {
outputSongList.setText("Original Order");
int condition = 0;
//condition is the value thatis increased by 1 every time each of these while loops are ran.
//from 1 to however many objects there are in the either the CDS or CDSS array list
//the extra S in CDSS stands for sorted
while(condition < CDS.size()){
outputSongList.setText(outputSongList.getText() + "\n" + CDS.get(condition));//writing the contents of the array list to the text area
condition++;
}
outputSongList.setText(outputSongList.getText() + "\n\n\nSorted Order");
Collections.sort(CDSS, String.CASE_INSENSITIVE_ORDER);//this sorts the CDSS array in alphabetical order
condition = 0;
while(condition < CDSS.size()){
outputSongList.setText(outputSongList.getText() + "\n" + CDSS.get(condition));//the same as the previous while loop
condition++;
}
buttonDisplay.setEnabled(false);//disables the display button so the user knows that all information is displayed
}
private void buttonAddActionPerformed(java.awt.event.ActionEvent evt) {
String inputSong = enterSong.getText();//getting the string that the user typed into the enterSong text field
if(Collections.binarySearch(CDS, inputSong) < 0){//this checks if the inputted song is in the arraylist
CDS.add(inputSong); //if it is, the outputted number will be 1...i thought
CDSS.add(inputSong); //if it isn't the numer will be less than 0
Collections.sort(CDSS); //this if statement will run if the inputted song isn't already in the arrays
buttonDisplay.setEnabled(true);
}
}
private void buttonRemoveActionPerformed(java.awt.event.ActionEvent evt) {
String inputSong = enterSong.getText();
if(Collections.binarySearch(CDS, inputSong) > -1){//if the inputted song is in the array this line will run
CDS.remove(Collections.binarySearch(CDS, inputSong));
CDSS.remove(Collections.binarySearch(CDS, inputSong));
buttonRemove.setEnabled(false);
buttonDisplay.setEnabled(true);
}
}
不完全確定你在問什麼。 – bowlturner