aboutsummaryrefslogtreecommitdiff
path: root/Week9 Webshop/src/com/camilstaps/shop/CLIInteraction.java
diff options
context:
space:
mode:
Diffstat (limited to 'Week9 Webshop/src/com/camilstaps/shop/CLIInteraction.java')
-rw-r--r--Week9 Webshop/src/com/camilstaps/shop/CLIInteraction.java94
1 files changed, 94 insertions, 0 deletions
diff --git a/Week9 Webshop/src/com/camilstaps/shop/CLIInteraction.java b/Week9 Webshop/src/com/camilstaps/shop/CLIInteraction.java
new file mode 100644
index 0000000..cbf59ab
--- /dev/null
+++ b/Week9 Webshop/src/com/camilstaps/shop/CLIInteraction.java
@@ -0,0 +1,94 @@
+/**
+ * Copyright (c) 2015 Camil Staps <info@camilstaps.nl>
+ * 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");
+ }
+} \ No newline at end of file