这个初始部分应该取一个混合分数,比如 1 1/2 并将其转换为 3/2
我所拥有的如下,问题是当我运行它时它给了我一个错误。说错误是
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at Calculator.main(Calculator.java:18)
代码开始如下:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
// prompt user for fraction string
// receive and store in variable
// convert to improper fraction
//print
System.out.println("Enter a fraction:"); //prompt for string
Scanner input = new Scanner(System.in); //Receive
String fractionAsString = input.next(); //store in variable
int getSpace = fractionAsString.indexOf('_'); //should fine where java spaces for the initial entering of fractoin
int getSlash = fractionAsString.indexOf('/'); //should find divisor (like in 1 1/2)
String firstString= fractionAsString.substring(0, getSpace+1);//converting string to int
String secondString=fractionAsString.substring(getSpace, getSlash);
String thirdString=fractionAsString.substring(getSlash+1);
int wholeNumber=Integer.parseInt(firstString);
int numerator=Integer.parseInt(secondString);
int denominator=Integer.parseInt(thirdString);
int newResult=wholeNumber*denominator;
int finalResult=numerator+newResult;
System.out.println(finalResult+"/"+denominator);
input.close();
}
}