I'm supposed to be making a calculator that will add, subtract, etc. two integers. It's supposed to prompt to enter in what the person would like to do endlessly, then terminate when "exit" is entered.
And yes, it's all supposed to be in a while loop.
There are two problems (maybe) with my code.
First, whenever I add, subtract, etc. the ints, it will give me a result. After the result, however, I'm getting an error saying there's a StringIndexOutofBoundsException at line 23: if(low.charAt(zero) == 'a')
I have no idea why.
Second, when I divide, it's returning the value as an int. I tried casting, but I couldn't get it to come out right.
Thanks in advance.
import java.util.Scanner; public class calculator { public static void main(String args[]){ Scanner in = new Scanner(System.in); String entered,low; int dur = 0; int first, second, zero= 0; int answer = 0; String ex = "exit"; double divide; while(dur == 0){ System.out.println("A) Add"); System.out.println("B) Subtract"); System.out.println("C) Multiply"); System.out.println("D) Divide"); System.out.println("Enter 'exit' to close the program"); entered = in.nextLine(); low = entered.toLowerCase(); if(low.charAt(zero) == 'a') {System.out.println("Enter in the first integer: "); first = in.nextInt(); System.out.println("Enter in the second integer: "); second = in.nextInt(); answer = add(first,second); System.out.println(answer);} else if(low.charAt(zero) == 'b') {System.out.println("Enter in the first integer: "); first = in.nextInt(); System.out.println("Enter in the second integer: "); second = in.nextInt(); answer= sub(first,second); System.out.println(answer);} else if(low.charAt(zero) == 'c') {System.out.println("Enter in the first integer: "); first = in.nextInt(); System.out.println("Enter in the second integer: "); second = in.nextInt(); answer = mult(first,second); System.out.println(answer);} else if(low.charAt(zero) == 'd') {System.out.println("Enter in the first integer: "); first = in.nextInt(); System.out.println("Enter in the second integer: "); second = in.nextInt(); divide = div(first,second); System.out.println(divide);} else if(low.equals(ex)) {System.out.println("Ending program"); dur = 1;} else {System.out.println("Invalid input. Try again.");} } } public static int add(int input1,int input2) {int sum; sum = (input1+input2); return sum;} public static int sub(int input1,int input2) {int equals; equals = (input1-input2); return equals;} public static int mult(int input1,int input2) {int prod; prod = (input1*input2); return prod;} public static double div(int input1,int input2) {double equ; equ=(input1/input2); return equ;} }