Printing initials of First, Middle, Last name - java

This is the first time for me using java and I have been trying to solve a problem. The problem was to print two letters from each name(First, middle, last). But this has to be done with indexOf and substring methods.
I tried as much as I can with a sample development example in textbook, but it's too hard for me.
Ex) if my full name is Amit Kugar Chandra the output should be
ChKuAm.
I tried getting the user to input his name one word at a time, but is there any there a possible way to get the export especially two letters with one uppercase another lowercase?
package test;
import java.util.*;
public class Ch2Monogram {
public static void main(String[] args) {
String name;
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter(System.getProperty("line.separator"));
System.out.print("Enter your full name(first, middle, last): ");
name = scanner.next();
String first = name.substring(0, 2);
name = name.substring(name.indexOf(" ")+1, name.length());
String middle = name.substring(0, 2);
String last = name.substring(0, 2);
System.out.println("Name entered: " + last + middle + first);
scanner.close();
}
}

Related

Replace last two letters in Java

I am asking for help on this code that I am making, I want it to replace the last two letters. I am coding a program that will:
Replace four letter words with "FRED"
Replace the last two letters of a word that ends with "ed" to "id"
Finally, replace the first two letters if the word starts with "di" to "id"
I am having difficulty with the second stated rule, I know that for number 3 I can just use replaceFirst() and to use the length for the first rule, but I am not sure how to specifically swap the last two characters in the string.
Here is what I have so far:
package KingFred;
import java.util.Scanner;
public class KingFredofId2 {
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
String king = input.nextLine();
String king22 = new String();
String king23 = new String();
if(king.length()==4)
{
System.out.println("FRED");
}
String myString = king.substring(Math.max(king.length() - 2, 0));
if (myString.equals("ed"))
{
king22 = king.replace("ed", "id");
System.out.println(king22);
}
if(true)
{
king23 = king.replace("di", "id");
System.out.println(king23);
}
}
I am new to Stack Overflow, so please let me know how I can make my questions a little more understandable if this one is not easily comprehended.
Thanks.
There may be a way to more optimally combine the regular expressions, but this will work.
\\b - word boundary (white space, punctuation,etc).
\\b(?:\\w){4}\\b - four letter word
ed\\b - word ending with ed
\\bdi - word starting with di
replaceAll(regex,b) - replace what regex matches with string b
String s =
"Bill charles among hello fool march good deed, dirt, dirty, divine dried freed died";
s = s.replaceAll("\\b(?:\\w){4}\\b", "FRED")
.replaceAll("ed\\b", "id")
.replaceAll("\\bdi", "id");
System.out.println(s);
prints
FRED charles among hello FRED march FRED FRED, FRED, idrty, idvine driid freid F
RED
This is the most simplest way I could think to solve the second case of replacing the last two characters.
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a line or a word: ");
String s = sc.nextLine();
//getting the length of entered string
int length = s.length();
//initializing a new string to hold the last two characters of the entered string
String extract = "";
//checking if length of entered string is more than 2
if (length > 2) {
//extracting the last two letters
extract = s.substring(length - 2);
//updating the original string
s = s.substring(0, length - 2);
}
//checking if the last two characters fulfil the condition for changing them
if (extract.equalsIgnoreCase("ed")) {
//if they do, concatenate "id" to the now updated original string
System.out.println(s + "id");
} else {
//or print the originally entered string
System.out.println(s + extract);
}
}
}
I believe the comments are giving enough explanation and further explanation is not needed.

need help understanding, converting toCharArray() to a string

im fairly sure the mistake I am making within this code is short sighted.
so this program starts by getting the first name and last name of the user and storing them as independent strings. the next part is for the program to manipulate that value into getting the first initial of the first name, which is where im having my problem (I have little experience with the CharArray function and have spent enough independent research time for me to opt to asking here lmao)
import java.util.Scanner; //Needed for the Scanner class
public class NumericTypes {
public static void main (String [] args) {
//TASK #2 Create a Scanner object here
//Reading from system.in
Scanner keyboard = new Scanner(System.in);
//prompt user for first name
System.out.println("Enter your first name: ");
//scans the next input as a double
String firstName = keyboard.nextLine();
//prompt user for last name
System.out.println("Enter your last name: ");
//scans the next input as a double
String lastName = keyboard.nextLine();
//concatenate the user's first and last names
String fullName = (firstName + " " + lastName);
//print out the user's full name
System.out.println(fullName);
//task 3 starts here
//get first initial from variable 'fullName'
String firstinitial = fullName.CharAt(0);
System.out.println("the first initial is: " + firstinitial);
}
}
my desired output is for the last set of lines to display the first initial of the first name (user input). any help would be greatly, greatly appreciated
This can be done in two ways -:
1.) Replace String firstinitial with char firstinitial
2.) Wrap fullName.charAt(0) with String.valueOf like this:
String firstinitial = String.valueOf(fullName.charAt(0));
Both will work just fine.

Which methods of the String class to use to get string after a white space?

I started a java course a few weeks ago and today we were given a question sheet we will be doing in class tomorrow. I wanted to have a go at it myself tonight but alas I'm stuck on question 1.
We covered methods of the String class today but I can't figure out which if any of them to use.
So finally here's the question:
Q. Write and test a program which will prompt the user to enter their name and write to the screen just the surname. (Where the surname is interpreted as everything after the first white space)
And here's what I have so far:
import java.util.Scanner;
public class Question1 {
public static void main(String[] args) {
String fullName;
String surname;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your name: ");
fullName = keyboard.nextLine();
if(fullName.contains(" ")) {
// not sure what goes in here?
}
}
}
I've been messing around with the if statement above and also various methods of the String class like subString(), charAt() etc but I don't know how to find the first space and then print out the String after the first space.
You can do it by making use of indexOf() and subString() methods of String class: For e.g.,
public String substringAfter(String str) {
int pos = str.indexOf(" ");
if (pos == -1) {
return "";
}
return str.substring(pos + 1);
}
You could use what's in the comments, but you could use the split method too. It takes two parameters (or one, the second one is optional): the delimeter String and the limit. It returns the String array of splitted Strings. Example:
String[] splitted = fullName.split(" ", 2);
Now splitted[0] is the first name (part before first white space) and splitted[1] is the rest.
More info here: http://docs.oracle.com/javase/8/docs/api/java/lang/String.html
And in general you can find a lot in the Java API documentation.
UPDATE
1) I mistaked the limit, it should be 2 instead of 1
For clarification, here is the test:
public class Test
{
public static void main(String[] args)
{
String fullName = "Luiggi SecondName ThirdName NotMyLastNameYet StillNotMyLastNameCuzImaTroll";
String surname;
String[] splitted = fullName.split(" ", 2);
surname = splitted[1];
System.out.println(splitted[1]);
}
}
Output:
SecondName ThirdName NotMyLastNameYet StillNotMyLastNameCuzImaTroll
Would this work for you or do you only want String methods?
public static void main(String[] args) {
String fullName;
String surname;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your name: ");
fullName = keyboard.nextLine();
if(fullName.contains(" ")) {
Scanner nameScanner = new Scanner(fullName);
String name = nameScanner.next();
surname = nameScanner.nextLine();
}
}

Taking Portions of a String

I am working on an assignment which is confusing to me. It requires me to write a method called processName() that accepts a Scanner for the console as a parameter and prompts the user to enter a full name, then prints the last name first and then the first name last. For instance, if I enter "Sammy Jankins", it would return "Jankins, Sammy".
My plan is to go through the string with a for loop, find an empty space, and create two new strings out of it—one for the first and last name each. However, I am not sure if this is the right path and how to exactly do this. Any tips would be appreciated, thanks.
Here is what I have so far:
import java.util.*;
public class Exercise15 {
public static void main(String[] args) {
Scanner inputScanner = new Scanner(System.in);
processName(inputScanner);
}
public static void processName(Scanner inputScanner) {
System.out.print("Please enter your full name: ");
String name = inputScanner.next();
System.out.println();
int n = name.length();
String tempFirst;
for (int i = 0; i <= name.length()-1; i++) {
// Something that checks the indiviual characters of each string to see of " "exists
// Somethow split that String into two others.
}
}
}
Why don't you simply use String#split?
I won't solve this for you, but here what you should do:
split according to spaces.
Check if the size of the array is 2.
If so, print the second element then the first.
Tip: Viewing the API can save a lot of efforts and time.
Why not just to say:
String[] parts = name.split("\\s+");
String formattedName = parts[1] + ", " + parts[0];
I am leaving it for you as an exercise to support names that contain more than 2 words, for example "Juan Antonio Samaranch" that should be formatted as "Samaranch, Juan Antonio".
Using StringTokenizer will be more easier. Refer http://www.mkyong.com/java/java-stringtokenizer-example/ for example.
You can replace for loop with the following code:
int spaceIdx = name.indexOf(' '); // or .lastIndexOf(' ')
if (spaceIdx != -1) {
int nameLength = name.length();
System.out.println(name.substring(spaceIdx + 1) + ", " + name.substring(0, spaceIdx));
} else {
// handle incorrect input
}
I think you should also consider such inputs - Homer J Simpson
1.Use the StringTokenizer to split the string .This will be very helpful when you are trying to split the string.
String arr[]=new String[2]; int i=0; StringTokenizer str=new StringTokenizer(StringToBeSplited,"");
while(str.hasMoreTokens()){
arr[i++]=new String(str.nextToken());
}
System.out.println(arr[1]+" "+arr[0]);
That's all

Checking string formats in Java?

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
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.
Look at the matches method if you know how to use regex. If not think about indexOf and substring methods.
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html
You can use the substring and the indexOf functions of String class to get what you need.
String#indexOf: Get's the position of a String inside a String.
String#substring: Get's a substring contained in a String.
String s = "Luiggi Mendoza J.";
String x;
while(s.indexOf(" ") > 0) {
x = s.substring(0, s.indexOf(" "));
System.out.println(x);
s = s.substring(s.indexOf(" ") + 1);
}
x = s;
System.out.println(x);
The program output will be:
Luiggi
Mendoza
J.
Use a while loop to continuously check whether user entered a string that consists of 3 parts which are seperated via a single space character ' ', then use split() function to verify 3 parts of string. By using substring() as demonstrated here you can get names seperately:
public static void main ( String [] args )
{
String name = "";
boolean ok = false;
Scanner key = new Scanner( System.in );
while ( !ok )
{
System.out.print( "Enter your name as 'First Middle Last': " );
name = key.nextLine();
try
{
if ( name.split( " " ).length == 3 )
ok = true;
}
catch ( Exception e ){ }
}
if ( ok )
{
String firstName = name.substring(0, name.indexOf(" "));
String middleName = name.substring(firstName.length()+1,
name.lastIndexOf(" "));
String surname = name.substring(middleName.length()+firstName.length()+2,
name.length());
}
}
This works using Pattern/Matcher and regexs. Also guards against strings of length 1 when adjusting case.
private static String properCase(String str) {
return str.substring(0, 1).toUpperCase()
+ (str.length() >= 1 ? str.substring(1).toLowerCase() : "");
}
public static void main(String[] args) {
boolean found = false;
do {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name as 'First Middle Last': ");
Pattern p = Pattern.compile("\\s*(\\w+?)\\s(\\w+?)\\s(\\w+)+\\s*");
Matcher m = p.matcher(scanner.nextLine());
found = m.find();
if (found) {
String first = m.group(1);
String middle = m.group(2);
String last = m.group(3);
String revised = properCase(first) + " " + properCase(middle)
+ " " + properCase(last);
System.out.println(revised);
System.out
.printf("%s %s %s.\n", properCase(last),
properCase(first), middle.substring(0, 1)
.toUpperCase());
}
} while (!found);
}

Categories

Resources