Parsing Strings (JAVA)

I’m trying to complete this assignment, but I’m stuck on how to proceed.

import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);

        while (true)
        {
            System.out.println("Enter input string: ");
            String userInput = scan.nextLine();

            if (userInput.contains(","))
            {
                System.out.println("First word:  " + userInput.split(",")[0]);
                System.out.println("Second word:" + userInput.split(",")[1]);
                System.out.println("\n");
            }
            else if (!userInput.contains(","))
            {
                System.out.println("Error: No comma in string");

            }
            else if (userInput.equalsIgnoreCase("q"))
            {
                break;
            }
        }
        return;
    }

}

enter image description here

** I’ve fixed the issue with the quit, still need help with the weird whitespace.

>Solution :

Your code never actually goes to the last "else if", because "q" doesn’t contain a comma, so only the second "else if" is accessed. Also, you aren’t removing the spaces in your string, you still keep them after spliting the words.

Leave a Reply