Question

I have basically been asked to develop a small game in which the user selects numbers from two different lists. Once they have done that, a target number is generated randomly and using the numbers selected (total of 6) they must work with the numbers only as often as they appear to reach the target number, it is then checked and appropriately scored.

List<Integer> large = Arrays.asList(25, 50, 75, 100);
List<Integer> small = Arrays.asList(1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
            7, 7, 8, 8, 9, 9, 10, 10);

Okay so what I am aiming to do now is successfully parse a user input string, so that I can compare their working to a target number that was generated. They can only use the operators + - * /.

For example if they input: 99+1*3/2-1, I would want to parse that successfully to reach the target number.

I'm rather unsure of how to go about doing this, although I have attempted a bit of it, but can't get any further.

Scanner myAns = new Scanner(System.in);
                userInput = myAns.nextLine();
                String st = userInput;
                int result;
                for(int i=0;i<st.length();i++)
                {
                if(st.charAt(i)=='+')
                  {
                    result = Integer.parseInt(st.substring(0, i))+Integer.parseInt(st.substring(i+1, st.length()));

                  }

Any help would be greatly appreciated.

Was it helpful?

Solution

You can use String.split()

Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextLine();
String[] plusSplit = userInput.split("+");

You will then have an array where each element is added. So for example "3+4+5" will give you a String array of length 3 where the 1st element is 3, the second 4, the third 5.

You can perform nested splits in order of operator strength.

So split on division first (remember to cast to double to avoid truncation). Then for each element in your division split, split on multiplication. Then addition, subtraction, etc. You can then traverse backwards using Integer.parseInt()/Double.parseDouble to reverse engineer your values until you get back to your first operation.

This is not a trivial but fun exercise that will give you great practice with the String class, arrays, java operators, and using variables to hold your intermediate values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top