/** * Copyright (c) 2015 Camil Staps * See the LICENSE file for copying permission. */ package com.camilstaps.shop; import java.io.InputStream; import java.io.PrintStream; import java.util.InputMismatchException; import java.util.Scanner; /** * Command Line Interface Interaction * @author Camil Staps, s4498062 */ public class CLIInteraction extends UserInteraction { private final Scanner in; private final PrintStream out; /** * Default is stdin and stdout */ public CLIInteraction() { this(System.in, System.out); } /** * CLI interaction with custom input and outputstream * @param is * @param ps */ public CLIInteraction(InputStream is, PrintStream ps) { in = new Scanner(is); out = ps; } @Override String getString() { return in.nextLine(); } @Override public int getChoice(String question, String[] options) { out.println(question); int i = 1; for (String option : options) { out.println(" " + (i++) + " : " + option); } int selection = 0; boolean read = false; do { if (read) { out.println("Invalid option. Try again:"); } try { selection = in.nextInt(); } catch (InputMismatchException ex) { } in.nextLine(); read = true; } while (selection < 1 || selection > options.length); return selection - 1; } @Override void putString(String string) { out.print(string); } @Override Command getCommand() { putString("► "); return new Command(getString()); } @Override float getFloat() { float result = in.nextFloat(); in.nextLine(); return result; } @Override boolean getBoolean() { putString(" (yes/no) "); String result; do { result = in.nextLine(); } while (!result.equalsIgnoreCase("yes") && !result.equalsIgnoreCase("no")); return result.equalsIgnoreCase("yes"); } }