1

I'm a Java newbie, so I apologize in advance if this is trivial. But, I have a simple calculator that prints the cost of 'a' items by 'b' dollars, but if you have more than 'c' items, then it costs 'd' dollars. The code for that is:

Scanner sc = new Scanner(System.in);
    int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt(), d = sc.nextInt();

    if (a < b){
        System.out.printf("%d", a * c);
    }
    if (a == b){
        System.out.printf("%d", a * c);

    }
    if (a > b){
        System.out.printf("%d", a * d);
    }

but I'd like to add a bit more flexibility and avoid ambiguity, that is, the user inputs something like a=10 b=5 c=4 d=10 or b=5 d=10 a=10 c=4 (or any combination) all on one line, and the output is 100 for both. So, my question is how can I make it so that the order in which the user inputs the variables is arbitrary, all whilst keeping the same functionality?

TIA

dejsdukes
  • 159
  • 1
  • 10
  • Just a hint: Use meanimgful variable names. – dan1st Sep 18 '20 at 19:34
  • I think there are a few work around. You can have a print statement to let user know the correct order to input, or sequentially asking for what to input, or use conditional statement to analyze input, which will increase complexity of program. – Hung Vu Sep 18 '20 at 19:38

2 Answers2

1

You can do something like as follows:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scannner = new Scanner(System.in);
        System.out.println("Enter the values: ");
        String input = scannner.nextLine();// Scan the complete line

        // Split the input on whitespace
        String[] parts = input.split("\\s+");

        // Create a Map with parts
        Map<String, Integer> map = new HashMap<>();
        for (String part : parts) {
            // Split on '='
            String[] tokens = part.split("=");
            map.put(tokens[0], Integer.valueOf(tokens[1]));
        }

        // The following processing is similar to what you are already doing
        if (map.get("a") < map.get("b")) {
            System.out.printf("%d", map.get("a") * map.get("c"));
        }
        if (map.get("a") == map.get("b")) {
            System.out.printf("%d", map.get("a") * map.get("c"));

        }
        if (map.get("a") > map.get("b")) {
            System.out.printf("%d", map.get("a") * map.get("d"));
        }
    }
}

A sample run:

Enter the values: 
a=10 b=5 c=4 d=10
100

Another sample run:

Enter the values: 
b=5 d=10 a=10 c=4
100

Note: This solution is to guide you progress. There is a lot to be done (e.g. validations, exception handling etc.) in order to make it better.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

Try this:

import java.util.Scanner;

public class SimpleCalculatorScanner {
    public static void main(final String[] args) {
        Scanner sc = new Scanner(System.in);
        String[] variables = sc.nextLine().split(" ");
        int a = 0;
        int b = 0;
        int c = 0;
        int d = 0;
        for(int i = 0; i < variables.length; i++) {
        try {
            if(variables[i].substring(0, 2).equals("a=")) {
                a=Integer.parseInt(variables[i].substring(2));
            }else if(variables[i].substring(0, 2).equals("b=")) {
                b=Integer.parseInt(variables[i].substring(2));
            }else if(variables[i].substring(0, 2).equals("c=")) {
                c=Integer.parseInt(variables[i].substring(2));
            }else if(variables[i].substring(0, 2).equals("d=")){
                d=Integer.parseInt(variables[i].substring(2));
            }else {
                System.out.println("Unrecognized variable "+variables[i].substring(0, 1)+" detected");
                return;
            }
        }catch(NumberFormatException e) {
            System.out.println("The character you assigned to variable "+variables[i].substring(0, 1)+" isn't a number");
            return;
        }           }
        if (a < b){
            System.out.printf("%d", a * c);
        }
        if (a == b){
            System.out.printf("%d", a * c);

        }
        if (a > b){
            System.out.printf("%d", a * d);
        }
    }
}

Sample I/O

Input

b=5 d=10 a=10 c=4

Output

100

Input 2

b=5 d=10 e=10 c=4

Output 2

Unrecognized variable e detected

Input 3

a=10 b=5 c=4 d=iforgot

Output 3

The character you assigned to variable d isn't a number

How it works

The Scanner reads a new line, and then turns it into an array by splitting every space.

Once the variables have been stored into an array, we run a for loop to test whether the first 2 characters of each item of the array are a=, b=, c= or d=. If it is a=, then it parses the every character after the = of the item in the array into an integer, and assigns it to variable a, vice versa.

If it doesn't recognize the variable, it will print Unrecognized variable <variablename> detected.

If the character assigned to the variable wasn't a number, it will print The character you assigned to variable <variablename> isn't a number

Spectric
  • 30,714
  • 6
  • 20
  • 43
  • 1
    Sorry, I made a mistake in my explanation. It doesn't only parse the last character of the item in the array - it parses all characters after the `=` – Spectric Sep 18 '20 at 20:24