Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking string formats in Java?

Tags:

java

string

having problems doing something for a class I'm taking, since I missed a class or two. (I know it's looked down on to 'do someone's homework,' but I'm not looking for that.)

The assignment is as follows:

Write a program to do the following:

  • Prompt for input of someone's first, middle, and last name as a single string (using any combination of upper and lowercase letters).
  • Check to make sure the name was entered in the correct format (3 names separated by spaces). If the input is not correct, continue to request the input again until the format is correct.
  • Capitalize only the first letters of each part of the name, and print out the revised name.
  • Print out the initials for that name.
  • Print out the name in the format of: Lastname, Firstname, MI.

The major problem I'm having is the second part of the assignment; I got the first part, and I'm fairly sure I can manage through the rest, after I get the second set up.

import java.util.*;

public class TestStrings
{
public static void main(String[] args) 
{
    Scanner key = new Scanner(System.in);
    String name;
    System.out.print("Enter your name as 'First Middle Last': ");
    name = key.nextLine();




}
}

From what I've gathered, I need to use the string.split? I'm not sure how to go about this, though, since I need to check to make sure there are three spaces, that aren't just right next to each other or something, such as "John(three spaces)Doe". I assume it's going to be some kind of loop to check through the input for the name.

The catch 22, is that I can't use arrays, or StringTokenizer. I must use the substring method.

Any help would be appreciated. Thanks. :D

like image 773
Steven Hickey Avatar asked Dec 04 '25 10:12

Steven Hickey


1 Answers

To point you in the right direction to find the first name(since you cant use arrays):

String firstName = input.substring(0, input.indexOf(" "));

This will get you a substring from the start to the first space. If you research the indexOf and substring methods you should be able to go from there.

like image 142
jzworkman Avatar answered Dec 05 '25 23:12

jzworkman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!