Programming Fundamentals/Strings/Java

strings.java

edit
// This program splits a given comma-separated name into first and last name
// components and then displays the name.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://en.wikibooks.org/wiki/Java_Programming

import java.util.*;

class strings {
    private static Scanner input = new Scanner(System.in);

    public static void main(String[] args) {
        String name;
        String last;
        String first;
        
        name = getName();
        last = getLast(name);
        first = getFirst(name);
        displayName(first, last);
    }

    private static String getName()
    {
        String name;
        int index;
        
        do
        {
            System.out.println("Enter name (last, first):");
            name = input.nextLine();
            index = name.indexOf(",");
        } while (index < 0);

        return name;
    }

    private static String getLast(String name)
    {
        String last;
        int index;
    
        index = name.indexOf(",");
        if(index < 0)
        {
            last = "";
        }
        else
        {
            last = name.substring(0, index);
        }
        
        return last;
    }

    private static String getFirst(String name)
    {
        String first;
        int index;
    
        index = name.indexOf(",");
        if(index < 0)
        {
            first = "";
        }
        else
        {
            first = name.substring(index + 1);
            first = first.trim();
        }
    
        return first;    
    }

    private static void displayName(String first, String last)
    {
        System.out.println("Hello " + first + " " + last + "!");
    }
}

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own Java compiler / interpreter / IDE.

See Also

edit