Как найти сумму двух чисел на java


Download Article


Download Article

Finding the sum of two numbers is simple, but it can get tedious if the numbers are big. Here is how you can create a Java program to find the sum of two numbers.

Steps

  1. Image titled Find the Sum of Two Numbers in Java Step 1

    1

    Plan your program. Finding the sum of two numbers isn’t difficult, but it is always a good practice to plan your program before beginning to code. Understand that you’d need two inputs/ parameters from the user for this program: the two numbers.

  2. Image titled Find the Sum of Two Numbers in Java Step 2

    2

    Write the code. Finding the sum of two numbers means the simple addition of both the numbers.[1]

    • Create a separate variable to store the value of the sum. This can be of the type int.
    • The formula to find the sum is:

      Sum = First Number + Second Number

    • To get these parameters (inputs) from the user, try using the Scanner function in Java.

    Advertisement

  3. Image titled Find the Sum of Two Numbers in Java Step 3

    3

    Display the output. Once the program has calculated the sum, display it to the user. Use the System.out.print or System.out.println (to print on a new line) function, in Java, for this.[2]

  4. Advertisement

Add New Question

  • Question

    Can the volume of a cuboid, cylinder, and cone be calculated by a switch statement taking suitable variables and data types?

    Living Concrete

    Living Concrete

    Top Answerer

    Yes. You may want to have the user specify what kind of shape before taking in any other input (such as dimensions).

  • Question

    How do I find the sum of numbers in Java?

    Community Answer

    Enter this code: import java.io.*;
    class addnumbers
    {
    public static void main(String args[])
    int a=10;b=20;c;
    c=a+b;
    System.out.println(“enter adding values”);
    }

  • Question

    How can I find the sum of 46 and 56?

    Community Answer

    Assume there are three integers (a, b, c): int a = 46; int b = 56; int c = a + b; System.out.println(c);

    Don’t forget the semicolons.

See more answers

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Sample Code

mScanner.nextInt();
      
      sum = firstNumber + secondNumber;
      
      System.out.println("The sum of the two numbers you entered = " + sum);
    }
}
  • Try expanding your program to perform multiple mathematical calculations.

  • Try making a GUI, which will make the program much more interactive and easier to use.

Thanks for submitting a tip for review!

Advertisement

About This Article

Thanks to all authors for creating a page that has been read 204,742 times.

Is this article up to date?

In this section, we will create Java programs to find the sum or addition of two numbers using the method and command-line arguments, the sum of three numbers, and the sum of n numbers.

Sum of Two Numbers in Java

In Java, finding the sum of two or more numbers is very easy. First, declare and initialize two variables to be added. Another variable to store the sum of numbers. Apply mathematical operator (+) between the declared variable and store the result. The following program calculates and prints the sum of two numbers.

SumOfNumbers1.java

Output:

The sum of numbers is: 340

Sum of Two Numbers in Java Using Method

There are two ways to find the sum of two numbers in Java.

  • By using User-defined Method
  • By using sum() Method

By Using User-defined Method

The Java Scanner class allows us to read input from the user. We take two numbers as input and pass them to the user-defined method sum(). The following program calculates the sum of two numbers using the method and prints the result.

SumOfNumbers2.java

Output:

Enter the first number: 34
Enter the second number: 12
The sum of two numbers x and y is: 46

By Using Integer.sum() Method

The Integer class provides the sum() method. It is a static method that adds two integers together as per the + operator. It can be overloaded and accepts the arguments in int, double, float, and long.

Syntax:

It returns the sum of the numbers that are passed as an argument. It throws ArithmaticException when the result overflows an integer value.

Note: If both arguments are negative, the result will be negative.

SumOfNumbers3.java

Output:

The sum of x and y is: 88
The sum of x and y is: -38

Similarly, we can calculate the sum of double, float, and long type numbers.

Sum of Two Numbers Using Command Line Arguments in Java

The command-line arguments are passed to the program at run-time. Passing command-line arguments in a Java program is quite easy. They are stored as strings in the String array passed to the args[] parameter of the main() method in Java.

SumOfNumbers4.java

Output:

The sum of x and y is: 101

First, compile the above program by using the command javac SumOfNumbers4.java. After that, run the program by using the command java SumOfNumbers4 89 12. Where 89 and 12 are command-line arguments.

Sum of Three Numbers in Java

The program for the sum of three numbers is the same as the sum of two numbers except there are three variables.

SumOfNumbers5.java

Output:

Enter the first number: 12
Enter the second number: 34
Enter the third number: 99
The sum of three numbers x, y, and z is: 145

Sum of N Numbers in Java

  1. Read or initialize an integer N (number of integers to add).
  2. Run a loop up to N times that ask to provide integers (to be added) again and again.
  3. Calculate the cumulative sum for each input and store it into a variable (sum).
  4. After terminating the loop, print the result.

Let’s implement the above steps in a Java program.

SumOfNumbers6.java

Output:

Enter Number of Numbers to be Calculated: 4
Enter the number: 12
Enter the number: 13
Enter the number: 5
Enter the number: 4
The sum of the numbers is: 34

Чтобы реализовать ввод чисел с клавиаутуры нужно воспользоваться классом Scanner из библиотеки пакетов Java. Данный класс нужно импортировать до создания основного класса Main.

Далее в методе мей мы создаем
объект scn класса Scanner. Стандартный поток ввода т.е клавиатура в Java представлен объектом — System.in.

Метод .nextInt() считывает целые числа типа int и присваиеват их в переменную a.

import java.util.Scanner; // импорт класса Scanner

public class Main {

   public static void main(String[] args) {

       Scanner scn = new Scanner(System.in); // объект класса Scanner

       System.out.println(“Введите число А = “);

       int a = scn.nextInt(); // считываем первое введенное число

       System.out.println(“Введите число В = “);

       int b = scn.nextInt();

       System.out.println(“Сумма = ” + (a+b));

   }

}

Решим еще одну подобную задачу. Условие задачи даны стороны треугольника. Найдите периметр треугольника. Решение подобно поэтому привожу только код программы.

import java.util.Scanner;

public class Main1{

   public static void main(String[] args) {

       System.out.println(“Введите сторону А = “);

       Scanner scn = new Scanner(System.in);

       int a = scn.nextInt();

       System.out.println(“Введите сторону B = “);

       int b = scn.nextInt();

       System.out.println(“Введите сторону C = “);

       int c = scn.nextInt();

       System.out.println(“Периметр треугольника равен = ” + (a+b+c));

   }

Пользователь вводит два числа и нужно найти сумму чисел между ними. Пример: 10 и 12, сумма которой будет 33. Но в моём случае программа почему-то всегда даёт сумму на три больше.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int m = scan.nextInt();
        int i = 0;
        if(m>n){
            while(n-1<m){
            n++;
            i +=n;
            }
            System.out.println(i);
      }
        
        
    }
}

Grundy's user avatar

Grundy

79.9k9 золотых знаков76 серебряных знаков133 бронзовых знака

задан 28 сен 2020 в 7:39

Аврелиус's user avatar

6

считайте по формуле арифметической прогрессии

Сумма n первых членов арифметической прогрессии вычисляется как:

(a_1 + a_n)*n/2

в вашем случае это

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int m = scan.nextInt();
        System.out.println((n + m)*(m - n + 1)/2);
        
    }
}

ну или по формуле

(n + m)*(m - n + 1)/2 это (10 + 12)*(12 - 10 + 1)/2 = 33

ответ дан 28 сен 2020 в 7:48

Aziz Umarov's user avatar

Aziz UmarovAziz Umarov

22.4k2 золотых знака10 серебряных знаков32 бронзовых знака

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    The java.lang.Integer.sum() is a built-in method in java that returns the sum of its arguments. The method adds two integers together as per the + operator. 

    Syntax : 

    public static int sum(int a, int b)

    Parameter: The method accepts two parameters that are to be added with each other: a : the first integer value. b : the second integer value. 

    Return Value: The method returns the sum of its arguments. 

    Exception: The method throws an ArithmeticException when the result overflows an int. 

    Examples:

    Input: a = 170, b = 455
    Output: 625
    
    Input: a = 45, b = 45
    Output: 90

    Below programs illustrate the Java.lang.Integer.sum() method: 

    Program 1: For a positive number. 

    java

    import java.lang.*;

    public class Geeks {

        public static void main(String[] args)

        {

            int a = 62;

            int b = 18;

            System.out.println("The sum is ="

                               + Integer.sum(a, b));

        }

    }

    Program 2: Below program illustrates the exception. 

    java

    import java.lang.*;

    public class Geeks {

        public static void main(String[] args)

        {

            int a = 92374612162;

            int b = 181;

            System.out.println("The sum is ="

                               + Integer.sum(a, b));

        }

    }

    Output:

    prog.java:8: error: integer number too large: 92374612162
           int a = 92374612162;
                   ^
    1 error

    Program 3 : Find the sum of integers using a loop

    Java

    import java.io.*;

    public class Arrays {

        public static void main(String[] args)

        {

            int[] arr = { 2, 4, 6, 8, 10 };

            int sum = 0;

            for (int i = 0; i < arr.length; i++) {

                sum += arr[i];

            }

            System.out.println("Sum of array elements is: "

                               + sum);

        }

    }

    Output

    Sum of array elements is: 30
    

    Last Updated :
    03 Apr, 2023

    Like Article

    Save Article

    Добавить комментарий