Home > Back-end >  Take fraction as string input and convert to int
Take fraction as string input and convert to int

Time:11-14

I am creating a fractions class, in my main I currently take fraction input as such

System.out.println("Enter whole number");
int wholeNumber = input.nextInt();

System.out.println("Enter numerator");
int numerator = input.nextInt();

System.out.println("Enter denominator");
int denominator = input.nextInt();

if (wholeNumber == 0) { // using fraction class to create fraction
    fraction.setWholeFraction(numerator, denominator);
} else {
    fraction.setMixedNumber(wholeNumber, numerator, denominator);
}

I want to take the input as a string with this format > x y/z

I am not allowed to use interger.parseInt or valueOf. I need to do this manually.

I created a preliminary string to int method, but it won't work for my fractions

public static int stringToint( String s ) {
  int r = 0;
  for (int i = 0; i < s.length();   i)
  {
    if (i > 0)
      r *= 10;

    r  = s.charAt(i)-'0';
  }
  return r;
}

I also need to be able to validate if they have entered it in the correct format, disallow doubles, and allow negatives.

if someone can help me out I have not been able to figure this one out.

CodePudding user response:

You can use method useDelimiter() to separate different parts of your string.

For checking double and negative values, you can traverse through the string and check if it contains floating point "," or negative sign "-"

CodePudding user response:

In case regular expressions are allowed in this task, they may be used to check formatting of the input string and parse appropriate parts.

Here, the pattern with named groups can help to get appropriate substrings which should be passed then to stringToint:

static final Pattern FORMAT = Pattern.compile("(?<neg>[- ]?)\\s*(?<whole>\\d*)\\s*(?<nomin>\\d )\\s*/\\s*(?<denom>\\d )");

static void parseRational(String str) {
    
    Matcher matcher = FORMAT.matcher(str);
    
    if (matcher.matches()) {
        System.out.println("sign: "    matcher.group("neg"));
        System.out.println("whole: "   stringToint(matcher.group("whole")));
        System.out.println("nomin: "   stringToint(matcher.group("nomin")));
        System.out.println("denom: "   stringToint(matcher.group("denom")));
    } else {
        System.out.println("Invalid input: "   str);
    }
}

Tests:

for (String str : Arrays.asList("-2 3/74", "2/5", " 4 / 9", "3.1415", "1.2 3.4/5.6")) {
    parseRational(str);
    System.out.println("====");
}

Output:

sign: -
whole: 2
nomin: 3
denom: 74
====
sign: 
whole: 0
nomin: 2
denom: 5
====
sign:  
whole: 0
nomin: 4
denom: 9
====
Invalid input: 3.1415
====
Invalid input: 1.2 3.4/5.6
====
  • Related