search
HomeJavajavaTutorialJava program to print the sum of numbers

There are different ways of adding the numbers in Java. The numbers to be added can be given as input at runtime or can be put directly inside the program. However, it is difficult to add numbers in this way if the list of numbers is too big. Sometimes, the data to be added is given in an excel spreadsheet/ google sheet. So, the easy way is to save the excel spreadsheet /google sheet into a file with extension CSV (Comma Separated Values) and then CSV file’s column can be selected for adding up the values together using Java program. In this article, both the approaches of summations of numbers are specified.

多种方法

对于通过Java程序进行数字求和,使用以下两种方法。

  • Approach 1: Getting the numbers from the user at runtime.

  • 方法2:使用Java通过csv文件添加数字。

Let’s see the programs along with the output one by one.

方法一:在运行时从用户获取数字

In this approach, the scanner class will be used to take the user input and write the necessary code to print the computed result.

算法

  • Step 1 − Ask the user how many numbers the user want to add.

  • Step 2 − Ask the user the numbers to be added.

  • 第三步 - 添加输入的数字。

  • 步骤 4 - 显示数字的总和。

示例(方法1)

import java.util.Scanner;
public class newarr {
   public static void main(String[] args) {
      int nn;
      
      // Scanner is used to take input from the user
      Scanner scnn=new Scanner(System.in);
      System.out.print("Enter the number of items you want to add: ");
      
      //get the input
      nn=scnn.nextInt();
      int[] arrayofNum = new int[10];
      System.out.println("Enter the numbers to be added: ");
      for(int n=0; n<nn; n++){
         arrayofNum[n]=scnn.nextInt();
      }
      int summ = 0;
      
      // adding Numbers
      for (int m = 0; m < arrayofNum.length; m++)
      summ += arrayofNum[m];
      
      // printing the sum
      System.out.println("Sum of given array is "+ summ);
   }
}

Output

Enter the number of items you want to add: 10
Enter the numbers to be added:
200
320
56
67
6768768
5454
67667
7878
78
99
Sum of given array is 6850587

Approach-2: Adding the numbers through CSV file using Java

In this approach, Excel spreadsheet are used. Then as per the algorithm, the program code would fetch the numbers which are presented in the sheet and the addition of the numbers would be displayed in output.

算法

  • 步骤 1 − 将Excel电子表格/ Google表格保存为CSV格式。

  • 第二步 - 逐行读取CSV文件。

  • Step 3 − Skip the header lines.

  • 第四步 − 选择要添加数据的列号。

  • 第五步 - 将字符串类型的数据转换为数值形式。

  • 步骤 6 − 添加指定列的数字。

  • Step 7 − Print the result.

Java program to print the sum of numbers

CSV file Content

Year,2022
Months,Icecream sales (Rs)
Jan,100034
Feb,245767
Mar,391500
Apr,537233
May,682966
Jun,1028699
Jul,974432
Aug,890165
Sep,265898
Oct,141163
Nov,135736
Dec,103097

例子(方法2)

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;
public class numbers {
   public static void main(String[] args) throws Exception {
      
      // specify the header lines in the csv file to skip
      int headerlines=2;
      int sum=0;
      
      // Read the csv file
      File file = new File("icecream_sales.csv");
      
      // Read all lines
      List<String> lines = Files.readAllLines(file.toPath(),StandardCharsets.UTF_8);
      
      // variable to hold int values after conversion
      int a;
      //current row number
      int rowcount=1;
      for (String line : lines) {
         
         //skip the number of header lines in csv file
         if (rowcount<=headerlines){
            rowcount=rowcount+1;
            continue;
         }
         String[] array = line.split(",", -1);
      
         //read the numbers from the second column after skipping the header lines
         a= Integer.parseInt(array[1]);
         System.out.println("Icecream Sales (in INR) for the month of "+ array[0] + " is "+ a);
        
         //Adding the numbers from the second column of CSV file
         sum =sum +a;
      }
      
      // printing the sum
      System.out.println("Total sum (in INR) for icecream sale in the given year is :" + sum);
   }
}

Output

Icecream Sales (in INR) for the month of Jan is 100034
Icecream Sales (in INR) for the month of Feb is 245767
Icecream Sales (in INR) for the month of Mar is 391500
Icecream Sales (in INR) for the month of Apr is 537233
Icecream Sales (in INR) for the month of May is 682966
Icecream Sales (in INR) for the month of Jun is 1028699
Icecream Sales (in INR) for the month of Jul is 974432
Icecream Sales (in INR) for the month of Aug is 890165
Icecream Sales (in INR) for the month of Sep is 265898
Icecream Sales (in INR) for the month of Oct is 141163
Icecream Sales (in INR) for the month of Nov is 135736
Icecream Sales (in INR) for the month of Dec is 103097
Total sum (in INR) for icecream sale in the given year is :5496690

Conclusion

In this article, two different programs are given to add the numbers using the java code. In the first approach, the numbers are given by the user at run time and in the second approach, the numbers are taken from a column of a CSV file for summation.

The above is the detailed content of Java program to print the sum of numbers. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
What are the advantages of using bytecode over native code for platform independence?What are the advantages of using bytecode over native code for platform independence?Apr 30, 2025 am 12:24 AM

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Is Java truly 100% platform-independent? Why or why not?Is Java truly 100% platform-independent? Why or why not?Apr 30, 2025 am 12:18 AM

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

How does Java's platform independence support code maintainability?How does Java's platform independence support code maintainability?Apr 30, 2025 am 12:15 AM

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

What are the challenges in creating a JVM for a new platform?What are the challenges in creating a JVM for a new platform?Apr 30, 2025 am 12:15 AM

The main challenges facing creating a JVM on a new platform include hardware compatibility, operating system compatibility, and performance optimization. 1. Hardware compatibility: It is necessary to ensure that the JVM can correctly use the processor instruction set of the new platform, such as RISC-V. 2. Operating system compatibility: The JVM needs to correctly call the system API of the new platform, such as Linux. 3. Performance optimization: Performance testing and tuning are required, and the garbage collection strategy is adjusted to adapt to the memory characteristics of the new platform.

How does the JavaFX library attempt to address platform inconsistencies in GUI development?How does the JavaFX library attempt to address platform inconsistencies in GUI development?Apr 30, 2025 am 12:01 AM

JavaFXeffectivelyaddressesplatforminconsistenciesinGUIdevelopmentbyusingaplatform-agnosticscenegraphandCSSstyling.1)Itabstractsplatformspecificsthroughascenegraph,ensuringconsistentrenderingacrossWindows,macOS,andLinux.2)CSSstylingallowsforfine-tunin

Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor