Issues with Java substring method - java

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());

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.

Using .length() in Java

I have to enter something like John Doe 12345 99 where First name is John, last name is Doe, ID is 12345, and wage is 99. It needs to be all in one string separated by spaces. So I have this:
while(x < Info.length()){
if(Info.charAt(x) == ' '){
First = Info.substring(0,x);
Last = Info.substring(x + 1, Info.length());
IDNum = Integer.parseInt(Info.substring(x + 2, Info.length()));
Wage = Double.parseDouble(Info.substring(x + 3, Info.length()));
x = Info.length();
}
++x;
}
I'm having trouble on the .length(); The example in the book only showed how to break up a string with two words in it. It's the length on IDNum and Wage. I'm not sure where to start them and end them. I think I need to change the ending for the length() when the Last calls it.
If it's separated by a space why not use the split() method:
String info = "John Doe 12345 99";
String[] seperatedInfo = info.split(" ");
String firstName = seperatedInfo[0];
String lastName = seperatedInfo[1];
int ID = Integer.parseInt(seperatedInfo[2]);
double pay = Double.parseDouble(seperatedInfo[3]);
System.out.println(firstName);
System.out.println(lastName);
System.out.println(ID);
System.out.println(pay);
Output:
John
Doe
12345
99
Also side note Java naming conventions for variables is to start with lower case and use camelCase
So, assuming you're not allowed to use something like String#split, which would be my personally preferred method, you could, instead, make use of the indexOf functionality, which supplies a couple of different ways to find the index of the a given character or String within a String.
So, something like...
String text = "John Doe 12345 99";
int index = text.indexOf(" ");
int lastIndex = 0;
while (index > -1) {
String part = text.substring(lastIndex, index);
System.out.println("[" + part + "]");
lastIndex = index + 1;
index = text.indexOf(" ", lastIndex);
}
if (lastIndex != 0) {
String part = text.substring(lastIndex);
System.out.println("[" + part + "]");
}
prints out...
[John]
[Doe]
[12345]
[99]
What I would do, is modify the above to maintain a "counter", which represents the current element you are "extracting" and then add that to the corresponding array element
Caveat: This will work for single "spaces" only, so just beware of that. You could also make use of String#trim to trim of leading and trailing spaces, but would require you to manually disassemble the String (using String#substring)
There are several ways you can parse that String, I would start by spliting it; then assign the tokens as desired. Something like,
String info = "John Doe 12345 99";
String[] tokens = info.split("\\s+");
String first = tokens[0], last = tokens[1];
int id = Integer.parseInt(tokens[2]);
double wage = Double.parseDouble(tokens[3]);
System.out.printf("%d %s, %s %.2f%n", id, last, first, wage);
Which outputs
12345 Doe, John 99.00
Filling tokens without split is still the approach I would take if limited in the methods I can use. You know there are four tokens, and you can use successive calls to indexOf(char) to find spaces. Like,
String info = "John Doe 12345 99";
int p = 0, c = 0;
String[] tokens = new String[4];
while (c < 4) {
int p1 = (c != 3) ? info.indexOf(' ', p) : info.length();
tokens[c] = info.substring(p, p1);
p = p1 + 1;
c++;
}
The rest of the answer above does not need to change.
You can also use StringTokenizer class.
Example:
String str = "John Doe 12345 99";
String delimeter = " ";
StringTokenizer stringTokenizer = new StringTokenizer(str, delimeter);
while (stringTokenizer.hasMoreTokens()) {
System.out.println(stringTokenizer.nextToken());
}

I have an error in java(Netbeans).Any suggestions?

This is the code.The code is enabled to extract the first letter from a person with 2 names but is unable to extract the first character with a person with 1 name since i am using split.
String name = jTextField1.getText().toUpperCase() + "";
String Surname = jTextField2.getText().toUpperCase().toString();
String Names[] = new String[1];
Names = name.split(" ");
int x = Names[1].length();
String initials = "";
if(x>0) {
initials = (Surname)+" "+(Names[0].charAt(0)+"") +(Names[1].charAt(0)+"");
jTextArea1.append("Wakefileds property "+"\n"+initials);
} else {
initials = (Surname)+ " " + (Names[0].charAt(0) + "");
jTextArea1.append("Wakefileds property "+"\n"+initials);
}
Try it like this
if (there are 2 words)
//check both words
else
//just check one word
Just add an if statement to check whether the length of Names is greater than 1 and adjust your logic accordingly.

Issue with substring method

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
}

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

Categories

Resources