0

I'm creating an application for my professor that takes several numbers entered from the user and sums them. I can't seem to figure out what I'm doing wrong. Any help will be appreciated. I tried different solutions, but I only got this far.

import java.util.*;
public class DebugSeven2
{
   public static void main(String[] args)
   {
      String str;
      int x;
      int length;
      int start;
      int num;
      int lastSpace = -1;
      int sum = 0;
      String partStr;
      Scanner in = new Scanner(System.in);
      System.out.print("Enter a series of integers separated by spaces >> ");
      str = in.nextLine();
      length = str.length();
      for(x = 0; x <= length; ++x)
      {
         if(str.charAt(x) == ' ')
         {
             partStr = str.substring(lastSpace);     
             num = Integer.parseInt(partStr);
             System.out.println("                " + num);
             sum += num;
             lastSpace = x;
          } 
      }
      partStr = str.substring(lastSpace + 1, length);
      num = Integer.parseInt(partStr);
      System.out.println("      " + num);
      sum += num;
      System.out.println("         -------------------" + "\nThe sum of the integers is " + sum);
   }
}
  • Describe what is your specific problem. Look at how you should ask a question https://stackoverflow.com/help/how-to-ask – Morph21 Mar 29 '22 at 12:51
  • @MrBrainBone, Welcome to SO, did you debug the code, your giving negative number to substring, check if that is allowed by substring() or not to get you started on your code error:) – Nishikant Tayade Mar 29 '22 at 12:55

1 Answers1

0

First of all, this is homework and SO isn't a place where people do other's homework. That said, I'll help you with the high level overview of the solution and more didactic rather efficient solution.

Instead of spaggetti code, create several functions that do the several steps that you need to solve. This will produce a 'longer' code but it'll be easier to read and understand.

This implementation below is not the most efficient but you can read the code, starting by main() and understand what's being done line by line. If there's any issue you can debug and test each function separately and make sure it covers all you use-cases.

Also, this implementation contains several advanced topics such as java 8 streams, intStreams, splitting string using regex. Some basic error handling to skip whatever the user inputs if is not parseable to Integer.

And it's important to remember: it's better to write readable and maintainable code rather than high-performing obfuscated code. If you need to iterate a list twice but it'll make the code clear, do it. If you know the list might have +1K elements, optimise.

public class Exercise {

    public String getUserInput() {
        //Implementation is left to you.
        return myString;
    }

    // https://stackoverflow.com/questions/7899525/how-to-split-a-string-by-space
    private List<String> splitStringBySpace(String input) {
        return Arrays.asList(input.split("\\s+"));
    }

    private List<Integer> convertListToIntegers(List<String> input) {
        return input.stream().map(str -> {
                    try {
                        return Integer.parseInt(str);
                    } catch (NumberFormatException ex) {
                        //Skip whatever is not parseable as a number
                        return null;
                    }
                }).filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
    
    private Integer sumList(List<Integer> input) {
        /* Alternative solution
        int acum = 0;
        for (int i = 0; i < input.size(); i++) {
            acum += input.get(i);
        }
        return acum;
       
         */
        return input.stream().mapToInt(i -> i).sum();
    }
    
    public static void main() {
        String inputText = getUserInput();
        System.out.println("User has entered: " + inputText);
        List<String> listOfNumbersAsString = splitStringBySpace(inputText);
        List<Integer> listOfNumbers = convertListToIntegers(listOfNumbersAsString);
        Integer myResult = sumList(listOfNumbers);
        System.out.println("Total = " + myResult);
    }

}

Alex Roig
  • 1,534
  • 12
  • 18