I am trying to make a calculator with Java and 3 classes

I am very new to JAVA Programming and tried to create a Java program consisting of 2 classes and an interface. The main class is StartingPoint.java, the other class is Calculate.java, and the interface is Equations.java.

So far, I have one equation in the Equation.java interface, which consists of a simple add function. I want the program to prompt the user to insert 2 integers and return the added solution. Any help would be greatly appreciated.

This is my main class called StartingPoint.java

import java.util.Scanner; public class StartingPoint { public static void main (String Hoda[]){ System.out.println("Please enter two values"); Scanner a = new Scanner(System.in); Scanner b = new Scanner(System.in); Calculate calculator = new Calculate(); int answer = calculator.add(in.nextInt(a), nextInt(Scanner b)); System.out.print(answer); } } 

Here is my second class: Calculate.java

 import java.util.Scanner; public class Calculate implements Equations { @Override public int add(Scanner a, Scanner b) { // TODO Auto-generated method stub return (a + b); } } 

And here is my interface called Equations.java

 import java.util.Scanner; public interface Equations { int add(Scanner a, Scanner b); } 
+6
source share
1 answer

You might want to convert the values ​​to an integer ... something like this:

 @Override public int add(Scanner a, Scanner b) { int n1=Integer.parseInt(a.next()); int n2=Integer.parseInt(b.next()); return (n1 + n2); } 

I see that you are new to java. Take a look at your function:

 public int add(... 

java expects this function to return an integer. You return + b, but a and b are instances of the Scanner object, not integers. Therefore, we must "convert" the input string to an integer object. Java is a very high-level language, so almost every object has many methods that will help us do whatever we want. In this case, the Integer class has a static method parseInt (String args), which will parse the given string and check whether it is numeric. If it is numeric, it will return an integer. If not, this will throw an exception. That is why you should check the input. If you type a non-numeric value, it will work.

+2
source

Source: https://habr.com/ru/post/946117/


All Articles