How to detect different non-numerical input in Java?

baronoke :

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.

Peter Walser :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=334487&siteId=1