Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- /**
- * Input: One String with numbers. numbers are separated by a single space
- * Output: numbers recognized and their sum Allowed: isDigit() substring()
- * charAt() Integer.parseInt() length() Forbidden: split(), arrays or
- * collections
- */
- public class NumberParser {
- public static void main(String[] args) {
- // print out the welcome header that gives the user instructions:
- System.out.println("Welcome to the Number Parser! Please enter one line"
- + " of numbers, separated by a single space between each,"
- + " followed by a return.");
- // get the user input
- Scanner stdin = new Scanner(System.in);
- String line = stdin.nextLine();
- // make sure the user input isn't empty or null
- if (line == null) {
- System.out.println("Invalid input. Input was null");
- System.exit(0);
- }
- /*
- * Now we have a valid input, and can parse out the numbers
- */
- // set up variables that will keep track of things as we go
- int sum = 0;
- int beginIndex = 0;
- // step through the input String one character at a time.
- for (int currentIndex = 0; currentIndex < line.length(); ++currentIndex) {
- // get the character at the current index
- char currentChar = line.charAt(currentIndex);
- // if the character is NOT a digit, then we have reached the end of a number.
- if (!Character.isDigit(currentChar)) {
- // make sure the number substring has at least one character in it
- if (currentIndex - beginIndex > 0) {
- // pull out the number substring.
- String numberSubstring = line.substring(beginIndex, currentIndex);
- // convert that number substring into an integer
- int currentNumber = Integer.parseInt(numberSubstring);
- // print out the number
- System.out.print(currentNumber + ", ");
- // add the number to the running total
- sum = sum + currentNumber;
- }
- // we're on a non-digit character, so a new number substring might begin next character
- beginIndex = currentIndex + 1;
- }
- }
- // print out the sum
- if (sum > 0) {
- System.out.println("sum: " + sum);
- } else {
- System.out.println("No numbers present.");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement