aboutsummaryrefslogtreecommitdiff
path: root/Week9 Webshop/src/com/camilstaps/shop/CLIInteraction.java
blob: cbf59ab29bbe4e4193c3bf9ada38da55f98d77f6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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");
    }
}