Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading