2011-12-11 3 views
0

Ok이 코드는 컴파일 중이지만 논리 오류가 있습니다. 좋아, 그럼 내가 읽고 싶은 데이터가있는 파일을 입력하고 난 다른 파일을로드 할 수있는 선택의 여지가 화면에 그 데이터를 인쇄하도록 선택합니다. 그러나 내가로드하고자하는 새 파일의 이름을 입력하면 출력 된 특정 상황에 대해 지정된 파일과 오류 메시지가로드되지 않습니다. 나는 각 쓰기 또는 그와 비슷한 것을 한 후에 스트림 버퍼를 플러시해야한다고 생각한다. 음, 왜 누군가가 이런 일이 일어 났는지 지적 할 수 있으면 감사하겠습니다.이전 파일을 인쇄 한 후 java에서 다른 파일을 다시로드하는 방법

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

public class Driver { 
    private static int numberOfCustomer = 0; 
    private static Customer[] customerList = new Customer[10]; 

     private static void readInCustomer(String file){ 
     FileReader freader; 
     BufferedReader inputFile; 
     try{ 
      freader = new FileReader(file); 
      inputFile = new BufferedReader(freader); 
      String strLine; 


      while ((strLine = inputFile.readLine()) != null) { 
        customerList[numberOfCustomer] = new Customer(); 
        customerList[numberOfCustomer].ID = strLine; 
        customerList[numberOfCustomer].name =     inputFile.readLine(); 
        customerList[numberOfCustomer].address = inputFile.readLine(); 
        customerList[numberOfCustomer].phone = inputFile.readLine(); 
        numberOfCustomer++; 
      } 

      inputFile.close(); 
     }catch(Exception e){ 
      System.out.println("Could not find file "+file+" System will now exit"); 
      System.exit(1); 

     } 

     return; 
    } 

     private static void printCustomer(Customer customer){ 
     System.out.println("The Customer Data corresponding to Customer Number " + customer.ID + " is:"); 
     System.out.println("Name:\t\t\t"+customer.name); 
     System.out.println("Address:\t\t"+customer.address); 
     System.out.println("Telephone:\t\t"+customer.phone); 
     System.out.println(); 
     return; 
    } 

     private static void printAll(){ 
     boolean hasID = false; 
      Scanner keyboard = new Scanner(System.in); 

     System.out.println("All customers from data file "+numberOfCustomer); 


     System.out.println(" Here they are!!! "); 
     for(int i=0; i<numberOfCustomer; i++){ 
      if(customerList[i] != null){ 
       System.out.println("The Customer Data corresponding to Customer Number " + customerList[i].ID + " is:"); 
       System.out.println("Name:\t\t\t"+customerList[i].name); 
       System.out.println("Address:\t\t"+customerList[i].address); 
       System.out.println("Telephone:\t\t"+customerList[i].phone); 
      } 
     } 
     if(!hasID){ 

     System.out.println(""); 
     } 
     System.out.println("Would you like to go to the menu? (Y or N):"); 
     String input = keyboard.nextLine(); 
     char repeat = input.charAt(0); 
     if(repeat == 'Y' || repeat == 'y'){Menu();} 
        return; 
    } 

    private static void Menu(){ 
     boolean hasID = false; 
     Scanner keyboard = new Scanner(System.in); 

     System.out.println("YOU MAY CHOOSE FROM THE FOLLOWING OPTIONS:"); 
     System.out.println("A. SEARCH for a customer by ID number"); 
     System.out.println("B. DISPLAY the entire Customer List"); 
     System.out.println("C. RE-LOAD DATA from a different data file"); 
     System.out.println("D. QUIT:"); 

     String choice = keyboard.nextLine(); 

     char repeat = choice.charAt(0); 
     if(repeat == 'A' || repeat == 'a'){Scostomer();} 
      if(repeat == 'B' || repeat == 'b'){printAll();} 
      if(repeat == 'C' || repeat == 'c'){mainn();} 
       return; 

     } 

    public static void Scostomer(){ 
    boolean hasID = false; 
     Scanner keyboard = new Scanner(System.in); 

     System.out.println("Type in the Id you are search for"); 

     String customerID = keyboard.nextLine(); 

     for(int i=0; i<numberOfCustomer; i++){ 
      if((customerList[i]!=null) && (customerID.equals(customerList[i].ID))){ 
       hasID = true; 
       printCustomer(customerList[i]); 
       i=customerList.length; 
      } 
     } 

     if(!hasID){ 
      System.out.println("Sorry, customer not found."); 
     } 
     System.out.println("Would you like to search for another custnomer? (Y or N):"); 
     String input = keyboard.nextLine(); 
     char repeat = input.charAt(0); 
     if(repeat == 'Y' || repeat == 'y'){Scostomer();} 
      if(repeat == 'N' || repeat == 'n'){Menu();} 
        return; 
    } 

    public static void main(String arg[]){ 
     Scanner keyboard = new Scanner(System.in); 
      System.out.println("Enter the fileName that contains the data of your customers: "); 
     readInCustomer(keyboard.nextLine()); 
     Menu(); 
     return; 
     } 

    public static void mainn(){ 
     Scanner keyboard = new Scanner(System.in); 

      System.out.println("Enter the fileName that contains the data of your customers: "); 
     readInCustomer(keyboard.nextLine()); 
     Menu(); 
     return; 

    } 
} 
+0

시도가'readInCustomer''의 catch 블록에서 'e.printStackTrace()을 넣고 귀하의 질문에 그 흔적을 넣어하지 않을 경우 다음 문제를 찾을거야 희망? – havexz

+0

코드가 완벽하게 작동합니다. 올바른 파일 경로와 올바르게 입력했는지 확인하십시오. –

+0

제가 문제는 두 번째 txt 파일에로드하려는 길이가 길어서 개인 정적 Customer [] customerList = new Customer [10]을 늘려야한다는 것입니다. 개인 정적 고객에게 [] customerList = 새 고객 [30]; – user1091869

답변

0

나를 위해 작동합니다 (파일을로드하고, c를 입력하여 새 파일을로드하고, b를 입력하여 모두 표시). 나는 뭔가 간단한 오류 (잘못된 파일명 또는 어리석은 것)가 있음을 제안하므로 catch 블록에서 무시하는 대신 예외 세부 정보를 기록하려고합니다. 당신이 쓰고,를하지 읽는만큼

} catch(Exception e) { 
     e.printStackTrace(); // should tell you what's wrong! 
     System.out.println("Could not find file "+file+" System will now exit"); 
     System.exit(1); 

    } 

플러싱 여기에 관련이 없습니다. 아마 전체 메뉴/입력 루프를 정리할 수도 있습니다. 조금 엉망입니다 (하지만 작동합니다!). 예를 들어, 주간 방법은 동일합니다. 분리 된 방법으로 추상화 한 것으로 간주 했습니까?

자신을 10 명의 고객으로 제한하는 대신 목록을 사용할 수 있으며 읽는 고객 수에 대해 걱정할 필요가 없습니다. 배열 대신 목록을 사용하도록 코드를 변경했을뿐입니다. :

import java.io.BufferedReader; 
import java.io.FileReader; 
import java.util.ArrayList; 
import java.util.List; 
import java.util.Scanner; 

public class Driver { 
    private static int numberOfCustomer = 0; 
    // List instead of array! 
    private static List<Customer> customerList = new ArrayList<Customer>(); 

    private static void readInCustomer(String file) { 
     FileReader freader; 
     BufferedReader inputFile; 
     try { 
      freader = new FileReader(file); 
      inputFile = new BufferedReader(freader); 
      String strLine; 

      while ((strLine = inputFile.readLine()) != null) { 
       Customer customer = new Customer(); 
       customer.ID = strLine; 
       customer.name = inputFile.readLine(); 
       customer.address = inputFile.readLine(); 
       customer.phone = inputFile.readLine(); 
       customerList.add(customer); // add to the List! 
      } 

      inputFile.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      System.out.println("Could not find file " + file 
        + " System will now exit"); 
      System.exit(1); 

     } 

     return; 
    } 

    private static void printCustomer(Customer customer) { 
     System.out 
       .println("The Customer Data corresponding to Customer Number " 
         + customer.ID + " is:"); 
     System.out.println("Name:\t\t\t" + customer.name); 
     System.out.println("Address:\t\t" + customer.address); 
     System.out.println("Telephone:\t\t" + customer.phone); 
     System.out.println(); 
     return; 
    } 

    private static void printAll() { 
     boolean hasID = false; 
     Scanner keyboard = new Scanner(System.in); 

     System.out.println("All customers from data file " + numberOfCustomer); 

     System.out.println(" Here they are!!! "); 
     for (Customer customer : customerList) { 
      System.out 
        .println("The Customer Data corresponding to Customer Number " 
          + customer.ID + " is:"); 
      System.out.println("Name:\t\t\t" + customer.name); 
      System.out.println("Address:\t\t" + customer.address); 
      System.out.println("Telephone:\t\t" + customer.phone); 
     } 

     if (!hasID) { 
      System.out.println(""); 
     } 
     System.out.println("Would you like to go to the menu? (Y or N):"); 
     String input = keyboard.nextLine(); 
     char repeat = input.charAt(0); 
     if (repeat == 'Y' || repeat == 'y') { 
      Menu(); 
     } 
     return; 
    } 

    private static void Menu() { 
     boolean hasID = false; 
     Scanner keyboard = new Scanner(System.in); 

     System.out.println("YOU MAY CHOOSE FROM THE FOLLOWING OPTIONS:"); 
     System.out.println("A. SEARCH for a customer by ID number"); 
     System.out.println("B. DISPLAY the entire Customer List"); 
     System.out.println("C. RE-LOAD DATA from a different data file"); 
     System.out.println("D. QUIT:"); 

     String choice = keyboard.nextLine(); 

     char repeat = choice.charAt(0); 
     if (repeat == 'A' || repeat == 'a') { 
      Scostomer(); 
     } 
     if (repeat == 'B' || repeat == 'b') { 
      printAll(); 
     } 
     if (repeat == 'C' || repeat == 'c') { 
      mainn(); 
     } 
     return; 

    } 

    public static void Scostomer() { 
     boolean hasID = false; 
     Scanner keyboard = new Scanner(System.in); 

     System.out.println("Type in the Id you are search for"); 

     String customerID = keyboard.nextLine(); 

     // iterate over the List! 
     for (Customer customer : customerList) { 
      if (customerID.equals(customer.ID)) { 
       hasID = true; 
       printCustomer(customer); 
       break; 
      } 
     } 

     if (!hasID) { 
      System.out.println("Sorry, customer not found."); 
     } 
     System.out 
       .println("Would you like to search for another custnomer? (Y or N):"); 
     String input = keyboard.nextLine(); 
     char repeat = input.charAt(0); 
     if (repeat == 'Y' || repeat == 'y') { 
      Scostomer(); 
     } 
     if (repeat == 'N' || repeat == 'n') { 
      Menu(); 
     } 
     return; 
    } 

    public static void main(String arg[]) { 
     Scanner keyboard = new Scanner(System.in); 
     System.out 
       .println("Enter the fileName that contains the data of your customers: "); 
     readInCustomer(keyboard.nextLine()); 
     Menu(); 
     return; 
    } 

    public static void mainn() { 
     Scanner keyboard = new Scanner(System.in); 

     System.out 
       .println("Enter the fileName that contains the data of your customers: "); 
     readInCustomer(keyboard.nextLine()); 
     Menu(); 
     return; 

    } 
} 
+0

와우 감사합니다. 나는 e.printStackTrace()를 보았다. 좋은 전에 그것은 내게이 오류를 준 java.lang.ArrayIndexOutOfBoundsException : 10-30에서 번호를 inscreaase 그래서 Driver.readInCustomer (Driver.java:33)에서 10 \t 그리고 그게 작동 – user1091869

+0

당신은 컬렉션 (예 : 목록) 배열이 아니라 최대 10 명의 고객이 있다고 보장 할 수없는 경우 –

+0

그러나 System.out으로 인쇄하고 e.printStackTrace()를 사용하면 일반적으로 frowned - commmons-logging, slf4j 등의 로깅 프레임 워크가 권장됩니다. 그러나 신속하고 더러운 로깅 또는 독립 실행 형 명령 줄 응용 프로그램에서는 문제가 없습니다. –

관련 문제