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