Brandon Latimer Brandon Latimer - 1 month ago 6
Java Question

Searching a string with multiple double values for one certain double value?

I have to create a calculator for my Computer Science class. I can calculate double values if they are only numbers like 3.4 or 6.8, while other double values like 64.7 or 6.78 will not work due to how I searched the String for the doubles. I am wondering if there is any way to find the doubles in the string or not. P.S. I know that testing the operator can be done a lot easier with switches. I am working on it.

public static void main(String[] args){
//Declares my input variables and Scanner variable
String firstInput;
String secondInput;
String userProblem;
char operator;
//Creates the scanner
Scanner userInput = new Scanner(System.in);

//Asks for input
System.out.println("Please enter a problem you would like to calculate (ex. \"2.0 * 4.3\")");
userProblem = userInput.nextLine();

//Finds the doubles in the string and the operator
firstInput = userProblem.substring(0, 3);
secondInput = userProblem.substring(6, 9);
operator = userProblem.charAt(4);

//parses the strings to doubles
double firstNumber = Double.parseDouble(firstInput);
double secondNumber = Double.parseDouble(secondInput);

//Tests for the operator and executes accordingly
if(operator == '+'){
System.out.println(firstNumber + secondNumber);
}
else{
if(operator == '-'){
System.out.println(firstNumber - secondNumber);
}
else{
if(operator == '*'){
System.out.println(firstNumber * secondNumber);
}
else{
if(operator == '/'){
System.out.println(firstNumber / secondNumber);
}
else{
if(operator == '%'){
System.out.println(firstNumber % secondNumber);
}
else{
System.out.println("You did not input correctly");
}
}
}
}
}
}


}

Answer

Use below code snippet for extracting two inputs and operator as well.

String[] tokensVal = userProblem.split("[-+*/%]");
firstInput = tokensVal[0].trim();
secondInput = tokensVal[1].trim();
operator = userProblem.charAt(tokensVal[0].length());
Comments