Note that there are some explanatory texts on larger screens.

plurals
  1. PODetermine if Decimal, Fraction or Invalid using Regex
    primarykey
    data
    text
    <p>How can I determine the input of the user if it is <strong>decimal,fraction,mixed</strong> fraction or invalid?</p> <p>This is the input that is allowed on my program</p> <pre><code>String[] s = new String[]{ "0",".",".0",".01","1.","1.0","1.01", "1 ","1 1","1/2","1/","1/0", "1 1/1", "1 0/0","1 /","1 /0", "1 0/"}; </code></pre> <p><strong>expected output:</strong></p> <pre><code>0) 0 ---- Zero 1) . ---- Error 2) .0 ---- Zero 3) 0.01 ---- Decimal 4) 1. ---- Decimal(the input 1. should be turned to decimal) 5) 1.0 ---- Decimal 6) 1.01 ---- Decimal 7) 1 ---- Decimal(the input with space after the whole number must be decimal) 8) 1 1 ---- Error(because of the space between the 1) 9) 1/2 ---- Fraction 10) 1/ ---- Error 11) 1/0 ---- Error 12) 1 1/1 ---- Mixed Fraction 13) 1 0/0 ---- Error 14) 1 / ---- Error 15) 1 /0 ---- Error 16) 1 0/ ---- Error </code></pre> <p><strong>Actual Output:</strong></p> <pre><code>0) 0 ---- Zero 1) . ---- Error 2) .0 ---- Zero 3) 0.01 ---- Decimal 4) 1. ---- Error 5) 1.0 ---- Decimal 6) 1.01 ---- Decimal 7) 1 ---- Error 8) 1 1 ---- Mixed Fraction 9) 1/2 ---- Fraction 10) 1/ ---- Fraction 11) 1/0 ---- Fraction 12) 1 1/1 ---- Mixed Fraction 13) 1 0/0 ---- Error 14) 1 / ---- Error 15) 1 /0 ---- Error 16) 1 0/ ---- Error </code></pre> <p>I don't have much knowledge on how to build a good pattern of regex?</p> <p>my code:</p> <pre><code>public class DecimalOrFraction { public static void main(String args[]){ String[] s = new String[]{ "0",".",".0",".01","1.","1.0","1.01", "1 ","1 1","1/2","1/","1/0", "1 1/1", "1 0/0","1 /","1 /0", "1 0/"}; for (int x = 0 ;x&lt;s.length;x++) { if(s[x].matches("[0]?([.][0]{1,3}\\s{0,1})?")){ System.out.println(x+") "+s[x]+" ---- Zero"); } else if(s[x].matches("\\d{0,3}([.]\\d{1,3}\\s{0,1})?")){ System.out.println(x+") "+Float.valueOf(s[x])+" ---- Decimal"); } else if(s[x].matches("[1-9]{1,5}([.]\\d{1,3})?\\s[1-9]\\d{0,2}([/]\\d{0,3})?")){ System.out.println(x+") "+s[x]+" ---- Mixed Fraction"); } else if(s[x].matches("[1-9]\\d{0,4}[/]\\d{0,3}")){ System.out.println(x+") "+s[x]+" ---- Fraction"); } else{ System.out.println(x+") "+s[x]+" ---- Error"); } } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload