fName.substring out of bounds - java

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.

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.

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
}

Use StringTokenizer to count number of words and characters in words

The objective is to get a sentence input from the user, tokenize it, and then give information about the first three words only (word itself, length, and then average the first 3 word lengths). I'm not sure how to turn the tokens into strings. I just need some guidance - not sure how to proceed. I've got this so far:
public static void main(String[] args) {
String delim = " ";
String inSentence = JOptionPane.showInputDialog("Please enter a sentence of three or more words: ");
StringTokenizer tk = new StringTokenizer(inSentence, delim);
int sentenceCount = tk.countTokens();
// Output
String out = "";
out = out + "Total number of words in the sentence: " +sentenceCount +"\n";
JOptionPane.showMessageDialog(null, out);
}
I'd really appreciate any guidance!
If you just wanted to get the first 3 tokens, then you could do something like this:
String first = tk.nextToken();
String second = tk.hasMoreTokens() ? tk.nextToken() : "";
String third = tk.hasMoreTokens() ? tk.nextToken() : "";
From there should be pretty easy to calculate the other requirements
public static void main(String[] args) {
String delim = " ";
String inSentence = JOptionPane.showInputDialog("Please enter a sentence of three or more words: ");
StringTokenizer tk = new StringTokenizer(inSentence, delim);
int sentenceCount = tk.countTokens();
// Output
String out = "";
out = out + "Total number of words in the sentence: " +sentenceCount +"\n";
JOptionPane.showMessageDialog(null, out);
int totalLength = 0;
while(tk.hasMoreTokens()){
String token = tk.nextToken();
totalLength+= token.length();
out = "Word: " + token + " Length:" + token.length();
JOptionPane.showMessageDialog(null, out);
}
out = "Average word Length = " + (totalLength/3);
JOptionPane.showMessageDialog(null, out);
}
The way to get the individual strings by using nextToken().
while (tk.hasMoreTokens()) {
System.out.println(st.nextToken());
}
You're free to do anything else than printing them, of course. If you only want the three first tokens, you might not want to use a while loop but a couple of simple if statements.

Print only twelve characters from user submitted string in Java

I have a user input their name as a string and then the name is printed out onto the screen. How can i limit what is printed to only 12 characters so that a user cannot type an insanely long name? Here is my code:
Scanner input = new Scanner(System.in);
System.out.print("Enter your player name: ");
String name= input.next();
System.out.print("\n" + name + " has started the game\n");
Something like:
String name = input.next();
name = name.length() > 12 ? name.substring(0, 11) : name;
and accept some of your previous answers.
{
public static void main (String[]args){
String s = new String();
String n = new String();
s = "ya ali madad";
if (s.length() > 10) {
n = s.substring(10, 12);
}
System.out.println("String s:" + s);
System.out.println("String n:" + n);}}

Categories

Resources