1

我正在开始 Java 课程,这是我的第一个代码,所以请温柔;)

//importing libraries
import java.io.*;
import javax.swing.*;

public class SongCollection {//class

//declaring arrays to hold user inputs
static String title[]={"","",""};
static String artist[]={"","",""};
static double length[]={0,0,0};

static int arrayindex=0;//declaring an index to keep track of arrays

public static void main(String[] args) throws IOException{//main method
    menu();//calling menu method
}

public static void menu() throws IOException{//menu method
    String s=JOptionPane.showInputDialog("Choose a menu option\n" +//taking user input and storing it into a string
            "1: Add Song\n" +
            "2: Search for a song\n" +
            "3: Edit a song\n" +
            "4: Sort songs\n" +
            "5: Print songs\n" +
            "6: Save songs to file\n" +
            "7: Read songs from file\n" +
            "8: Exit");
    int menu=Integer.parseInt(s);//converting user input into a number

    switch(menu){//going to the appropriate method depending on what number the user presses on the keyboard
    case 1: add(); break;
    case 2: search(); break;
    case 3: edit(); break;
    case 4: sort(); break;
    case 5: print(); break;
    case 6: tofile(); break;
    case 7: fromfile(); break;
    case 8: System.exit(0); break;
    default: JOptionPane.showMessageDialog(null,"Please choose a valid option"); break;
    }
}

public static void add() throws IOException{//add method
    if(arrayindex>=title.length){//checking if the array is full
        JOptionPane.showMessageDialog(null,"Song collection is full");
        menu();
    }

    //taking the user input and storing them into variables
    String newtitle=JOptionPane.showInputDialog("Enter the song title:");
    String newartist=JOptionPane.showInputDialog("Enter the artist of the song:");
    String s=JOptionPane.showInputDialog("Enter the length of the song:");
    double newlength=Double.parseDouble(s);//converting length into a number

    //taking the variables and storing them in the arrays
    title[arrayindex]=newtitle;
    artist[arrayindex]=newartist;
    length[arrayindex]=newlength;
    arrayindex+=1;//incrementing one to the array index because one new entry was added

    menu();
}

public static void search() throws IOException{//search method
    String key=JOptionPane.showInputDialog("Enter your search key: ");//taking in the users search key

    for(int i=0; i<title.length; i++){
        if(key.equals(title[i]) || key.equals(artist[i]) || key.equals(length[i])){//checking if the key is in any of the arrays
            JOptionPane.showMessageDialog(null,title[i]+", "+artist[i]+", "+length[i]);//printing out the found key
            menu();
        }
    }
    JOptionPane.showMessageDialog(null,"Key not found");//if the loop completes the key doesnt exist
}

public static void edit() throws IOException{//edit method
    String s=JOptionPane.showInputDialog("Which entry do you want to edit. Enter a whole number between 0 and " + (arrayindex-1));//asking the user which entry they want to edit
    int edit=Integer.parseInt(s);//converting user input into a number

    if(edit>arrayindex || edit<0){//checking if they enter a valid entry that can be editted
        JOptionPane.showMessageDialog(null,"The entry you entered is does not exist");
        menu();
    }

    //taking new entries from the user
    String newtitle=JOptionPane.showInputDialog("Enter the new song title:");
    String newartist=JOptionPane.showInputDialog("Enter the new artist of the song:");
    String s2=JOptionPane.showInputDialog("Enter the new length of the song:");
    double newlength=Double.parseDouble(s2);

    //storing them into the array replacing what was previously stored in that index
    title[edit]=newtitle;
    artist[edit]=newartist;
    length[edit]=newlength;
    menu();
}

public static void sort(){//sort method
    //nested loop to loop through all elements and make swap when needed
    for(int i=0; i<title.length-1; i++)
    {
        for (int i1=0; i1<title.length-1; i1++)
        {
            //storing title current index and title next into 2 different variables
            String t1 = title[i1];
            String t2 = title[i1 + 1];

            //storing artist current index and artist next index into 2 different variables
            String a1 = artist[i1];
            String a2 = artist[i1 + 1];

            //storing length current index and length next index into 2 different variables
            double l1 = length[i1];
            double l2 = length[i1 + 1];

            //comparing title current index with title next index using the compareto method
            if ((t1).compareTo(t2) > 0)
            {
                //creating a temporary variable to store the first variable and then swapping the 2 around
                String t3 = t1;
                title[i1] = t2;
                title[i1 + 1] = t3;

                String a3 = a1;
                artist[i1] = a2;
                artist[i1 + 1] = a3;

                Double l3 = l1;
                length[i1] = l2;
                length[i1 + 1] = l3;
            }
        }
    }
}

public static void print() throws IOException{//print method
    //looping through and printing out each element
    for(int i=0; i<title.length; i++)
    {
        JOptionPane.showMessageDialog(null,title[i]+","+artist[i]+","+length[i]);
    }
    menu();
}

public static void tofile() throws IOException{//tofile method
    final FileWriter fw=new FileWriter("SongCollection.txt");//declaring filewriter
    final BufferedWriter bw=new BufferedWriter(fw);//delcaring buffer
    final PrintWriter pw=new PrintWriter(bw);//declaring print writer

    //looping through array
    for(int i=0; i<title.length; i++)
    {
        pw.println(title[i]+","+artist[i]+","+length[i]);//using print writer to write all 3 elements on one line
    }
    pw.close();//closing the writer
    menu();
}

public static void fromfile() throws IOException{//from file method
    final FileReader inf=new FileReader("SongCollection.txt");//declaring file reader
    final BufferedReader ib=new BufferedReader(inf);//declaring buffer reader
    String s;//string to hold read lines from file

    while((s=ib.readLine())!=null)//looping through the file while the lines are not empty
    {
        JOptionPane.showMessageDialog(null,s);//outputting the read in data to the screen   
    }
}
 }

我有一些问题:

如何让添加歌曲界面有返回主菜单的按钮?其他接口类似吗?

4

2 回答 2

4

这是一个典型的新手错误:你的班级做得太多了。把事情分解一下。

有一个将事物封装在一起的 Song 类:

package model;

public class Song {
    private String title;
    private String author;
    private int length;
    // You add the rest.
}

不要使用基元数组;改用Java 集合

从模型类中分离出 UI 的东西。无需重写所有代码即可更改 UI。

于 2012-04-22T14:50:58.957 回答
2

你真的应该使用 Vector 或 ArrayList,而不是那些 String[] 数组。否则,您基本上是在说用户不可能输入三个以上的输入。即使他们可以,您也必须调整数组的大小,或者您会遇到 arrayoutofbounds 异常。

通过声明 Vector 或 ArrayList,您可以继续添加元素(虽然您仍然有可用内存),并且它可以防止原始字符串数组可能引发的数组越界异常。

于 2012-04-22T16:55:24.817 回答