Emily
Emily

Reputation: 1

java program: Adding Integers from users string input

For this program I am taking input as a string with the following format: A name, followed by integers separted by spaces. There can be one or more integers in the series. Its output ends up being the name of the series and its sum. Here is an example of the what the output should be:

Series? seriesname 1 3 5 7 11
sum(seriesname) = 27

I am having problems with my code, It keeps having issues with this line (the exception):

int number = Integer.parseInt(series.substring(start, space));

I have moved quite a bit around but this is what I have right now:

import java.util.Scanner;

public class NamePlusAddingInts {
    public static String series;
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Series? ");

        series = scan.nextLine();
        String name = series.substring(0, series.indexOf(' '));

        System.out.print("Sum(" + name + ") = " + number);
    }
    public static int adding() {
        int space = series.indexOf(' ');

        while (space != -1) {
            int start = space + 1;
            int number = Integer.parseInt(series.substring(start, space));

            number = number + number;
            space++;
        }
        return number;
    }
}

Upvotes: 0

Views: 1609

Answers (2)

jials
jials

Reputation: 13

A better implementation of the adding() method will be to break the long string into a string array. You can call the String method, split(" ") to convert the string into string array.

public static int adding(String input) {
    int sum = 0;
    String[] array = input.split(" ");

    //starts from 1 because array[0] is the name of the series
    for (int i = 1; i < array.length; i++) {
        sum += Integer.parseInt(array[i]);
    }
    return sum;
}

Hope this helps!

Upvotes: 0

FruitAddict
FruitAddict

Reputation: 2032

You're overthinking it. You have clear separators between things that interest you, you could just split the string at spaces, take the first element as name and make the code much clearer, consider this:

    String numbers = "name 5 20 26 4 2 13";
    String[] splitNumbers = numbers.split(" ");

    int sum =0;
    String name = splitNumbers[0]

    for(int i = 1; i < splitNumbers.length ; i++){
        sum += Integer.parseInt(splitNumbers[i]);
    }

Now just change the hard-coded numbers value to user input and its done. You can surround it in try-catch to check for format exceptions if you're afraid of user inputting something other than numbers.

Upvotes: 1

Related Questions