Java Lab #4: Loops

  1. Create a new project in your Eclipse workspace named Lab04 with a class of the same name. Put a main method in that class.

  2. Write a program that accepts a list of integers separated by spaces and prints the sum of all the integers in the list. Here is a sample run of the program.

            > 13 84 -18 79
            Sum is: 158
          

    Your program should use nextLine in the Scanner class to get a line of text from the user. It should then loop splitting integers off that line and using Integer.parseInt to convert the substrings into actually values of type int. Your program should then add each integer found to a running total (an "accumulator").

    If you suppose the integers are separated by a single space you could try using indexOf repeatedly.

            int currentPosition = 0;
            while (currentPosition < line.length()) {
                int nextSpacePosition = line.indexOf(' ', currentPosition);
                String numberText = line.substring(currentPosition, nextSpacePosition);
                // ...
            }
          

    Notice that this uses a version of indexOf that allows you to specify the starting point of your search. The loop above will not work for you as-is! It is only a sketch of an idea. You will need to make some adjustments to get the behavior you want.

    NOTE: The String class has a method split that breaks a string into multiple words. Don't use it. For one thing it uses arrays, a topic we haven't discussed yet, but in any case processing a line of input "manually" is a good exercise.

  3. OPTIONAL: Consider what it would take to correctly handle the case where there are multiple spaces between the integers.

Turn in your final program with appropriate comments. Be sure your name is on your submission.