Sum of two numbers - java

I want to make sum of two numbers. But I have problems to do that. I don't understand why my sum is always zero.
import java.util.*;
public class Numbers {
static int a;
static int b;
static int result;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Type the first number:");
String a = in.nextLine();
System.out.println(a);
System.out.println("Type the second number:");
String b = in.nextLine();
System.out.println(b);
display();
}
public static void display(){
result=a+b;
System.out.println("Sum of numbers is " + result);
}
}

I'm not a java programmer, but I can see that you have global variables called a and b and local variables called a and b.
Your main() is setting the local variables. display() is reading the global variables.

You don't need static "global" variables in your case. So you can remove this piece of code :
static int a;
static int b;
static int result;
Then, juste use your local variables and give a and b as parameter to display() method like this :
public static void display(int a, int b){
System.out.println("Sum of numbers is " + (a+b));
}
Eventually, you will need to cast Strings obtained via in.nextLine() and cast them to int, with Integer.parseInt() for example. Or just directly get integer from the user.

You did couple of mistakes :
String a and String b is a local variable to main() method. So you cant access
those variables from display() method. result=a+b;in display() method is actually adding a and b which are declared in the class level whose by default value is 0. so summation is 0.
Even if you write result=a+b;inside main method it will not work. Because a and b are String in main method and you cant do addition on String

Use this code
import java.util.*;
public class NewClass {
static int a;
static int b;
static int result;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Type the first number:");
a = in.nextInt();
System.out.println(a);
System.out.println("Type the second number:");
b = in.nextInt();
System.out.println(b);
display();
}
public static void display(){
result=(a+b);
System.out.println("Sum of numbers is " + result);
}
}
Use nextInt in place of nextLine method .If the type is int then use nextInt method.

Related

Java: Adding a class function in the main class

I am new to JAVA. I want to create a class and write a function in it. I then want to use that function in the main class.
import java.util.Scanner;
public class multi_fun {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a, b, c;
System.out.println("Enter 1st number: ");
a = scan.nextInt();
System.out.println("Enter 2nd number: ");
b = scan.nextInt();
Addition obj = new Addition();
c = obj.add(a,b);
System.out.println("The sum is "+c);
scan.close();
}
}
class Addition{
public int add (int a, int b)
{
return(a+b);
}
}
The problem I think according to error message you mentioned in the comments:
Exception in thread "main" java.lang.NoSuchMethodError:
Addition.add(II)I at multi_fun.main(multi_fun.java:15)
It seems that you are putting class Addition declaration in the same source file of multi_fun.java program.
You should create a java class file called Addition.java and put your class code in it:
class Addition{
public int add (int a, int b)
{
return(a+b);
}
}
After that it should work without any errors.
Update:
You can check this Answer which explain Causes of 'java.lang.NoSuchMethodError: main Exception in thread “main”'it would be a useful solution to your problem.
Make sure both the java files are in the same folder.
MultiFun.java
import java.util.Scanner;
public class MultiFun {
public static void main(String[] args) {
Addition obj = new Addition();
Scanner scan = new Scanner(System.in);
int a, b, c;
System.out.println("Enter 1st number: ");
a = scan.nextInt();
System.out.println("Enter 2nd number: ");
b = scan.nextInt();
c = obj.add(a, b);
System.out.println("The sum is " + c);
scan.close();
}
}
Addition.java
class Addition {
public int add(int a, int b) {
return (a + b);
}
}
run the following commands
javac MultiFun.java
java MultiFun
import java.util.Scanner;
public class multi_fun {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a, b, c;
System.out.println("Enter 1st number: ");
a = scan.nextInt();
System.out.println("Enter 2nd number: ");
b = scan.nextInt();
add(a,b);
System.out.println("The sum is "+c);
scan.close();
}
}
public static int add (int a, int b)
{
return(a+b);
}
The reason for this error is that there was already an other file in the same folder named Addition. So when I wrote a Class with the same name and tried to create an object, it was giving error message, as the parameters where different.
Thank you everyone for your help.
If you are run your program using Terminal or command prompt(cmd) make sure to run the class that have main method(created object from Addition class). And also do not create main methods in both classes and do not add public to Addition class.
One last thing: compile and run only the main class(multi_fun). Which is,
javac multi_fun.java
java multi_fun

How to get an user input and use the value inside method?

How to get an user input using scanner class and use it inside method to process, and obtain output?
Example : You get two numbers from the user and pass it to 4 methods to get its value after addition, subtraction, multiplication, division.
The scanner should be in main class and not inside every method.
Here is my code, it's in basic form. I want to get input from the user and process it inside the methods and get the result:
class Calc{
public static void main(String[] args){
add();
sub();
mul();
div();
{
void Add() {
int a=5,b=10;
sum=a+b;
System.out.println(sum);
}
void sub() {
int a=5,b=10;
sub=a=b;
System.out.println(sub);
}
void mul() {
int a=5,b=10;
mul=a*b;
System.out.println(mul);
}
void div() {
int a=5,b=10;
div=a/b;
System.out.println(div);
}
}
}
}
Simply use the array or nextInt() method to get the number of input and passed it to your method.
For e.g. If you are supposed two take two input at time
Scanner sc = new Scanner(System.in);
int[] integers = new int[2];
for(int i = 0; i < 2; i++)
{
integers[i] = sc.nextInt();
}
Now use the integers array to get the value from index and passed it to your method
You can get input by using new Scanner(System.in), as follows:
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
add(a,b);
sub(a,b);
multiply(a,b);
divide(a,b);

Calling simple methods in java

I just want to know how to call methods/functions in java. Can you please help me with this?
So here's my code.
import java.util.Scanner;
public class MyFirstProject {
public static void main(String[] args) {
hello();
}
static void hello(int a, int b) {
Scanner scan = new Scanner(System.in);
int total;
System.out.print("Enter first number: ");
a = scan.nextInt();
System.out.print("Enter second number: ");
b = scan.nextInt();
total = a + b;
System.out.println("The total is: " + total);
}
}
You make the method hello static for the class MyFirstProject so it has connotations -> Explanation.
But the problem here is that you are missing to pass parameters to the method:
int example_arg_one = 3;
int example_arg_two = 5;
MyFirstProject.hello(example_arg_one,example_arg_two);
2 clicks away, here's a pictured answer - http://www.wikihow.com/Call-a-Method-in-Java
In your code what you're actually missing is passing the required parameters - the values for a and b. The call should actually look like MyFirstProject.hello(2, 5)
Since your method hello(int a, int b) has a parameter of two integers, you need to give it the integers when calling it in order for it to work. But that also doesn't make sense since you have a Scanner which defines your integers in your method. Just remove the parameters of your method and your code should work.
public static void main(String[] args) {
hello();
}
static void hello() {
Scanner scan = new Scanner(System.in);
int total;
System.out.print("Enter first number: ");
int a = scan.nextInt();
System.out.print("Enter second number: ");
int b = scan.nextInt();
total = a + b;
System.out.println("The total is: " + total);
}
Regarding how to call methods, you're doing it right. Just do not neglect your parameter, if your method has one you have to give it one. If you do not know what a parameter is, it is the hello (int a, int b). Your method is expecting you to give it two integers, because that is how you defined your method, you defined it to take two integers. If you want to call it using the parameter, call it in your main and give it two integers, for example hello(1, 2)
Note: If you want to do that you have to remove the scan.nextInt() from your code.
You forgot to pass two parameters a and b into method hello.
public static void main(String[] args) {
int a = 1;
int b = 2;
hello(a,b);
}

A simple java program

I have a problem statement
Problem
Write a program to calculate the sum of 2 numbers and print the output.
Input
Line 1: An integer.
Line 2: An integer.
Output :The output consists of a single integer which corresponds to sum, followed by a new line
Sample Input I
3
1
Sample Output I
4
Sample Input II
13
10
Sample Output II
23
To which my solution is
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Add {
public static void main(String[] args)throws IOException
{
int a=0, b=0, sum;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the numbers to be summed");
try{
a=sc.nextInt();
sc.nextLine();
b=sc.nextInt();
}
catch(InputMismatchException e){
System.out.println("Please enter an Integer number");
e.printStackTrace();}
catch(Exception e){System.out.println(e);}
sum=a+b;
System.out.println(sum);
sc.close();
}
}
I'm supposed to submit it to an online directory, that I assume tries to execute the program automatically. And when I do, it tells me
Wrong Answer Almost there,think some more
I think pondering over it for an hour is more than enough before you decide to call in for reinforcement.
The output should be "a single integer which corresponds to sum, followed by a new line".
But the output of your program is
Enter the numbers to be summed
<the sum>
remove sc.nextLine(). It makes it move to the next line, but since both integers are on the same line, the value for b remains at 0.
These can be solve by two thing command line arguments or Scanner class or BufferReader.
Using the Command line Arguments.
public Class Sum
{
public static void main(String [] args)
{
int a ,b,c;
a=Integer.parseInt(args[0]); //using Integer wrapper Class to cast object
to primitive Datatype Integer.
b= Integer.parseInt(args[1]) ;
c= a+b;
System.out.println("The Sum of two number is : "+c);
}
}
Using Command Line Arguments with code re usability(Method Sum)
public Class Sum
{
public static long sum(int a,int b)
{
return a+b;
}
public static void main(String [] args)
{
int a ,b;
long c; // for long summation of numbers .
a=Integer.parseInt(args[0]); //using Integer wrapper Class to cast object
to primitive Datatype Integer.
b= Integer.parseInt(args[1]) ;
c= sum(a,b);
System.out.println("The Sum of two number is : "+c);
}
}
Using the External resources from the java.util.Scanner
public Class Sum
{
public static void main(String [] args)
{
int a ,b;
long c;
Scanner scan;
scan = new Scanner(System.in) ; //Taking system Keyboard for input.
System.out.println("Enter the value of A: \n");
a= ss.nextInt() ;
System.out.println("Enter the value of B: \n");
b=ss.nextInt();
c= (long) (a+b);
System.out.println("The Sum of two number is : "+c);
}
}
Try this:
import java.util.Scanner;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num1 = 0;
int num2 = 0;
int sum = 0;
System.out.println("Enter Number: ");
num1 = in.nextInt();
System.out.println("Enter Number2: ");
num2 = in.nextInt();
sum = num1 + num2;
System.out.println(sum);
}
}
package stack;
public class Satck {
public static int MAX=100;
int top;
int [] a= new int [MAX];
boolean empty()
{
return (top<0);
}
Satck()
{
top=-1;
}
void push(int x)
{
a[++top]=x;
}
public int pop()
{
int x=a[top--];
return x;
}
public int peek()
{
int x=a[top];
return x;
}
public static void main(String[] args) {
Satck s=new Satck();
s.push(10);
s.push(11);
s.push(12);
s.push(13);
System.out.println(s.peek());
System.out.println(s.empty());
System.out.println(s.pop());
System.out.println(s.peek());
}
}

How would I return x and y from different classes to main in Java?

How would I return my x and y variable into main in order to perform the addition?
Thanks in advance for the help!
import java.util.Scanner;
public class calling {
public static int x;
public static int y;
public static void num1() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number: ");
x=scanner.nextInt();
}
public static void num2() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number: ");
y=scanner.nextInt();
}
public static void main(String[] args){ **//place to return variables.**
num1();
num2();
System.out.print("The sum of the two numbers is: " + (x+y));
}
}
public static int getInput() {
Scanner scanner = new Scanner(System.in);
return scanner.nextInt();
}
public static void main(String[] args){
System.out.println("Please enter a number: ");
int x = getInput();
System.out.println("Please enter a second number: ");
int y = getInput();
int sum = x + y;
System.out.print("The sum of the two numbers is: " + sum);
}
or a more OO (Object Orientated) approach might look like
public class Calculator {
private Scanner scanner;
public Calculator() {
scanner = new Scanner (System.in);
}
public int getInput() {
return scanner.nextInt();
}
public int add(int x, int y) {
return x + y;
}
public static void main(String[] args) {
Calculator calculator = new Calculator();
System.out.println("Please enter a number: ");
int x = calculator.getInput();
System.out.println("Please enter a second number: ");
int y = calculator.getInput();
int sum = calculator.add(x, y);
System.out.print("The sum of the two numbers is: " + sum);
}
Note that Java naming conventions state classes should have uppercase first letters.
You shouldn't be using static data members or methods - those should only be used when the member of method applies to all instances of a class.
In this case the only static method should be main and that should only create a single instance of the current class. main should almost never do any real work - although in this trivial example I suppose an exception could be made.
You should ideally also only create a single Scanner object - the Scanner class is perfectly capable of reading a continuous stream of numbers without you needing to create a new one over and over for each number to be read.
In the code below I just create one and use it twice directly.
import java.util.Scanner;
public class calling {
public calling() {
Scanner scanner = new Scanner (System.in);
System.out.print("Please enter a number: ");
int x = scanner.nextInt();
System.out.print("Please enter a second number: ");
int y = scanner.nextInt();
System.out.println("The sum of the two numbers is: " + (x + y));
}
public static void main(String[] args) {
new calling();
}
}
Alternatively the scanner object could have been stored as a member variable, as in this example:
import java.util.Scanner;
public class calling {
private Scanner scanner = null;
private int getInt(String prompt) {
System.out.print(prompt);
return scanner.nextInt();
}
public calling() {
scanner = new Scanner(System.in)
int x = getInt("Please enter a number: ");
int y = getInt("Please enter a second number: ");
System.out.println("The sum of the two numbers is: " + (x + y));
}
public static void main(String[] args) {
new calling();
}
}
Simply change the return types of num1 and num2 to int and save the result of both functions in variables in main. Then perform your addition with the new variables, or just change the addition to (num1() + num2()).
In addition to that, grab a book and try to understand how to use functions because what you're asking is pretty basic.
if you are looking for a way to return the values to main function, read the code below
import java.util.Scanner;
public class test {
public static int x;
public static int y;
public static int num1() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a number: ");
x=scanner.nextInt();
return x;
}
public static int num2() {
Scanner scanner = new Scanner (System.in);
System.out.println("Please enter a second number: ");
y=scanner.nextInt();
return y;
}
public static void main(String[] args){
int a = num1();
int b = num2();
System.out.print("The sum of the two numbers is: " + (a+b));
}
}

Categories

Resources