2012-04-20 2 views
0

"삽입" "삭제" "검색"및 "인쇄"기능에서 비교를 계산하는 방법에 대한 정보를 얻고 싶습니다. 이 프로그램이 수반하는 것은 '학생'을 목록에 추가하고, 목록에서 삭제하고, 목록을 인쇄하고, 다른 기능을 추가 할 수 있다는 것입니다. 그러나 삽입, 삭제, 검색 및 인쇄시 얼마나 많은 비교가 이루어 졌는지 계산할 수 있어야합니다. 이 for 루프가 필요하다는 것을 알고 있지만, 제대로 이해하지 못합니다. 제안이 있습니까? 자바 프로젝트에서 비교 횟수를 계산하십시오.

다음

내 코드 (경고, 그것은 큰) :

int count; 

을하고 그것을마다 증가 :

import java.io.*; 
import java.util.*; 

import javax.swing.JOptionPane; 

public class Assignment3{ 
static String students = ""; //Records of matching students 
static int matches = 0; //Number of matching students 
static Set <Student> names = new HashSet<Student>(); //HashSet to store Students 

public static void main(String[] args) throws FileNotFoundException{ 

    int ID = 0;     
    String lastName;   
    double GPA;    
    boolean run = true; 

    while (run == true){ 
     String menu = JOptionPane.showInputDialog(null, "1) Loading students" + 
       "\n2) Adding new student" + 
       "\n3) Removing student " + 
       "\n4) Searching students" + 
       "\n5) Printing students " + 
       "\n6) Quit"); 

     //Loading students from a text file 
     if (menu.equals("1")){ 
      String inputFileName = JOptionPane.showInputDialog(null, "Input file:"); 
      File inputFile = new File(inputFileName); 
      Scanner in = new Scanner(inputFile); 

      while (in.hasNext()){ //Loading names from text file to array! 
       ID = in.nextInt(); 
       lastName = in.next(); 
       GPA = in.nextDouble(); 
       Student student = new Student(ID,lastName,GPA); 
       names.add(student); 
      } 
      in.close(); //Done loading from file, closing input! 
     } 

     //Adding more students to your list 
     if (menu.equals("2")){ 
      String idString = JOptionPane.showInputDialog(null, "Please Enter an ID for student"); 
      ID = Integer.parseInt(idString); 
      lastName = JOptionPane.showInputDialog(null, "Please enter a last name for student"); 
      String gpaString = JOptionPane.showInputDialog(null, "Please enter a GPA for student"); 
      GPA = Double.parseDouble(gpaString); 
      Student student = new Student(ID,lastName,GPA); 
      names.add(student); 
     } 

     //Remove student 
     if (menu.equals("3")){ 
      String idString = JOptionPane.showInputDialog(null, "Please enter an ID for student to remove"); 
      deleteStudentByID(Integer.parseInt(idString),names); 
     } 

     //Search 
     if (menu.equals("4")){ 
      String searchMenu = JOptionPane.showInputDialog(null, "1) Search by ID" + 
        "\n2) Search by name" + 
        "\n3) Search by GPA"); 


      if (searchMenu.equals("1")){ 


       int count = 0; 
       for (int n=1; n<ID; n++) 
        count++; // insert a[n] into a[0..(n-1)] 



       String idSearch = JOptionPane.showInputDialog(null, "Please enter ID number"); 
       JOptionPane.showMessageDialog(null, "Found " + (findStudentByID(Integer.parseInt(idSearch),names) + " Student\n" + students)); 
       System.out.println("The number of comparisons is " + count); 

      } 
      if (searchMenu.equals("2")){ 
       String nameSearch = JOptionPane.showInputDialog(null, "Enter last name"); 
       JOptionPane.showMessageDialog(null, "Found: " + findStudentByName(nameSearch,names) + "\n" + matches + " student(s) with last name of " + nameSearch); 
      } 
      if (searchMenu.equals("3")){ 



       String gpaSearch = JOptionPane.showInputDialog(null, "Enter GPA"); 
       JOptionPane.showMessageDialog(null, "Found " + (findStudentByGPA(Double.parseDouble(gpaSearch),names) + " Student(s)\n" + students)); 
      } 
     } 

     //Print 
     if (menu.equals("5")){ 
      String printMenu = JOptionPane.showInputDialog(null, "1) Print to console" + 
        "\n2) Print to file"); 
      //Console 
      if (printMenu.equals("1")){ 
       Iterator <Student> iter = names.iterator(); 
       while (iter.hasNext()){ 
        Student tempStudent = iter.next(); 
        System.out.println("ID: " + tempStudent.getID() + " Name: " + tempStudent.getName() + " GPA: " + tempStudent.getGPA() + " Hash Code: " + tempStudent.hashCode());  
       } 
       JOptionPane.showMessageDialog(null,"Output to console complete"); 
      } 
      //Text file 
      if (printMenu.equals("2")){ 
       String outputFileName = JOptionPane.showInputDialog(null, "Output file:"); 
       PrintWriter out = new PrintWriter(outputFileName); 
       Iterator <Student> iter = names.iterator(); 
       while (iter.hasNext()){ 
        Student tempStudent = iter.next(); 
        out.println("ID: " + tempStudent.getID() + " Name: " + tempStudent.getName() + " GPA: " + tempStudent.getGPA() + " Hash Code: " + tempStudent.hashCode());  
       } 
       out.close(); //Done writing to file, close output 
       JOptionPane.showMessageDialog(null,"Output saved to " + outputFileName); 
      } 
     } 

     //Quit 
     if (menu.equals("6")){ 
      System.exit(0); 
     } 
    } 
} 

//Delete a student 
static void deleteStudentByID(int id, Set <Student> list){ 
    matches = 0; 
    students = ""; 
    Iterator<Student> iterator = names.iterator(); 
    while (iterator.hasNext()) { 
     Student student = iterator.next(); 
     if (student.getIDHash() == Integer.toString(id).hashCode()){ 
      matches++; 
      students = "ID: " + student.getID() + " Name: " + student.getName() + " GPA: " + student.getGPA() + "\n"; 
      list.remove(student); 
      JOptionPane.showMessageDialog(null, "Deleted " + matches + " Student\n" + students); 
      break; 
     } 
    } 

    if (matches == 0){ 
     JOptionPane.showMessageDialog(null,"Student not found"); 
    } 
} 
//Search by ID 
static int findStudentByID(int id,Set <Student> list){ 
    matches = 0; 
    students = ""; 
    for (Student student : list){ 
     if (student.getIDHash() == Integer.toString(id).hashCode()){ 
      matches++; 
      students = "ID: " + student.getID() + " Name: " + student.getName() + " GPA: " + student.getGPA() + "\n"; 
     } 
    } 
    return matches; 
} 
//Search by name 
static String findStudentByName(String name,Set <Student> list){ 
    matches = 0; 
    students = ""; 
    for (Student student : list) { 
     if (student.getNameHash() == name.hashCode()){ 
      matches++; 
     } 
    } 
    if (matches > 0){ 
     return "YES"; 
    } 
    return "NO"; 
} 
//Search by GPA 
static double findStudentByGPA(double gpa,Set <Student> list){ 
    matches = 0; 
    students = ""; 
    for (Student student : list){ 
     if (student.getGPAHash() == Double.toString(gpa).hashCode()){ 
      matches++; 
      students += "ID: " + student.getID() + " Name: " + student.getName() + " GPA: " + student.getGPA() + "\n"; 
     } 
    } 
    return matches; 
} 

가}

답변

0

그냥 카운터 변수가 말 프로그램은 비교를합니다.

+0

맞습니다. int count와 for 루프가 필요하다는 것을 이해하지만, 어떻게 설정합니까? 예를 들어, for 루프가 있다면, count ++를 증가시킬 것이지만, 성으로 검색한다면 그것을 비교할 것입니다. 성은 문자열입니다. –

+0

@TrevorE'delete ...'와'find ...'메소드에서'while'과'for' 루프가 있습니다. – talnicolas

0

Abstract Method과 조합하여 Chain of Responsibility 패턴을 사용하는 것이 좋습니다.

즉, 예제는 전혀 객체 지향적이지 않습니다. 함수 프로그래밍을 사용하고 있기 때문에이 계산은 심각한 코드 중복을 의미합니다 (많은 곳에서 count++해야 함). Comparison 클래스와 AbstractComparison 구현의 체인을 도입하십시오.

+0

카운트를 어떻게 구현합니까? for 루프는 어떻게 설정 될까요? –

+0

카운트 ++는'ComparisonFactory # counted()'에 구현되고'AbstractComparison # counted()'에서 호출됩니다. 'for' 루프는 비교 사슬을 사용합니다 – yegor256

+0

샘플을 볼 수 있습니까? 아마도 lastName이나 GPA에 대한 것일까요? 나는 이것을 파악하지 못하고있다. –

관련 문제