2

I'm trying to create a program that will calculate user input in the forms of: fractions, mixed fractions, and decimals. I have no problems with fractions input, what I do have is with the mixed fractions, and decimals.

import java.util.Scanner;

public class Fraction {

    public static int gcd(int a, int b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        //ignore all non-numerical input
        //how to detect if that non-numerical input is '/' or '.', or ' ' (blank space)?
        scan.useDelimiter("\\D");

        int num, den;
        num = scan.nextInt();
        den = scan.nextInt();

        int GCD = gcd(num, den);
        num = num / GCD;
        den = den / GCD;

        if (den == 0) {
            System.out.println("Invalid denominator, cannot divide by 0");
        } else {
            System.out.println("Fraction: "+num+"/"+den);
            if (num > den) {
                System.out.println("Mixed Fraction: "+(num / den)+" "+(num % den)+"/"+den);
            } else {
                System.out.println("Mixed Fraction: N/A");
            }
            System.out.println("Decimal: "+((double) num / (double) den));
        }

        scan.close();

    }
}

Right now, I can only input a fraction, and not mixed fraction or decimal. Here's an example of a correct output from a fraction input:

Input:
46/22

Output:
Fraction: 23/11
Mixed Fraction: 2 1/11
Decimal: 2.090909090909091

I need to create one where the program can automatically detect if the non-numerical input is either '/', ' ' (blank space), or '.' to differentiate fractions, mixed fractions, and decimals. Is there any way I could do that?

Note: I'm fairly new to Java, and the only other language I've learned is C.

2
  • 3
    You should read the whole line as a String and then work on that. You could simply iterate over all the characters and decide what the input is based on that. Commented Mar 20, 2020 at 8:38
  • It would be the same in C.... Commented Mar 20, 2020 at 8:39

2 Answers 2

1

Suggestion:

  • read the whole line of user input (scanner.nextLine())
  • use regular expressions (Pattern and Matcher) to detect which input case it is (fraction, mixed fraction, decimal).
  • in case of a match, extract the values using capturing groups
  • in case none of the cases match, tell the user that the input format is invalid.

The patterns you need are following:

Pattern DECIMAL = Pattern.compile("\\s*(-?\\d+(?:\\.\\d+)?)\\s*");
Pattern FRACTION = Pattern.compile("\\s*(-?\\d+)\\s*\\/\\s*(\\d+)\\s*");
Pattern MIXED_FRACTION = Pattern.compile("\\s*(-?\\d+)\\s+(\\d+)\\s*\\/\\s*(\\d+)\\s*");

Hint: the patterns also accept negative values such as -3.14, -5/8 and -2 1/3), and are lenient towards whitespaces (-2 3 / 4 is the same as -2 3/4).

Matching and extracting the values:

String line = scanner.nextLine();

Matcher matcher = DECIMAL.matcher(line);
if (matcher.matches()) {
    System.out.println("Decimal: " + matcher.group(1));
}
matcher = FRACTION.matcher(line);
if (matcher.matches()) {
    System.out.println("Fraction: " + matcher.group(1) + "/" + matcher.group(2));
}
matcher = MIXED_FRACTION.matcher(line);
if (matcher.matches()) {
    System.out.println("Mixed Fraction: " + matcher.group(1) + " " + matcher.group(2) + "/" + matcher.group(3));
}

Hint: if you're new to regular expressions, and want to understand what each part of it does, or you want to build and test them, there's many useful online tools to work with, e.g. regex101.com. Just make sure to remove the escaped backslashes (\\ -> \) when pasting expression from Java code into these tools.

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

if you just want to read in as normal fraction only, you can use a Delimiter (e.g scan.useDelimiter("/"); ) But if you want to be able to read in different input, you will have to work with a string, as showed as full solution in following code:

import java.util.Scanner;

public class Fraction {

    public static int gcd(int a, int b) {
        if (b == 0) {
            return a;
        }
        return gcd(b, a % b);
    }

    public static void main(String[] args) {
        boolean run = true;
        Scanner scan = new Scanner(System.in);
        scan.useDelimiter(System.lineSeparator());
        do {
            String input = scan.next();
            int num = 0, den = 0;
            if (input.matches("-?\\d*\\.\\d*")) {
                // input is floating point number... convert it, may
                // https://stackoverflow.com/a/26084714/12558456 fits better for you
                String[] splittedinput = input.split("\\.");
                num = Integer.parseInt(splittedinput[0] + splittedinput[1]);
                den = (int) Math.pow(10, splittedinput[1].length());

            } else if (input.matches("-?\\d* \\d*/\\d*")) {
                String[] splittedinput = input.split("/");
                String[] splittedfront = splittedinput[0].split(" ");
                den = Integer.parseInt(splittedinput[1]);
                num = Integer.parseInt(splittedfront[0]) * den + Integer.parseInt(splittedfront[1]);
            } else if (input.matches("-?\\d*/\\d*")) {
                String[] splittedinput = input.split("/");
                num = Integer.parseInt(splittedinput[0]);
                den = Integer.parseInt(splittedinput[1]);
            } else if (input.contentEquals("q")){
                run=false;
                System.out.println("quit programm");
                continue;
            } else {
                System.out.println("invalid input, plese type in Fraction, Decimal or Mixed Fraction");
                continue;
            }

            int gcd = gcd(num, den);
            num = num / gcd;
            den = den / gcd;

            if (den == 0) {
                System.out.println("Invalid denominator, cannot divide by 0");
            } else {
                System.out.println("Fraction: " + num + "/" + den);
                if (num > den) {
                    System.out.println("Mixed Fraction: " + (num / den) + " " + (num % den) + "/" + den);
                } else {
                    System.out.println("Mixed Fraction: " + num);
                }
                System.out.println("Decimal: " + ((double) num / (double) den));
            }
        } while (run);

        scan.close();

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.