简体   繁体   中英

How to convert a String Fraction “2/6” into two integers? Java

I'm doing a Fraction Calculator, i already have all the code for the operations.

But now i want to create a Scanner that takes a String and converts the String into 2 Integers (Numerator AND Denominator).

The user input String should be in this format: Number / Number. If it's something else i'll make the scanner appear again.

The code i already have can handle negative Integers so the - sign and the 0 shoudn't be a problem.

您始终可以使用String.split()来基于定界符(在本例中为/ String.split()分割String,然后使用String.trim()输出,并对它们进行解析以获取分子和分母。

You can split the String on "/" and extract the numerator and denominator in the following way.

public void scan(String string){
 if(string.matches("-{0,1}[0-9]+\\/[0-9]+"){
  String[] numbers = string.split("/");

  int numerator = Integer.parseInt(numbers[0]);
  int denominator = Integer.parseInt(numbers[1]);
 }
 else{
  scan(string);
 }
}

You could use a Pattern with a regular expression, which at the same time, enforces a correct formatted string, and enables you to extract Numerator and Dominator:

Pattern inputPattern = 
    Pattern.compile("\\A(?<numerator>-?\\d+)[ ]*\\/[ ]*(?<denominator>-?\\d+)\\z");
Matcher matcher = inputPattern.matcher(inputString);
if (matcher.matches()) {
    //valid inputstring
    int numerator = Integer.parseInt(matcher.group("numerator"));
    int denominator = Integer.parseInt(matcher.group("denominator"));

} else {
    letTheScannerAppearAgain();
}

The pattern used here contains two named groups marked by rounded brackets (..) , and separated by a slash (escaped because slash also has a meaning in a regex \\/ ) Numerator/denominator may start with a minus sign, and should contain at least one digit. Spaces before and after the slash are allowed.

I just did like this:

int fTop, fBottom;
Fraction(String frak) {
    fTop = Integer.parseInt(frak.substring(0,frak.indexOf('/')));
    fBottom = Integer.parseInt(frak.substring(frak.indexOf('/')+1,frak.length())); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM