I want the program to accept operation signs (+, -, * ,/) as input. Whenever I do that it throws an exception. Can anybody help me fix this problem and make the program accept one of these signs as input.
import java.lang.*;
import java.util.*;
public class Calculator
{
private double solution;
private static double x, y;
private static char ops;
public static interface Calculate
{
public abstract double operation(double x, double y);
}
public static class addition implements Calculate
{
public double operation(double x, double y){
return(x+y);
}
}
public static class subtraction implements Calculate
{
public double operation(double x, double y){
return(x-y);
}
}
public static class multiplication implements Calculate
{
public double operation(double x, double y){
return(x*y);
}
}
public static class division implements Calculate
{
public double operation(double x, double y){
return(x/y);
}
}
public void calc(int ops){
Scanner operands = new Scanner(System.in);
System.out.println("operand 1: ");
x = operands.nextDouble();
System.out.println("operand 2: ");
y = operands.nextDouble();
System.out.println("Solution: ");
Calculate [] jumpTable = new Calculate[4];
jumpTable['+'] = new addition();
jumpTable['-'] = new subtraction();
jumpTable['*'] = new multiplication();
jumpTable['/'] = new division();
solution = jumpTable[ops].operation(x, y);
System.out.println(solution);
}
public static void main (String[] args)
{
System.out.println("What operation? ('+', '-', '*', '/')");
System.out.println(" Enter 0 for Addition");
System.out.println(" Enter 1 for Subtraction");
System.out.println(" Enter 2 for Multiplication");
System.out.println(" Enter 3 for Division");
Scanner operation = new Scanner(System.in);
ops = operation.next().charAt(0);
Calculator calc = new Calculator();
calc.calc(ops);
}
}
The error is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 43
at Calculator.calc(Calculator.java:54)
at Calculator.main(Calculator.java:76)
jumpTable['+']
will be translated to the ASCII code (43) of the + sign (it's converted to a char), leaving you with a number out of the 0-4 range. You probably want to use actual numeric indices (or make sure your array can contain the highest numerical representation for your set of char values, in this case 47 by /).
ASCII table:
You can only reference jumpTable by 0..3 indices. But you're trying to reference it by '+' sign which is beyond this scope. Consider using HashMap<String, Calculate> for storing operations in such way:
Map<String, Calculate> jumpTable = new HashMap<String, Calculate>();
jumpTable.put("+", new addition());
jumpTable.put("-", new subtraction());
jumpTable.put("*", new multiplication());
jumpTable.put("/", new division());
String operation = Character.toString((char) ops);
solution = jumpTable.get(operation).operation(x, y);
Related
Hey everyone very new to coding!
So I was trying to make a calculator program using object oriented programming in Java however when I try to call my method for addition it doesn't do the job entirely so what am I doing wrong here ?
Thanks in advance :)
import java.util.Scanner;
public class CalculatorOOP {
Scanner input = new Scanner(System.in);
public static double currentValue;
public double valueInput;
public CalculatorOOP(double valueTyped){
valueTyped = currentValue;
}
public double addToValue(){
System.out.println("Type the value you want to add:");
double valueToAdd = input.nextDouble();
double valueAfterAddition = CalculatorOOP.currentValue + valueToAdd;
return valueAfterAddition;
}
public double substractToValue(){
System.out.println("Type the value you want to substract:");
double valueToSubstract = input.nextDouble();
double valueAfterSubstraction =
CalculatorOOP.currentValue - valueToSubstract;
return valueAfterSubstraction;
}
public double multiplyValue(){
System.out.println("Type the factor value:");
double factor = input.nextDouble();
double valueAfterMultiplication = CalculatorOOP.currentValue * factor;
return valueAfterMultiplication;
}
public double divideValue(){
System.out.println("Type the divisor value:");
double divisor = input.nextDouble();
double valueAfterDivision = CalculatorOOP.currentValue / divisor;
return valueAfterDivision;
}
}
import java.util.Scanner;
public class Main {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Type a value:");
double valueInput = input.nextDouble();
CalculatorOOP obj = new CalculatorOOP(valueInput);
System.out.println("Enter the calculation option (1, 2, 3, or 4):");
int optionEntered = input.nextInt();
switch (optionEntered){
case 1 : obj.addToValue();
}
}}
Here this is what I get when running the code however it is not performing the addition it is just asking for values
Type a value:
2
Enter the calculation option (1, 2, 3, or 4):
1
Type the value you want to add:
4
Process finished with exit code 0
Your addToValue method seems to perform the addition correctly and return the calculated sum. Where you call the method, you are not picking up the return value — so it just disappears, is discarded. I believe you want to assign it back into CalculatorOOP.currentValue and/or print it. Either from inside the method or from where you called it.
I am a beginner in Java and my professor wants us to create a program that involves some math. The thing is that he wants the calculations in a separate method. Can someone please help me. The program will not run the result for some reason. I tried looking around this website and could not find the answer. Here is the code below:
import javax.swing.JOptionPane;
public class forFun {
public static void main(String[] args)
{
double x, y, z;
String xVal, yVal, zVal;
xVal = JOptionPane.showInputDialog("Enter first integer: ");
yVal = JOptionPane.showInputDialog("Enter second integer: ");
zVal = JOptionPane.showInputDialog("Enter third integer: ");
x = Double.parseDouble(xVal);
y = Double.parseDouble(yVal);
z = Double.parseDouble(zVal);
System.exit(0);
}
public static void sumOfStocks(double x, double y, double z)
{
double result = x * y * z;
System.out.println("The product of the integers is: " + result);
System.exit(0);
}
}
Here is the example of how the code should be
import javax.swing.JOptionPane;
public class forFun {
public static void main(String[] args)
{
double x, y, z;
String xVal, yVal, zVal;
xVal = JOptionPane.showInputDialog("Enter first integer: ");
yVal = JOptionPane.showInputDialog("Enter second integer: ");
zVal = JOptionPane.showInputDialog("Enter third integer: ");
x = Double.parseDouble(xVal);
y = Double.parseDouble(yVal);
z = Double.parseDouble(zVal);
double result = sumOfStocks(x, y, z);
System.out.println("The result is %d", result);
System.exit(0);
}
public static double sumOfStocks(double x, double y, double z)
{
double result = x * y * z;
return result;
}
}
I have tried just about everything I can think of to fix my error but I;m completely stumped. I keep getting a "class, interface, or enum expected" error. What am I missing?
import java.until.*;
public class FutureValues {
public static final Scanner CONSOLE = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Lab 3 written by JENNIFER ADAME");
System.out.println();
//declare variables
double p;
double r;
double y;
double f;
System.out.print("Enter present value: ");
double p = console.nextDouble( );
System.out.print("Enter interest rate: ");
double r = console.nextDouble( );
System.out.print("Enter number of years: ");
double y = console.nextDouble( );
double f = compoundInterest(p, r, y);
System.out.print("The future value is" + f);
}
public static double compoundInterest (double p, double r, double y) {
double f = p * Math.pow(((1 + r) / 100), y);
return f;
}
}
}
If anyone could help that would be awesome!
You are adding one extra brace '}' at the end...just remove it
If wanna keep safe from these kind of errors in future,consider formatting your code properly.(Use Ctrl+shift+f for eclipse and Alt+shift+f for netbeans)
There is a mismatched brace at the end of your file.
I have a problem with my code, whenever I try to make a Tester Class, the code won't compile( my guess is that they are not linking with each other). However when they are not in tester form, they work perfectly.
Here is my code:
import java.io.*;
import java.util.*;
public class DistToline {
public static double A;
public static double B;
public static double C;
public static double distance;
public static double
getDist(double a, double b){
distance= Math.abs(((A*a)+(B*b)+(C))/(Math.pow(A, 2))+(Math.pow(B, 2)));
return distance;
}
public static void main(String args[])
{
Scanner f= new Scanner(System.in);
System.out.print("Enter the A value for the line:");
A = f.nextDouble();
Scanner g= new Scanner(System.in);
System.out.print("Enter the B value for the line:");
B = g.nextDouble();
Scanner h= new Scanner(System.in);
System.out.print("Enter the C value for the line:");
C = h.nextDouble();
Scanner i= new Scanner(System.in);
System.out.print("Enter the x coordinate of the point:");
Double X = i.nextDouble();
Scanner j= new Scanner(System.in);
System.out.print("Enter the y coordinate of the point:");
Double Y = j.nextDouble();
System.out.print("Distance from the point to the line is: ");
System.out.println(getDist(2.17, -4));
}
}
That is my full code, however when I make a Tester class, the codes are not linking with each other. I think this is because I haven't declared yet.
Here is my attempt on creating a Tester Class-
Tester:
class Tester{
public static void main(String args[])
{
Scanner f= new Scanner(System.in);
System.out.print("Enter the A value for the line:");
A = f.nextDouble();
Scanner g= new Scanner(System.in);
System.out.print("Enter the B value for the line:");
B = g.nextDouble();
Scanner h= new Scanner(System.in);
System.out.print("Enter the C value for the line:");
C = h.nextDouble();
Scanner i= new Scanner(System.in);
System.out.print("Enter the x coordinate of the point:");
Double X = i.nextDouble();
Scanner j= new Scanner(System.in);
System.out.print("Enter the y coordinate of the point:");
Double Y = j.nextDouble();
System.out.print("Distance from the point to the line is: ");
System.out.println(getDist(2.17, -4));
}
}
Class:
import java.io.*;
import java.util.*;
public class DistToline {
public static double A;
public static double B;
public static double C;
public static double distance;
public static double
getDist(double a, double b){
distance= Math.abs(((A*a)+(B*b)+(C))/(Math.pow(A, 2))+(Math.pow(B, 2)));
return distance;
}
The code is not stating any variables and they aren't even linking with each other. Is this because they are not declared? If so how would I fix it so that they are linking with each other?
The problem is due to the fact that your getDist() function is inside the DistToline class, but your mainline (void main()) is in the Tester class. You need to invoke the getDist() function by explicitly specifying the class it's in, as follows:
System.out.println(DistToline.getDist(2.17, -4));
Note this works because getDist() is declared as static. If getDist() were non-static, you would have to instantiate the DistToline class and call the function from the instance.
In your mainline you will also need to reference the variables A, B, and C the same way:
DistToline.A = f.NextDouble();
This is because they are static members of the DistToline class.
One more thing, although this won't affect the result: your public static distance variable can and should be moved into the getDist() function, as it doesn't need to be a static. Although you can just eliminate it altogether, and return the result of Math.abs directly:
public static double
getDist(double a, double b){
return Math.abs(((A*a)+(B*b)+(C))/(Math.pow(A, 2))+(Math.pow(B, 2)));
}
import java.io.IOException;
import java.util.*;
public class calling {
public static String s;
public static String t;
public static int y;
public static int x;
public static int num1() {
int x;
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number called x: ");
x=scanner.nextInt();
return x;
}
public static int num2() {
int y;
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number called y: ");
y=scanner.nextInt();
return y;
}
public static void calculation() {
Scanner input = new Scanner(System.in);
System.out.println("What process would you like to do? *, /, + or - ?");
s=input.next();
if (s.equals("*")) {
System.out.println("\nThe product of these numbers is:" + (x*y));}
else
if (s.equals("+")) {
System.out.println("\nThe sum of these numbers is: " + (x+y));}
System.out.println("\nDo you want x or y to be the dividor/subtractor?: ");
t=input.next();
if (t.equals("y") || t.equals("Y") ) {
if (s.equals("/")) {
System.out.println("\nThe quotient of these numbers is: " + (x/y));}
else
if (s.equals("-")) {
System.out.println("\nThe difference of these numbers is: " + (x-y));}}
else
if (t.equals("x") || t.equals("X")){
if (s.equals("/")) {
System.out.println("\nThe quotient of these numbers is: " + (y/x));}
else
if (s.equals("-")) {
System.out.println("\nThe difference of these numbers is: " + ((y-x)));}}
}
public static void main (String [] args) throws IOException {
num1();
num2();
calculation();
}
}
i keep getting this error in what should be my final result which is simply the result of the calculations being performed
this is the error:" Exception in thread "main" java.lang.ArithmeticException: / by zero
at calling.calculation(calling.java:44)
at calling.main(calling.java:64)"
Since this is likely homework, I'll give you a hint to point you in the right direction.
When you run your program, you execute num1 and num2 to collect the values of x and y from the user. Within num2, y is declared as a local variable. What happens to that variable when num2 returns? And what does that imply for the class field (variable) y declared on line 7?
This is also a good time to learn how to use a debugger. Put a breakpoint on line 44, and see what the values of x and y are.
You need to make sure that the:
int x;
int y;
are the ones you want. Integer's default to zero when static.