Issue with substring method - java

I wrote a little program that prompts a user to enter their first middle and last name I then attempt to locate each white space and store the name that comes after the whitespace into a new String variable.
Problem: I want to locate the white spaces before each part of the name so that I can take each relative name and store it in a new String variable but i'm not sure where I'm going wrong.
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String name = "",
firstName = "",
middleName = "",
lastName = "";
boolean isName = false;
while(!isName)
{
System.out.print("\nEnter your name as 'First Middle Last': ");
name = input.nextLine();
if(name.length() < 0)
{
System.out.print("\nEnter your name as 'First Middle Last': ");
name = input.nextLine();
System.out.print("Invalid input");
}
else isName = true;
}
for(int j = 0; j < name.length(); j++)
{
if(name.charAt(j) == ' ')
{
firstName = name.substring(0, j); // Start at 0 end at first white space
middleName = name.substring(j + 1, name.length());
lastName = name.substring(j + 1, name.length());
}
}
System.out.println("\nLast Name, First Name, Middle Name: " + lastName + firstName + middleName );
}
}
The output I'm getting looks like this
Enter your name as 'First Middle Last': Adam Thomas Smith
Last Name, First Name, Middle Name: SmithAdam ThomasSmith
Any suggestions as to how to fix this?

name = name.trim(); // To avoid suprises, as Pshemo suggested.
String[] splitName = name.split("\\s+");
System.out.println("\nLast Name, First Name, Middle Name: "
+ splitName[2] + " " + splitName[0] + " " + splitName[1]);
Try this instead. It uses String.split() to split the name on a space (\\s+, a regex) and returns the values as an array. The names could also be assigned to a variable if you choose.

You can try the following code, just by splitting the 'name' variable on each space into an String[] Then by getting each value from the array and assigning to the value you wish.
String[] str = name.split(" ");
firstName = str[0];
middleName = str[1];
lastName = str[2];

Better to use split(" ") function... It will change you string to an string array. Eg:-
String names = "Madan mohan malviya";
String arr[] = name.split(" ");
for( name :names){
System.out.println(name); // print each string content
}

Related

Make second word capital in a string

I don't really know how to explain the problem. I do have a scanner imported after the package. I'm not sure if you can stack methods, and if you can I'm definitely doing it wrong.
Scanner console = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = console.next();
name.trim();
name.toUpperCase(name.substring(name.charAt(name.indexOf(" "))));
System.out.println("Your name is: " + name);
Just split the String into the first word and second word based on the indexOf(" ")
Capitalize the second word using toUpperCase
Concatenate both words together using +
name = name.substring(0, name.indexOf(" ")) + name.substring(name.indexOf(" ")).toUpperCase();
Note: Not sure if you are required to handle invalid input, but this code would only work assuming a valid two-word name is entered, with a space in-between
Also, make sure to change console.next() to console.nextLine() to ensure you retrieve the entire line of input
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = console.nextLine();
String[] words = name.split(" ");
words[1] = capitalizeWord(words[1]);
name = String.join(" ", words);
System.out.println("Your name is: " + name);
}
private static String capitalizeWord(String s) {
s = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
return s;
}
At first you split the input into a String array. Then you replace the first character of the 2nd (index 1) element and join the array back to a String.
Input: john doe, Output: john Doe
String is immutable in java so if you want to "change" a Strig variable value, you need to reassign it to itself. I think a good approach to prepare more than 2 input, many people has middle name e.g.
This function split the input into parts then make the first letter uppercase then return the whole name after concat them with space.
public String capitalizeName(String name) {
String[] nameParts = name.split(" ");
for (int i = 0; i < nameParts.length; i++) {
nameParts[i] = nameParts[i].substring(0, 1).toUpperCase() + nameParts[i].substring(1);
}
return String.join(" ", nameParts);
}
String is immutable in Java.
BE SIMPLE!!!
public static void main(String... args) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.print("Enter your first name and last name: ");
String firstName = upperCaseFirstLetter(scan.next().trim());
String lastName = upperCaseFirstLetter(scan.next().trim());
System.out.println("Your name first name: " + firstName);
System.out.println("Your name last name: " + lastName);
}
private static String upperCaseFirstLetter(String name) {
return Character.toUpperCase(name.charAt(0)) + name.substring(1);
}
One solution would be to make the String a String array using the split(regex)-method. It will split up a string into a String array, breaking them up at regex.
For example:
String text = "This is a text.";
String textArray = text.split(" ");
for(String element : textArray)
{
System.out.println(element);
}
will print
This
is
a
text.
If you got a String[] like that, you can choose the second String (index 1 of array) and capitalize it. You can do so in a foreach loop, for example.
String text = "This is a text.";
text = text.trim(); // if you want to trim it.
String[] textArray = text.split(" ");
String newText = "";
int index = 0;
for(String element : textArray)
{
if(index == 1)
{
element = element.toUpperCase();
}
newText = newText + element + " ";
index++;
}
System.out.println(newText);
If you want to handle errors, you can put in in a try-catch-block like this.
try
{
[Your code]
}
catch (Exception e)
{
System.out.println("An error occured.");
}
This is, of course, not a very short way to do it. However, it's easy to understand and it can handle even a string consisting of several words.

Printing Abbreviated Names in Java

I'm trying to write code in Java that will output abbreviated names based on input. For example; if the input is "John Alex Smith", the output is "Smith, J.A." And if the input is "John Smith", the output is "Smith, J." my code works perfectly fine if a first, middle, and last name are input, but it doesn't work if only a first and last are input, and I can't figure out why?
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String firstName = scnr.next();
String middleName = scnr.next();
String lastName = scnr.next();
char middleInitial = middleName.charAt(0);
char firstInitial = firstName.charAt(0);
if (middleName.length() > 0 && lastName.length() == 0) {
lastName = middleName;
System.out.println(lastName + ", " + firstInitial + "."); }
else if (lastName.length() > 0) {
System.out.println(lastName + ", " + firstInitial + "." + middleInitial + "."); }
/* Type your code here. */
}
}
I assume your inputting 2 strings and then just pressing return for the case of a first and last name only? In which case firstName will have the first String. middleName will have the second String and then lastName will be an empty String . There are no conditions in your if else that support that siutation so nothing is printed.
You'll want to change it to check:
If firstName or middleName is null or empty then that's an error
Otherwise is last name not null and not empty? If so then that's 3 named input
Otherwise it's 2 named input

Issues with Java substring method

I wrote a program that prompts a user to input his/her full name First , middle , last. I'm attempting to break that name down into three separate pieces using the substring method by locating each white space in the string. Once each white space is found the following portion of the name is stored in a new string variable.
The issue I'm having is that the middle name is storing both middle and last because the counter isn't stopping correctly as you will see in my below code so my question is how can I fix this.
Please note, I do not want to split the string, I do not want to use a StringTokenizer, I do not want to use Arrays, I already know how to do it that way. All I need to know is how to fix my counter, what I am trying to do will work this way I'm not looking for a new way to do this; I'm only working with substring and charAt.
import java.util.Scanner;
public class Example
{
public static void main(String[] args)
{
String name = "",
firstName = "",
middleName = "",
lastName = "";
Scanner in = new Scanner(System.in);
System.out.print("Please enter your name 'First Middle Last': ");
name = in.nextLine();
int i = 0;
while(i < name.length())
{
if(name.charAt(i) == ' ')
{
firstName = name.substring(0, i); // Starts at 0 ends at first occurence of ' '
/* middleName = name.substring(i + 1, i); Should start at i + 1,
or one postion after the previously located white space and
then end at the next occurence of ' '
^ The above does not work, and this is where the issue is
happening, how ever if I do the following */
middleName = name.substring(i + 1, name.length());
/* This does work but because the endIndex is name.length() it
runs the length of name and grabs both the middle and last name.*/
i = name.length();
}
++i;
}
System.out.print("\nDisplayed with last name first: " + "\nLast Name: " + lastName + "\nFisrt Name: " + firstName + "\nMiddle Name: " + middleName);
}
}
The output this produces looks like this
Please enter your name 'First Middle Last': First Middle Last
Displayed with last name first:
Last Name:
First Name: First
Middle Name: Middle Last
As you can see first Name is displayed correctly.
Middle name is not because it included "Last" and not just "middle"
You could use indexOf(' ') and lastIndexOf(' ') to find first space and last space
everything before 1st space is firstname
everything after last space is lastname
the rest in the middle is middlename
Pseudocode:
firstName = name.substring(0, name.indexOf(' '));
middleName = name.substring(name.indexOf(' ') + 1, name.lastIndexOf(' '));
lastName = name.substring(name.lastIndexOf(' ') + 1);
Instead of substring you can use split function:
String string = "Peter Ralph Joseph"; //Here the string
String[] parts = string.split(" "); //Here the string it is divide taking as reference the space
System.out.println(parts[0]); //Peter
System.out.println(parts[1]); //Ralph
System.out.println(parts[2]); //Joseph
In my opinion, it is easier and faster to do it with split function.
Instead of running through a loop with charAt, if you really want to use substring you could just do:
int firstSpace = fullName.indexOf(' ');
String firstName = fullName.substring(0, firstSpace);
int secondSpace = fullName.indexOf(' ', firstSpace+1);
String middleName = fullName.substring(firstSpace+1, secondSpace);
String lastName = fullName.substring(secondSpace+1);
var mode = 0;
var last = 0;
for(i=0;i<name.length();i++)
{
if(name.charAt(i)==' '||i==(name.length()-1))
{
mode++;
var text = name.substring(last, i-last);
last = i+1;
if(mode==1) { firstName = text; }
else if(mode==2) { middleName = text; }
else if(mode==3) { lastName = text; break; }
}
}
do it in the following way:
no need to run the while loop.
firstName=name.substring(0,name.indexOf(' '));
middleName=name.substring(name.indexOf(' ')+1,name.lastIndexOf(' '));
lastName=name.substring(name.lastIndexOf(' ')+1,name.length());

Seeing if a index is negaitve

I am writing a program for my structured programming class and we have to take a input string, break it into 3 substrings and then check to see if all three names are there. I have the string broken up at the spaces and now I just need to check that there are three spaces. My professor told us that we had to make sure that there is a space between each name. He told me to simply test if the index of the space character is -1, because if it is the space wont be there. I just cant find a way to test it without getting a "string index out of range" error. Any help would be much appreciated. This is the code I am using to test the input string.
System.out.println("Enter filer full name (First Middle Last):");
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
int n = fullName.indexOf(' ');
int m = fullName.indexOf(' ', n + 1);
String firstName = fullName.substring(0, n);
String middleName = fullName.substring(n + 1, m);
String lastName = fullName.substring(m + 1);
Before you take the substrings, useif(n >-1 && m > -1) to tell if you have the spaces. Your new code would look something like this
System.out.println("Enter filer full name (First Middle Last):");
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
int n = fullName.indexOf(' ');
int m = fullName.indexOf(' ', n + 1);
if(n>-1&&m>-1){
String firstName = fullName.substring(0, n);
String middleName = fullName.substring(n + 1, m);
String lastName = fullName.substring(m + 1);
}else{
System.out.println("Don't have spaces!");
}
indexOf returns negative one if the input is not contained in the String. Also, String indices start at zero. So to test for it you would do something like this:
if (fullName.indexOf(" ") == -1)
{
System.out.print("Space not contained in fullName");
} //end if
How about just using a split
String fullname = "Scary Old Wombat";
String [] names = fullname.split (" ");
assert (names.length == 3);
You can use the indexOf() method for this.
Eg:
if(fullName.indexOf(' ') == -1){
// index of space is -1, means space is not present
}
Some names may or may not have a middle name as in John Doe while some names may have a middle name that comprises of more than 2 names as in John Smith Williams Joseph Doe.
Hence you can try this!
System.out.println("Enter filer full name (First Middle Last):");
Scanner input = new Scanner(System.in);
String fullName = input.nextLine();
String name [] = fullName.split(" ");
if(name.length == 1) {
System.out.println("You don't have spaces in the name");
}
else
if(name.length == 2) {
System.out.println("First Name: " + name[0]);
System.out.println("Last Name: " + name[1]);
}else
if(name.length > 2) {
System.out.println("First Name: " + name[0]);
System.out.print("Middle Name: ");
for (int i = 1; i < (name.length-1) ; i++) {
System.out.print(name[i] + " ");
}
System.out.println();
System.out.println("Last Name: " + name[(name.length-1)]);
}
Output - Enter filer full name (First Middle Last):
John Smith Williams Joseph Doe
First Name: John
Middle Name: Smith Williams Joseph
Last Name: Doe

fName.substring out of bounds

public class Registration {
public static void main(String[] args) {
final String MY_DELIMITER = "','";
boolean tryAgain = true;
String fName = "";
String A = fName.substring(0,2);
String lName = "";
int lNameLength = lName.length();
String B = lName.substring(lNameLength-4,lNameLength);
String address = "";
String zip = "";
String C = zip.substring(0,5);
String age = "";
String D = age.substring(0,1);
String gender = "";
String race = "";
String regList = "";
Scanner myScanner = new Scanner(System.in);
boolean showList = false;
// Get input from the user until they type "q"
// For each input check for "q"
// if not q, append the input
// to the existing String + the delimiter
while(tryAgain)
{
System.out.println("Name: (q to quit)");
fName = myScanner.nextLine();
System.out.println("Last Name: (q to quit)");
lName = myScanner.nextLine();
System.out.println("Addess: ");
address = myScanner.nextLine();
System.out.println("Age: ");
age = myScanner.nextLine();
System.out.println("Gender: ");
gender = myScanner.nextLine();
System.out.println("Race: ");
race = myScanner.nextLine();
if(fName.equals("q"))
{
tryAgain = false;
}
else
{
// Append new name to the list using a delimiter
regList = fName + lName + "\n" + address + "\n" + age + "\n" + gender + "\n" + race + MY_DELIMITER;
}
} // end of while( )
System.out.println("Here is your registration:" + regList);
// Convert the String into an array, using the same delimiter
String[ ] regArray = regList.split(MY_DELIMITER);
// Ask the user if they want to display the contents of the array
// If "y" then display the list using a foreach loop
System.out.println("Would you like to see the registration from the Array? [y-n]");
fName = myScanner.nextLine( );
myScanner.close();
fName = fName.toLowerCase( );
showList = fName.equals("y")?true:false;
if(showList)
{
// Display the results using for each
System.out.println("Here is your registration from the array: ");
// Use a for each statement instead of the more complex for( ) loop
// for(int counter=0; counter < employeeArray.length; counter++)
for(String thisReg:regArray)
{
System.out.println(thisReg);
System.out.printf("USER ID: ", A + "-" + B + "-" + C + "-" + D);
}
} // end of if(showList)
}
}
I am trying to extract out the first 3 letters of the fName input, so I figured I could use fName.substring to do that, but it gives me this error.
Sorry I didn't add all of my code, to save time. Apparently it looked confusing. Any way so the fName input is the name of the user. Can it not be in that order?
Erm...your sequence of operations is suspect. Everywhere, actually.
Look at the following interaction:
String fName = "";
String A = fName.substring(0,2);
You declare an empty string, then immediately take the substring of it. Where are you getting the data for the substring from? There's nothing to substring here - the empty string has a length of zero.
You should be certain that you're putting data into your string before taking a substring of it. Using a Scanner would go a long way here.
Or better yet, moving your instance of myScanner at the top of main would make it much clearer as to where that's supposed to go, and how it's supposed to work.
Always check the length of string before substring anything. Especially when a user is giving you this variable.
You are trying to get a substring of an empty string.
String fName = "";
String A = fName.substring(0,2); // here fName is empty!!!
Change fName into some actual String and also check for length of the String before calling substring to make sure substring of the size you want exists.
String fName = "somestring";
if(fName.length() >= 2) {
String A = fName.substring(0,2);
System.out.println(A); // prints out "so"
}
That is the case with all of your other Strings as well.

Categories

Resources