简体   繁体   English

如何将字符串分数“ 2/6”转换为两个整数? 爪哇

[英]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). 但是现在我想创建一个使用StringScanner ,并将该String转换为2个Integers (分子和分母)。

The user input String should be in this format: Number / Number. 用户输入的String应采用以下格式:数字/数字。 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. 我已经拥有的代码可以处理负Integers因此-号和0应该不是问题。

您始终可以使用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与正则表达式配合使用,同时强制使用正确的格式化字符串,并使您能够提取Numerator和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. 此处使用的模式包含两个用圆括号(..)标记的命名组,并用斜杠分隔(转义,因为斜杠在regex \\/也具有含义)。分子/分母可能以减号开头,应包含至少一位数字。 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())); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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