2016-06-18 3 views
0

나는 자바를 배우고 간단한 전화 번호부를 만들고있다. 이 부분에서는 아래의 3 가지 옵션 중 하나를 선택하라는 메시지를 표시하려고합니다. "아닌 문 오류"라고기본 자바 전화 번호부 만들기

public class PhoneBook { 

    public static void main (String[] args){ 
     options();  
     /*This method prompts the user to enter phone number 
     String s; 
     Scanner in = new Scanner(System.in); 
     System.out.println("Enter Phone Number"); 
     s = in.nextLine(); 
     System.out.println("You entered phone number "); 
     System.out.println(s);*/ 
    } 

    public static void options(){ 
    //This method gives the user choices on what to do 

     char choice; 
     char enterNumber = 'n'; 
     char showNumber = 's'; 
     char closeBook = 'c'; 

     String read; 
     String freeLine = "error"; 
     Scanner keyboard = new Scanner(System.in); 
     while (true){ 

      System.out.println("Please select from the following"); 
      System.out.println("n to Enter the number"); 
      System.out.println("s to Show the number "); 
      System.out.println("c to Close the Phone book"); 

     read = keyboard.nextLine(); 
     choice = read.charAt(0); 
     switch (choice) { 
     case 'n': enterNumber; 
       system.out.println(); 
     case 's':showNumber; 
       system.out.println(); 
     case 'c': closeBook; 
        break; 
     default: System.out.println("Invalid Entry"); 


     } 
     } 
    } 

} 

내가 컴파일 할 때 내가 선 (37), (39)에 에러가 발생, 41. 뭔가 빠진 것 같아. 누구든지 도움을받을 수 있다면 크게 감사하겠습니다.

+0

라인 37은 어느 라인입니까? – Timo

+3

'case '가 무엇을 기대합니까 : showNumber;'할일? – njzk2

+0

이 전화 번호부는 어떻게 이해가되지 않습니다. 그것은 나에게 뭔가를 입력하고 그것을 인쇄하거나 일종의 "에코"복제물로 보입니다. – ifly6

답변

1

콘솔에 enterNumbern 문자를 인쇄하려면 다음 행을 사용한다고 가정합니다.

case 'n': enterNumber; 
      system.out.println(); 

올바른 Java 구문이 아닙니다. System.out.println 메서드 호출에 변수 값을 전달할 수는있을 것이다 :

case 'n': System.out.println(enterNumber); 

는 또한 자바는 대소 문자를 구별하므로 당신은 대문자로 System을 주문해야합니다. 당신이 '후 변수를 작성할 필요가 없습니다

switch (choice) { 
    case 'n': System.out.println(enterNumber); 
       break; 
    case 's': System.out.println(showNumber); 
       break; 
    case 'c': System.out.println(closeBook); 
       break; 
    default: System.out.println("Invalid Entry"); 
} 
+0

나는 그것을 실행했고 선택을 복제했다. 예를 들어 내가 "n"을 넣을 선택을 할 때처럼. 숫자를 입력 할 수 있도록 빈 줄을 제공해야하지만 대신 선택 텍스트를 반복하는 것입니다. – NekaB

0

: 보조 노트에

, 당신은 그렇지 않으면 다음과 같은 경우의 코드뿐만 아니라 실행됩니다, 당신 case 문장의 각 후 break;하기를 원할 것입니다 캐스트 '진술.

아래 코드를 참조하십시오.

import java.util.Scanner; 

public class PhoneBook { 


    public static void main (String[] args){ 
     options();  
     /*This method prompts the user to enter phone number 
     String s; 
     Scanner in = new Scanner(System.in); 
     System.out.println("Enter Phone Number"); 
     s = in.nextLine(); 
     System.out.println("You entered phone number "); 
     System.out.println(s);*/ 
    } 

    public static void options(){ 
    //This method gives the user choices on what to do 

     char choice; 
     char enterNumber = 'n'; 
     char showNumber = 's'; 
     char closeBook = 'c'; 

     String read; 
     String freeLine = "error"; 
     Scanner keyboard = new Scanner(System.in); 
     while (true){ 

      System.out.println("Please select from the following"); 
      System.out.println("n to Enter the number"); 
      System.out.println("s to Show the number "); 
      System.out.println("c to Close the Phone book"); 

     read = keyboard.nextLine(); 
     choice = read.charAt(0); 
     switch (choice) { 
     case 'n': 
     System.out.println(); 
     case 's': 
     System.out.println(); 
     case 'c': 
        break; 
     default: System.out.println("Invalid Entry"); 


     } 
     } 
    } 

} 
+0

코드에 "캐스트"가 없습니다. 그리고 코드는 빈 줄만 인쇄합니다. – Sekkuar

0

나는 당신을 위해 특별한 대답을했습니다. 나는 추가적인 설명을 추가하지 않는다. 그것은 큰 대답입니다. 당신이 묻는 것 이상을 말하지만, 나는 읽을 수있는 코드를 만들기 위해 최선을 다 했으므로 전화 번호부 (콘솔 테스트 드라이브 응용 프로그램)를 만들 때 최소한 필요한 것을 이해하기 위해 단계별로 분석 할 수 있습니다. . 더 자세한 설명이 필요한 경우 의견 아래에 작성하십시오.

첫째는 PhoneEntry 클래스합니다

import java.util.Objects; 

public class PhoneEntry implements Comparable<PhoneEntry> { 
    // https://jex.im/regulex/#!embed=false&flags=&re=%5E%5Ba-zA-Z%5D%7B2%2C%7D((-%7C%5Cs)%5Ba-zA-Z%5D%7B2%2C%7D)*%24 
    private static final String NAME_PATTERN = "^[a-zA-Z]{2,}((\\-|\\s)[a-zA-Z]{2,})*$"; 

    // https://jex.im/regulex/#!embed=false&flags=&re=%5E%5C%2B%3F%5Cd%2B((%5Cs%7C%5C-)%3F%5Cd%2B)%2B%24 
    private static final String NUMBER_PATTERN = "^\\+?\\d+((\\s|\\-)?\\d+)+$"; //^\+?\d+((\s|\-)?\d+)+$ 

    private final String name; 
    private final String number; 

    public PhoneEntry(String name, String number) { 
     if (!name.matches(NAME_PATTERN) || !number.matches(NUMBER_PATTERN)) { 
      throw new IllegalArgumentException(); 
     } 
     this.name = name; 
     this.number = number; 
    } 

    public String getName() { 
     return name; 
    } 

    public String getNumber() { 
     return number; 
    } 

    public boolean nameContainsIgnoreCase(String keyword) { 
     return (keyword != null) 
       ? name.toLowerCase().contains(keyword.toLowerCase()) 
       : true; 
    } 

    @Override 
    public boolean equals(Object obj) { 
     if (obj == null) { 
      return false; 
     } 
     if (!(obj instanceof PhoneEntry)) { 
      return false; 
     } 
     PhoneEntry phoneEntry = (PhoneEntry) obj; 
     return name.equalsIgnoreCase(phoneEntry.name) 
       && number.equalsIgnoreCase(phoneEntry.number); 
    } 

    @Override 
    public int hashCode() { 
     int hash = 5; 
     hash = 17 * hash + Objects.hashCode(this.name.toLowerCase()); 
     hash = 17 * hash + Objects.hashCode(this.number.toLowerCase()); 
     return hash; 
    } 

    @Override 
    public int compareTo(PhoneEntry phoneEntry) { 
     return name.compareToIgnoreCase(phoneEntry.name); 
    } 
} 

public class TestDrive { 

    private static final String choices = "nspc"; 

    enum Choice { 
     CREATE, READ, PRINT, CLOSE; 

     static Choice getChoice(char c) { 
      switch (c) { 
       case 'n': 
        return Choice.CREATE; 
       case 's': 
        return Choice.READ; 
       case 'p': 
        return Choice.PRINT; 
       case 'c': 
        return Choice.CLOSE; 
      } 
      return null; 
     } 
    } 

    // Main 
    public static void main(String[] args) { 
     Scanner kbd = new Scanner(System.in); 
     final Set<PhoneEntry> entries = new TreeSet<>(); 
     Choice choice; 
     while ((choice = getChoice(kbd)) != Choice.CLOSE) { 
      switch (choice) { 
       case CREATE: 
        PhoneEntry entry = getPhoneEntry(kbd); 
        if (entry != null) { 
         entries.add(entry); 
        } 
        break; 
       case READ: 
        print(readEntries(entries, kbd)); 
        break; 
       case PRINT: 
        print(entries); 
        break; 
      } 
     } 
    } 

    private static Choice getChoice(Scanner kbd) { 
     System.out.println("\nPlease select from the following"); 
     System.out.println("\tn to Enter the number"); 
     System.out.println("\ts to Show numbers by keyword "); 
     System.out.println("\tp to Show all numbers "); 
     System.out.println("\tc to Close the Phone book"); 
     System.out.print("> "); 
     String input = kbd.nextLine(); 
     Choice choice = null; 
     if (!input.isEmpty() 
       && choices.contains(input.toLowerCase()) 
       && ((choice = Choice.getChoice(input.toLowerCase().charAt(0))) != null)) { 
      return choice; 
     } 
     System.out.println("ERR: INVALID ENTRY. TRY AGAIN"); 
     return getChoice(kbd); 
    } 

    private static PhoneEntry getPhoneEntry(Scanner kbd) { 
     System.out.print("Type contact name: "); 
     String name = kbd.nextLine(); 
     System.out.print("Type phone number: "); 
     String number = kbd.nextLine(); 
     try { 
      return new PhoneEntry(name, number); 
     } catch (IllegalArgumentException ex) { 
      System.out.println("\nERR: WRONG ENTRY"); 
     } 
     return null; 
    } 

    private static void print(Set<PhoneEntry> entries) { 
     System.out.println("\nPHONE NUMBERS\n"); 
     entries.stream().forEach(entry -> { 
      System.out.printf("Name: %s%nPhone: %s%n%n", 
        entry.getName(), entry.getNumber()); 
     }); 
    } 

    private static Set<PhoneEntry> readEntries(Set<PhoneEntry> entries, Scanner kbd) { 
     System.out.print("Type keyword: "); 
     return entries.stream().filter(entry 
        -> entry.nameContainsIgnoreCase(kbd.nextLine())) 
       .collect(Collectors.toCollection(TreeSet::new)); 
    } 
} 
+0

감사합니다! 이것은 정말로 진보 된 것처럼 보이지만 나는 나의 책을 가지고 있으므로 확실히 이해할 수있을 것입니다. – NekaB

+0

Whoa man, 그것은 지금 그들이있는 곳보다 3 단 계단 앞에 있습니다. – Sekkuar

+0

나는 그저 나쁜 예가 있다고 생각합니다. 예제와 연습은 조금만 현실적이어야합니다. 전화 번호부에 대해 이야기 할 때, 전화 번호부에 전화 번호를 추가하는 것에 관한 번호를 표시하는 경우, 이것은 최소한 기대할 수있는 것입니다. – LowLevel

0

대신 enterNumber;의 다음 테스트 드라이브를, 당신은 enterNumber();를 작성해야합니다.

괄호의 의미 : 메서드를 호출합니다.

+0

감사합니다. 나는 그것을 놓쳤다. 나는 그것을 나의 메모에 추가하고있다 :) – NekaB