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?
}
}
include: sum += Integer.parseInt(number[counter])
in your for loop and print it at last
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?
you can write below logic :
for(int i=0;i<number.length;i++){
try{
sum+=Integer.parseInt(number[i]);
}
catch( Exception e ) {
}
}
System.out.println("The sum is:"+sum);
使用流 (在Java 8中引入),您可以将总和写成一行:
int sum = Arrays.stream(number).mapToInt(Integer::valueOf).sum();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.