将用户输入的值加在一起并打印它们

时间:2018-10-10 11:06:06

标签: java arrays string sum

我需要将此程序的用户输入字符串的值加在一起作为Java项目。我已经尝试了解析,但是它似乎没有用,而且我想不出许多其他简单的方法来查找字符串值的总和并打印它们。

import java.util.Scanner;

public class Lab4 {

    public static void main(String[] args) {

        int length;
        int counter;
        int sum = 0;

        Scanner input = new Scanner(System.in);

        System.out.println("How many numbers will you enter"); // input prompt
        length = input.nextInt();

        String[] number = new String[length];

        for (counter = 0; counter < length; counter++) {
            System.out.print("Number " + (counter + 1) + ": ");
            number[counter] = input.next();
        }

        input.close();

        System.out.print("The summation of ");
        for (counter = 0; counter < length - 1; counter++) {
            System.out.print(number[counter] + ", ");
        }
        System.out.print("and " + number[counter] + " is: ");

        System.out.print(""); // How would I go about printing a sum ofthe values of the string?

    }
}

3 个答案:

答案 0 :(得分:0)

在您的for循环中包括:sum += Integer.parseInt(number[counter])并最终打印出来

for(counter = 0; counter < length-1; counter++){
  System.out.print(number[counter] + ", ");
  sum += Integer.parseInt(number[counter]);
 } 


System.out.print(sum); // How would I go about printing a sum ofthe values of the string?

答案 1 :(得分:0)

您可以编写以下逻辑:

for(int i=0;i<number.length;i++){
    try{
        sum+=Integer.parseInt(number[i]);
    }
    catch( Exception e ) {

    }
}
System.out.println("The sum is:"+sum);

答案 2 :(得分:0)

使用streams(在Java 8中引入),您可以将总和写成一行:

int sum = Arrays.stream(number).mapToInt(Integer::valueOf).sum();