将用户输入的值相加并打印出来 [英] Adding user-inputted values together and printing them

查看:37
本文介绍了将用户输入的值相加并打印出来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将用户输入的字符串的值作为 Java 项目添加到该程序中.我试过解析但它似乎不起作用,我想不出许多其他简单的方法来找到字符串值的总和并打印它们.

I need to add values of a user-inputted string together for this program as a Java project. I've tried parsing but it doesn't seem to work, and I can't think of many other simple ways to find the sum of the string values and print them.

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?

    }
}

推荐答案

你可以写下面的逻辑:

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

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

这篇关于将用户输入的值相加并打印出来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆