001package myproject.ui; 002 003import java.io.BufferedReader; 004import java.io.IOException; 005import java.io.InputStreamReader; 006import java.io.PrintStream; 007 008public final class TextUI implements UI { 009 final BufferedReader in; 010 final PrintStream out; 011 012 public TextUI() { 013 this.in = new BufferedReader(new InputStreamReader(System.in)); 014 this.out = System.out; 015 } 016 017 public void displayMessage(String message) { 018 out.println(message); 019 } 020 021 public void displayError(String message) { 022 out.println(message); 023 } 024 025 private String getResponse() { 026 String result; 027 try { 028 result = in.readLine(); 029 } catch (IOException e) { 030 throw new UIError(); // re-throw UIError 031 } 032 if (result == null) { 033 throw new UIError(); // input closed 034 } 035 return result; 036 } 037 038 public void processMenu(UIMenu menu) { 039 out.println(menu.getHeading()); 040 out.println("Enter choice by number:"); 041 042 for (int i = 1; i < menu.size(); i++) { 043 out.println(" " + i + ". " + menu.getPrompt(i)); 044 } 045 046 String response = getResponse(); 047 int selection; 048 try { 049 selection = Integer.parseInt(response, 10); 050 if ((selection < 0) || (selection >= menu.size())) 051 selection = 0; 052 } catch (NumberFormatException e) { 053 selection = 0; 054 } 055 056 menu.runAction(selection); 057 } 058 059 public String[] processForm(UIForm form) { 060 // TODO 061 return null; 062 } 063}