Im trying to create a recursive parsing calculator in java for addition, multiplication and factorial, but I'm struggling on the very first part of just reading through the user input to split the input into numbers and operators. While debugging I tried to see where it was going wrong, and I found that when the "+" was going through the if else statements it just skipped over it. I'm really unsure on what the issue is, I originally tried using tokens, and splitting up into substring, but it wasn't going well then either. Any help would be appreciated. Thank you
package com.company;
import java.util.Scanner;
class Main {
public static void main(String[] param) {
String input = input("Please enter an expression");
int n = input.length()-1;
String[] splitter = input.split("(?<=\\G.)");
split(input, n);
//int result = calculate(input);
//String[] splitter = input.split("(?<=\\G.)");
}
public static String split(String input, int n) {
String[] splitter = input.split("(?<=\\G.)");
System.out.println(splitter[n]);
String symbol = splitter[n];
if (symbol.equals("+")) {
evalADD(n, splitter);
}
if (symbol.equals("*")) {
evalMULT(n, splitter);
}
if (symbol.equals("!")) {
evalFACT(n, splitter);
}
else if (Integer.parseInt(splitter[n]) >= 0 && Integer.parseInt(splitter[n]) <=9)
{
if (n != 0) {
n = n - 1;
split(input, n);
}
}
if (n != 0)
n = n - 1;
split(input, n);
return input;
}
public static int evalADD(int n, String [] splitter){
int arg1;
int arg2;
int result;
arg1 = Integer.parseInt(splitter[n+1]);
arg2 = Integer.parseInt(splitter[n+2]);
result = arg1 + arg2;
return result;
}
public static int evalMULT(int n, String [] splitter){
int arg1;
int arg2;
int result;
arg1 = Integer.parseInt(splitter[n+1]);
arg2 = Integer.parseInt(splitter[n+2]);
result = arg1 * arg2;
return result;
}
public static int evalFACT(int n, String [] splitter){
int arg1;
int arg2;
int result;
arg1 = Integer.parseInt(splitter[n+1]);
arg2 = Integer.parseInt(splitter[n+2]);
result = arg1 - arg2;
return result;
}
public static String input(String message) {
Scanner scanner = new Scanner(System.in);
System.out.println(message);
return (scanner.nextLine());
}
}
I have noticed that you are using the java.util.Scanner. I wrote a script that should do the task for you by following all of your criteria:
import java.util.Scanner;
class recursiveParsingCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Ask user to input the expression
System.out.println("Please input the expression");
String userInput = scanner.nextLine();
System.out.println(
"And the final result is: " + recursiveCalculation(userInput, userInput.length() - 1, 0, 0, 0));
scanner.close();
System.exit(0);
}
// Identify the type of character at a specific position
public static char charOfString(String userInput, int i) {
return userInput.charAt(i);
}
/*
* Position must be userInput.length() - 1 initially. currentResults, operand1
* and operand2 are also meant to be initilized with 0.
*/
public static int recursiveCalculation(String userInput, int position, int operand1, int operand2,
int currentResults) {
// If position is zero, just output the operand.
if (position == 0) {
if (Character.isDigit(charOfString(userInput, position))) {
return charOfString(userInput, position) - '0';
} else {
System.out.println("Invalid input.");
}
}
if (position > -1) {
// Check if it is a number or an operator
if (Character.isDigit(charOfString(userInput, position))) {
operand1 = charOfString(userInput, position) - '0'; // First operand
// Check if 2nd char is a number or an operator.
if (Character.isDigit(charOfString(userInput, position - 1))) {
operand2 = charOfString(userInput, position - 1) - '0';
position = position - 1;
}
} else {
// If it is an operator, then proceed to compute the results so far
char operator = charOfString(userInput, position);
// If it is a binary situation
if (operator == '+' || operator == '*') {
currentResults = binaryOperator(operator, operand1, operand2);
operand2 = currentResults;
}
// If it is an unary situation
else if (operator == '!') {
if (currentResults == 0) {
currentResults = operand1;
}
currentResults = unaryOperator(currentResults);
operand2 = currentResults;
} else {
System.out.println("Invalid operator");
return 0; // Return zero by default
}
}
position = position - 1;
}
if (position > -1) {
return recursiveCalculation(userInput, position, operand1, operand2, currentResults);
} else {
return currentResults;
}
}
public static int binaryOperator(char operator, int operand1, int operand2) {
switch (operator) {
case '+':
return operand1 + operand2;
case '*':
return operand1 * operand2;
default:
System.out.println("Invalid binary Operator");
return 0; // Return zero by default
}
}
// Calculate the factorial
public static int unaryOperator(int operand) {
if (operand <= 1)
return 1;
else
return operand * unaryOperator(operand - 1);
}
}
Examples of usage: For a binary operator, input +21, and it will add them for you. With unary, input !3, and it will yield the factorial. Now, you can try any chain of combinations and permutations of numbers with unary and binary operators, and it will calculate the values for you recursively.
For example, consider the input !*3+12: It will add 1 and 2, then multiply it by 3 and finally, it calculates the factorial out of the whole expression, thereby resulting in 362880 as expected.
Why don't you assign the input calculation string to a character array and iterate through the array and match the characters '+', '-','*'?
Related
I'm very new to binary search and I attempted a code that would read values from a document and then the user can input a number to search for from the document, and through binary search, the number would be found. I'm having trouble now because the "low" variable that I initialize in the binary search section of my code is not being returned to my main code and there's an error that says "low can not be resolved to a variable".
Here is the code for my binary search:
static public int search (int[]numbers,int target, int count)
{
int high = numbers.length;
int low = -1;
int middle = (high+low)/2;
while(high-low>1)
{
count++;
middle = (high+low)/2;
if(numbers[middle]>target)
{
high = middle;
}
else if(numbers[middle]<target)
{
low = middle;
}
else
{
break;
}
System.out.println(numbers[middle]);
System.out.println(middle);
}
if(low == -1 || numbers[low]!=target)
{
low=-1;
return low;
}
else
{
return low;
}
}
And here is the code from my main code. The part with the if statements is where the error is showing up:
public static void main(String[] args) throws IOException {
DataInputStream input = new DataInputStream(System.in);
int [] numbers = new int [50000];
int target;
int count=0;
try
{
BufferedReader br = new BufferedReader(new FileReader("randNums.txt"));
for(int i=0;i<50000;i++)
{
numbers[i]=Integer.parseInt(br.readLine());
}
br.close();
Arrays.sort(numbers);
System.out.print("Choose a number between 1-100000000 to search for: ");
target = Integer.parseInt(input.readLine());
search(numbers, target,count);
if(low==-1)
{
System.out.println("The number was not on the list.");
}
else
{
System.out.println("The number is at position " + low);
System.out.println("It took " + count + " comparisons to find the number.");
}
}
You have to initialize low in main:
int low=search(numbers, target,count);
I have Already resolved this algorithm.
Try my code :
public static int guessNumber(int number) {
int first = 0;
int last = 1_000_000;
if (verify(first) == 0) {
count++;
return first;
}
if (verify(last) == 0) {
count++;
return last;
}
while (last > first && count <= 50) {
count += 1;
// get the middle of the range
int middle = (first + last) / 2;
if (verify(middle) == 0) {
return middle;
}
if (verify(middle) == 1) {
first = middle + 1;
if (verify(first) == 0) {
return first;
}
}else {
last = middle - 1;
if (verify(last) == 0)
return last;
}
}
return 0;
}
//Function verify(integer) => integer
public static int verify(int guess){
if (numberTobeGuessed > guess ) {
return 1;
}else if (numberTobeGuessed < guess) {
return -1;
}
return 0;
}
I recently found a solution for lazy peoples like me use below code
int position = Arrays.binarySearch(numbers , target);
here no need to sort, and array variable number integer variable target.
I'm pretty lost at the moment on how I would go about implementing this Tree, I'm trying to construct a Tree from a string representation of input "(4 + 6) + (2 + 3)". How would I go about making a Tree from two Stacks?
public class Tree {
private Stack opStk = new Stack();
private Stack valStk = new Stack();
private Tree parent = null;
public Tree(String str){
System.out.println((EvaluateExpression(str)));
}
public void doOperation() {
Object x = valStk.pop();
Object y = valStk.pop();
Object op = opStk.pop();
if ((Integer) x <= 0 || (Integer) y <= 0){
throw new NumberFormatException();
}
if (op.equals("+")) {
int sum = (Integer) x + (Integer) y;
valStk.push(sum);
}
}
public void repeatOps(char refOp) {
while (valStk.count() > 1 &&
prec(refOp) <= prec((char)opStk.pop())) {
doOperation();
}
}
int prec(char op) {
switch (op) {
case '+':
case '-':
return 0;
case '*':
case '/':
return 1;
case '^':
return 2;
default:
throw new IllegalArgumentException("Operator unknown: " + op);
}
}
public Object EvaluateExpression(String str) {
System.out.println("Evaluating " + str);
Scanner s = null;
try {
s = new Scanner(str);
//while there is tokens to be read
while (s.hasNext()) {
//if token is an int
if (s.hasNextInt()) {
//read it
int val = s.nextInt();
if(val <= 0) {
throw new NumberFormatException("Non-positive");
}
System.out.println("Val " + val);
//push it to the stack
valStk.push(val);
} else {
//push operator
String next = s.next();
char chr = next.charAt(0);
System.out.println("Repeat Ops " + chr);
repeatOps(chr);
System.out.println("Op " + next);
opStk.push(chr);
}
repeatOps('+');
}
} finally {
if (s != null) {
s.close();
}
}
System.out.println("Should be the result: " + valStk.pop());
return valStk.pop();
}
I have a few suggestions to make that might set you on the right path (hopefully).
Firstly I suggest your expression tree follow the Composite Design Pattern. It works very well for these types of hierarchies. For your purpose it would look something like:
interface Expression {
int getValue();
}
class Constant implements Expression {
private int value;
public int getValue() {
return value;
}
}
class Operation implements Expression {
private Expression operand1;
private Operator operator;
private Expression operand2;
public int getValue() {
return operator.apply(operand1, operand2);
}
}
Note that you don't need any concept of operator precedence or parentheses: it's entirely implicit in how the tree is constructed. For example "3 + 4 * 2" should result in a tree "(+ 3 (* 4 2))" while "(3 + 4) * 2" should result in a tree "(* (+ 3 4) 2)".
Secondly I suggest you make your operators into an enum rather than relying on the string values:
enum Operator {
TIMES((n1, n2) -> n1 * n2),
DIVIDE((n1, n2) -> n1 / n2),
PLUS((n1, n2) -> n1 + n2),
MINUS((n1, n2) -> n1 - n2);
private final BinaryOperator<Integer> operation;
Operator(BinaryOperator<Integer> operation) {
this.operation = operation;
}
public int apply(int operand1, int operand2) {
return operation.apply(operand1, operand2);
}
}
The advantage of this approach is that it's trivial to add new operators without changing the structure of the tree at all.
Thirdly I suggest you split your conversion from string to expression tree into two steps. The first is to convert from string to tokens and the second from token to trees. These are call lexical and semantic analysis in the jargon.
If you are using the shunting yard algorithm for the semantic analysis then keep in mind that the output stack will hold Expression instances ready to become operands. I can give you more detail on how to shunt operators but it's probably worth you giving the suggestions above a try first.
I was trying to build a Java program for finding the LCM of 'N' numbers. but first of all i am stuck at finding the total prime factors of a number including their occurrences. For example (6=2x3) and (8=2x2x2). but the output i get is '2' for (6) and only two '2's for (8). Where are the other? I am even checking the integer 's' to be prime.
package lcm;
import java.util.ArrayList;
import java.util.Scanner;
public class LCM {
public static boolean isPrime(int numero){
for (int i = 2; i <= Math.sqrt(numero); i++) {
if (numero % i == 0) {
return false;
}
}
return true;
}
public static void factor(int x){
int s;
int copy = x;
ArrayList<Integer> al = new ArrayList<>();
for(s=2;s<copy;s++){
if(copy%s==0){
if (isPrime(s)){
al.add(s);
copy/=s;
//used for repetition
s--;
}
}
}
for( int p : al){
System.out.println(p);
}
}
public static void main(String[] args) {
// TODO code application logic here
int j,k;
int temp=0;
System.out.println("Enter no. of numbers");
Scanner cin = new Scanner(System.in);
int i = cin.nextInt();
int []a = new int[i];
int []b=new int[100];
System.out.println("Enter numbers one by one");
for(j=0;j<a.length;j++){
a[j] = cin.nextInt();
}
for(j=0;j<a.length;j++){
temp=a[j];
factor(temp);
}
}
}
The reason is when s=2 and copy also becomes 2 in a case at that time it skips the loop so only two 2's are shown. Try putting <=copy in that place
I think one of the best way to approach this problem is to use recursion since you continuously have to divide in order to find all the prime factors.
package leastcommonmultiple;
import java.util.ArrayList;
import java.util.Scanner;
public class Runner {
private static LeastCommonMultiple lcm;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Enter numbers and separate them with a comma: ");
Scanner cin = new Scanner(System.in);
String[] inputs;
String lineInput;
try {
lineInput = cin.nextLine();
while (lineInput.isEmpty()) {
System.out.println("Enter at least 2 numbers separated by a comma ");
lineInput = cin.nextLine();
}
inputs = lineInput.split(",");
int length = inputs.length;
int[] numbers = new int[length];
int temp = 0;
for (int i = 0; i < length; i++) {
if (inputs[i] != null && !inputs[i].isEmpty()) {
if ((temp = Math.abs(Integer.valueOf(inputs[i].trim()))) == 0) {
throw new IllegalArgumentException("No number should be 0");
}
numbers[i] = temp;
}
}
ArrayList<Integer> list = new ArrayList<>();
lcm = new LeastCommonMultiple();
System.out.println("The Least Common Multiple is: " + lcm.getLeastCommonMultipleOfListOfNumbers(numbers));
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
package leastcommonmultiple;
import java.util.ArrayList;
public class LeastCommonMultiple {
public LeastCommonMultiple() {
}
/**
* #param numbers array of numbers whose LCM should be found.
* #assure numbers.length > 1
* #return LCM of numbers contained in numbers array
*/
public int getLeastCommonMultipleOfListOfNumbers(int[] numbers) throws IllegalArgumentException {
int leastCommonMultiple;
int length = numbers.length;
if ( length <= 1) {
throw new IllegalArgumentException("Please enter at least 2 numbers separated by a comma.");
} else {
leastCommonMultiple = getLeastCommonMultipleOfTwoNumbers(numbers[0], numbers[length-1]);
length = length-1;
for ( int i=1; i<length; i++ ) {
leastCommonMultiple = getLeastCommonMultipleOfTwoNumbers(leastCommonMultiple, numbers[i]);
}
}
return leastCommonMultiple;
}
private int getLeastCommonMultipleOfTwoNumbers(int number1, int number2) {
int leastCommonMultiple = 0;
int maxOfTheTwoNumbers = Math.max(number1, number2);
int minOfTheTwoNumbers = Math.min(number1, number2);
int quotient = 0;
if (number1 % number2 == 0 || number2 % number1 == 0) {
leastCommonMultiple = maxOfTheTwoNumbers;
} else {
ArrayList<Integer> primeFactors = getPrimeFactors(minOfTheTwoNumbers, new ArrayList<>());
for (int primeFactor : primeFactors) {
if (maxOfTheTwoNumbers % primeFactor == 0) {
maxOfTheTwoNumbers = (maxOfTheTwoNumbers / primeFactor);
}
leastCommonMultiple = minOfTheTwoNumbers * maxOfTheTwoNumbers;
}
}
return leastCommonMultiple;
}
// recursive methods that finds all the prime factors for a given number
/**
* #param numero positive number whose prime factors has to be found
* #param primeFactors an empty ArrayList where the prime factors will be
* stored
* #return the ArrayList containing the found prime factors
*/
private static ArrayList<Integer> getPrimeFactors(int numero, ArrayList<Integer> primeFactors) {
int sqrt = (int) Math.sqrt(numero);
int quotient;
if (isPrime(numero)) {
primeFactors.add(numero);
} else {
if (numero % sqrt == 0) {
quotient = numero / sqrt;
if (isPrime(sqrt)) {
primeFactors.add(sqrt);
} else {
primeFactors = getPrimeFactors(sqrt, primeFactors);
}
} else {
quotient = numero / (sqrt - 1);
if (isPrime(sqrt - 1)) {
primeFactors.add(sqrt - 1);
} else {
primeFactors = getPrimeFactors((sqrt - 1), primeFactors);
}
}
if (!isPrime(quotient)) {
primeFactors = getPrimeFactors(quotient, primeFactors);
} else {
primeFactors.add(quotient);
}
}
return primeFactors;
}
// Make sure a number is prime
public static boolean isPrime(int numero) {
int length = (int) Math.sqrt(numero);
for (int i = 2; i <= length; i++) {
if (numero % i == 0) {
return false;
}
}
return true;
}
}
Here's a solution which is faster by using binary splitting on the Euclidean algorithm:
private static int gcd(int a, int b) {
if (a == 0) return b;
if (b == 0) return a;
return gcd(b, a%b);
}
private static int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
public static int LCM(int[] numbers) {
int len = numbers.length;
if (len == 2) return lcm(numbers[0], numbers[1]);
if (len == 1) return numbers[0];
if (len == 0) return 1;
int[] left = Arrays.copyOfRange(numbers, 0, len/2);
int[] right = Arrays.copyOfRange(numbers, len/2+1, len);
return lcm(LCM(left), LCM(right));
}
I was asked this question in an interview recently (Java programming que)
Return the sum of all integers from a random String.
Just iterate over the string, handle one digit at a time. This is pretty much exactly what the regex would do anyway:
String testStrings[] = { "-1a2b3c", "123ab!45c", "abcdef", "0123.4",
"dFD$#23+++12##T1234;/.,10" };
for (String testString : testStrings) {
String currentNumber = "";
int sum = 0;
for (int i = 0; i < testString.length(); i++) {
char currentChar = testString.charAt(i);
// Add digits or a leading minus to "currentNumber"
if (Character.isDigit(currentChar)
|| (currentNumber.equals("") && currentChar == '-')) {
currentNumber += currentChar;
} else {
// We've stumbled across a non-digit char.
//Try to parse the "currentNumber" we have so far
if (!currentNumber.equals("") && !currentNumber.equals("-"))
sum += Integer.parseInt(currentNumber);
currentNumber = "";
}
}
// Add the last "currentNumber" in case the string ends with a
// number
if (!currentNumber.equals("") && !currentNumber.equals("-"))
sum += Integer.parseInt(currentNumber);
System.out.println(sum);
}
Output:
4
168
0
127
1279
public class Random {
public int SumofNumbers(String s){
char[] str = s.toCharArray();
String answer="";
int sum = 0;
List<String> al = new ArrayList();
for (int i=0;i< str.length;i++){
if (checkNumber(str[i])){
answer=answer+str[i];
}
else
{
if(!answer.isEmpty()){
al.add(answer);
answer = "";
}
}
if (i == str.length -1 && !answer.isEmpty()) {
al.add(answer);
}
}
for (String a1 : al){
sum = sum + Integer.valueOf(a1);
}
return sum;
}
private boolean checkNumber(char c) {
if ((int)c > 47 && (int)c < 58){
return true;
}else if ((int)c == 45){
return true;
}
return false;
}
public static void main(String [] args){
Random r = new Random();
String test = "123ab!45c";
System.out.println(r.SumofNumbers(test));
}
}
public class StringToIntAddition {
public static void main(String[] args) throws Exception {
String str = "2e40 ssdf 23-9", number="";
int sum=0;
for(int i=0; i<str.length() ;i++){
if(Character.isDigit(str.charAt(i))){
number += str.charAt(i);
}
else if(!number.isEmpty()){
sum += Integer.parseInt(number);
number= "";
}
if (str.charAt(i) == '-'){
number = "-" ;
}
}
if(!number.isEmpty()){
sum += Integer.parseInt(number);
}
System.out.println("number= " + sum);
}
}
I've got a slightly 'cute' way to do this in Java 8: implement it as a Collector
public DigitCollector {
private boolean negative = false;
private int current = 0;
private int total = 0;
public int getTotal() {
if (negative) {
total -= current;
} else {
total += current;
}
current = 0;
negative = false;
return total;
}
public void accept(Character ch) {
if (Character.isDigit(ch)) {
current = 10 * current + Integer.parseInt(ch.toString());
} else if (ch.equals('-')) {
negative = true;
} else {
getTotal();
}
}
}
Now you can collect a stream of characters:
text.chars().map(ch -> new Character((char)ch))
.collect(DigitCollector::new, DigitCollector::accept, null)
.getTotal();
I realise the mapping ch -> new Character((char)ch)) looks strange but .chars() returns a stream of integers instead of characters. See here for reasons why (though pretty much everyone agrees it was a mistake).
This is a slightly longwinded way of doing it but it's pretty flexible: you could take a stream of Character from anywhere and do any sort of manipulation you wanted before collecting them. It seems to me to be a natural representation of the problem and, mostly, I just reckon streams are cooler than traditional iteration :-)
There's already quite a few answers, but this one seemed fun. I have a different solution that should be pretty efficient:
public static int countString(String input) {
if (input == null) return 0;
int sum = 0;
int accumulator = 0;
boolean lastCharWasDigit = false;
for (int i = 0, len = input.length(); ++i) {
char c = input.charAt(i);
// If a non-digit character is found, clear the
// accumulator and add it to the sum.
if (c < '0' || c > '9') {
sum += accumulator;
accumulator = 0;
lastCharWasDigit = false;
continue;
}
// If the previous character was a digit, that means
// this is a continuation. Multiply by ten to shift
// it over one power of ten before adding the new value
if (lastCharWasDigit) {
accumulator *= 10;
}
// Add the integer value of the character
int charValue = c - '0';
accumulator += charValue;
lastCharWasDigit = true;
}
// Finally, clear the accumulator for any ending digits,
// and return the sum
sum += accumulator;
return sum;
}
If I have four different files that I'm passing through a loop with count++ how would I get the count++ to refresh and start at 1 for every new file?
Right now, the output for the files is:
20
37
57
76
But I want it to refresh and start at 1, so the output would be:
20
17
20
16
My code in entirety:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Grader {
public static int Score = 0;
public static void getFileInfo(String fileName)
throws FileNotFoundException {
Scanner in = new Scanner(new File(fileName));
while (in.hasNext()) {
String fileContent = in.nextLine();
String result = removeSpaces(fileContent);
double first = Double.parseDouble(fileContent.substring(0, fileContent.indexOf(" ")));
char operator = getOperator(fileContent);
double second = secondNumber(result, fileContent);
double last = Double.parseDouble(result.substring(result.indexOf("=") + 1));
double math = mathChecking(first, second, operator);
mathGrading(math , last);
}
System.out.println(Score);
}
public static String removeSpaces(String content){
String result = content.replace(" ","");
return result;
}
public static double mathGrading(double math , double last) {
if (math == last){
Score++;
}
return Score;
}
public static double secondNumber(String result, String opContent){
int checkAdd = opContent.indexOf('+');
int checkMinus = opContent.indexOf('-');
int checkMulti = opContent.indexOf('*');
int checkDivi = opContent.indexOf('/');
if (checkAdd != -1){
return Double.parseDouble(result.substring(result.indexOf('+')+1 , result.indexOf('=')));
}
else if (checkMinus != -1) {
return Double.parseDouble(result.substring(result.indexOf('-')+1 , result.indexOf('=')));
}
else if (checkMulti != -1) {
return Double.parseDouble(result.substring(result.indexOf('*')+1 , result.indexOf('=')));
}
else if (checkDivi != -1){
return Double.parseDouble(result.substring(result.indexOf('/')+1 , result.indexOf('=')));
}
return 0;
}
public static char getOperator(String fileContent){
int checkAdd = fileContent.indexOf('+');
int checkMinus = fileContent.indexOf('-');
int checkMulti = fileContent.indexOf('*');
int checkDivi = fileContent.indexOf('/');
if (checkAdd != -1){
char operator = fileContent.charAt(fileContent.indexOf('+'));
return operator;
}
else if (checkMinus != -1) {
char operator = fileContent.charAt(fileContent.indexOf('-'));
return operator;
}
else if (checkMulti != -1) {
char operator = fileContent.charAt(fileContent.indexOf('*'));
return operator;
}
else if (checkDivi != -1){
char operator = fileContent.charAt(fileContent.indexOf('/'));
return operator;
}
return ' ';
}
public static double mathChecking(double first, double second, char operator){
double math = 0;
if (operator == '+'){
return math = (first + second);
}
else if (operator == '-'){
return math = (first - second);
}
else if (operator == '*'){
return math = (first * second);
}
else if (operator == '/'){
return math = (first / second);
}
return math;
}
Here's the Starter class:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Starter {
public static void main(String[] args) throws FileNotFoundException {
Grader.getFileInfo("data\\studentSubmissionA.txt");
Grader.getFileInfo("data\\studentSubmissionA2.txt");
Grader.getFileInfo("data\\studentSubmissionB.txt");
Grader.getFileInfo("data\\studentSubmissionB2.txt");
Change the getFileInfo method to the following:
public static void getFileInfo(String fileName) throws FileNotFoundException {
Scanner in = new Scanner(new File(fileName));
Score = 0;
while (in.hasNext()) {
String fileContent = in.nextLine();
String result = removeSpaces(fileContent);
double first = Double.parseDouble(fileContent.substring(0, fileContent.indexOf(" ")));
char operator = getOperator(fileContent);
double second = secondNumber(result, fileContent);
double last = Double.parseDouble(result.substring(result.indexOf("=") + 1));
double math = mathChecking(first, second, operator);
mathGrading(math , last);
}
System.out.println(Score);
}