I have one String text that i would like to split,result i want to get is that when i take text/split output each part like for example: Name: John, Last Name: Davidson, Date of Birth: 05051968, Place of Birth: London. But i am not getting correct result. my code is following:
public class Person{
public String name;
public String lastName;
public String dateOfBirth;
public String placeOfBirth;
poblic void printDetails(){
String text = "John.Davidson/0505168/London Micheal.Bartson/06061680/Paris";
String[] newText = text.split("[./ ]");
for(int i=0; i<newText.length; i++){
String name = newText[i].split("")[0];
String lastName = newText[i].split("")[0];
String dateOfBirth = newText[i].split("")[0];
String placeOfBirth = newText[i].split("")[0];
System.out.println("Name: " + name + ", last name: " + lastName + ", date of birth: " + dateOfBirth + ", place of birth: " + placeOfBirth);
}
Result i am getting is following:
Name: J, last Name: J, date of birth: J, place of birth: J
Name: D, last name: D, date of birth: D, place of birth: D .......
and it goes like that for every first character in text. Please can some one look and tell me where i am mistaking?
The results of the split come in groups of four, so you need to set the step of your loop at 4, and get the individual parts through offsets 0, 1, 2, and 3, like this:
for(int i=0; i<newText.length; i+=4){
String name = newText[i];
String lastName = newText[i+1];
String dateOfBirth = newText[i+2];
String placeOfBirth = newText[i+3];
System.out.println("Name: " + name + ", last name: " + lastName + ", date of birth: " + dateOfBirth + ", place of birth: " + placeOfBirth);
}
Demo.
You're splitting using the "" which means split every character. Then you take the first character. I don't know why you're doing it that way.
In summary, what happens in every loop is it takes the first character ([0]) of element i of the array, then sets every single value that wil lbe printed in the string to that character. Instead, try this
String[] newText = text.split("[./ ]");
for(int i = 0; i < newText.length - 4; i+=4){
System.out.println("Name: " + newText[i] + ", last name: " + newText[i+1] + ", date of birth: " + newText[i+2] + ", place of birth: " + newText[i+3]);
}
However, this is a terrible solution, it relies on fixed sized entries and should not be used in practice. What if someone enters the string in a different order, or with one too many inputs or one too few? Try using more flexible designs, such as the usage of a csv format parser, so you always split using commas, and the rows can be something like
entry-type, entry
entry-type, entry2
entry-type, entry3
Or something like that. Try it out. Always try to aim for flexible solutions that don't rely on exact input to work, otherwise you will have exceptions and runtime issues like there's no tomorrow.
PS the point of the split() method is to split the string between occurences of the specified input, i.e. [./], so don't use it if you want to just give a "", that's no different than making a charArray (except instead of char[] it is String[])
Related
For example the name Donald trump (12 character) brings up the error string index out of range 7 (where the space is found) even though the name Donald trump is longer.
package test;
import javax.swing.JOptionPane;
public class Usernamesubstring {
public static void main(String[] args) {
String fullname = JOptionPane.showInputDialog("What is your full name");
int breakbetween = fullname.lastIndexOf(" ");
String firstnamess = fullname.substring(breakbetween - 3, breakbetween);
int length = fullname.length();
String lastnamess = fullname.substring(length - 3, length);
String firstnamec = firstnamess.substring(0, 0);
String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 );
firstnamec = firstnamec.toUpperCase();
lastnamec = lastnamec.toUpperCase();
String firstname = firstnamess.substring(1,3);
String lastname = firstnamess.substring(1,3);
firstname = firstnamec + firstname;
lastname = lastnamec + lastname;
System.out.println(firstname + lastname);
}
}
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
at java.lang.String.substring(String.java:1963)
at test.Usernamesubstring.main(Usernamesubstring.java:14)
You've made it more complicated than it needs to be. A simple solution can be made using String.split (which divides a string into an array of smaller strings based on a delimiter, e.g. "Donald Trump".split(" ") == {"Donald", "Trump"})
Full Code
class Usernamesubstring // change that since it no longer uses substrings
{
public static void main (String[] args)
{
String fullName = "Donald Trump";
String[] parts = fullName.split(" ");
String firstName = parts[0]; // first item before the space
String lastName = parts[parts.length - 1]; // last item in the array
System.out.println(firstName + " " + lastName);
}
}
sometimes independent of your indexes
String fullName = "Donald Trump";
String[] result = fullName.split (" ");
in result you will find now
result [0] ==> Donald
result [1] ==> Trump
isn't that a little easier for your project?
Your error shoul be in the line String lastnamec = lastnamess.substring(breakbetween + 1, breakbetween + 1 ); as lastnamess is a string of lenght 3 from fullname.substring(length - 3, length); and breakbetween is greater then 3 for "Donald Trump", where space is character 6.
You should simpify your code a bit, it makes it easier to read and find the problems.
tl;dr: The exception occurs when you try to access a String at an index which exceeds it's length or is just not contained in the string (negative values).
Regarding your approach: It's usually not a good idea to prompt a name in full because people tend to input weird stuff or mix up the order. Better prompt for first and last name separately.
Assuming someone input his name with Firstname Lastname you wouldn't have to make such a substring mess, Java has some nice features:
String name = "Mario Peach Bowser";
name = name.trim();
String[] parts = name.split(" ");
String lastname = parts[parts.length-1];
String firstname = name.replace(lastname, "").trim();
System.out.println("Hello "+firstname+", your last name is: "+lastname);
In this case I am using the trim() function to remove whitespaces at the start and end and just split the string when a white space occurs. Since people can have some middle names and stuff, I just replace the last name out of the raw input string, call trim() on it again and you have everything extracted.
If you really want a substring approach, the following would work:
String lastname = name.substring(name.lastIndexOf(" ")).trim();
String firstname = name.substring(0,name.lastIndexOf(" ")).trim();
You usually don't store the index variables. But each variant would need some sort of error check, you can either use try{} and catch() or check the String before parsing.
Only these lines are required.
String[] nameArr = fullname.split(" ");
String lastN = nameArr[nameArr.length - 1];
int lastIndexOf = fullname.lastIndexOf(lastN);
String firstN = fullname.substring(0, lastIndexOf);
System.out.println(firstN + " " + lastN);
I have a text file that holds data like this:
Jones,Mary,903452
4342,2.5,A
3311,4,B+
I'm using Scanner to read the file. This is my code:
while(reader.hasNextLine())
{
reader.useDelimiter(",");
String lastN = reader.next();
String firstN = reader.next();
String id = reader.nextLine();
String course1 = reader.next();
double credits = reader.nextDouble();
String grade = reader.nextLine();
}
But when I print the line on the console, the , on the last part of the line doesn't get delimited and it prints like this:
Jones, Mary, ,903452
4342, 2.5, ,A
6.5, ,3.569
My toString method on my class:
public String toString() {
return lastName + ", " + firstName + ", " + idNo + "\n"
+ courseOne + ", " + credits + ", " + grade;
I'm searched around for a solution. I tried reader.useDelimiter("[,]") and reader.useDelimiter(",|,") but still gives me the same output. How can I fix this?
From the Scanner's documentation:
This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
(Emphasis mine) This means that the whole rest of the line is returned, including delimiters. Setting id to reader.next() wouldn't work because it sucks up everything until the next delimiter. A better solution would be to make it accept line breaks as a delimiter, like so:
reader.useDelimiter("[,\n]");
Here are some lines from a file and I'm not sure how to parse it to extract 4 pieces of information.
11::American President, The (1995)::Comedy|Drama|Romance
12::Dracula: Dead and Loving It (1995)::Comedy|Horror
13::Balto (1995)::Animation|Children's
14::Nixon (1995)::Drama
I would like to get the number, title, release date and genre.
Genre has multiple genres so I would like to save each one in a variable as well.
I'm using the .split("::|\\|"); method to parse it but I'm not able to parse out the release date.
Can anyone help me!
The easiest would be matching by regex, something like this
String x = "11::Title (2016)::Category";
Pattern p = Pattern.compile("^([0-9]+)::([a-zA-Z ]+)\\(([0-9]{4})\\)::([a-zA-Z]+)$");
Matcher m = p.matcher(x);
if (m.find()) {
System.out.println("Number: " + m.group(1) + " Title: " + m.group(2) + " Year: " + m.group(3) + " Categories: " + m.group(4));
}
(please don't nail me on the exact syntax, just out of my head)
Then first capture will be the number, the second will be the name, the third is the year and the fourth is the set of categories, which you may then split by '|'.
You may need to adjust the valid characters for title and categories, but you should get the idea.
If you have multiple lines, split them into an ArrayList first and treat each one separately in a loop.
Try this
String[] s = {
"11::American President, The (1995)::Comedy|Drama|Romance",
"12::Dracula: Dead and Loving It (1995)::Comedy|Horror",
"13::Balto (1995)::Animation|Children's",
"14::Nixon (1995)::Drama",
};
for (String e : s) {
String[] infos = e.split("::|\\s*\\(|\\)::");
String number = infos[0];
String title = infos[1];
String releaseDate = infos[2];
String[] genres = infos[3].split("\\|");
System.out.printf("number=%s title=%s releaseDate=%s genres=%s%n",
number, title, releaseDate, Arrays.toString(genres));
}
output
number=11 title=American President, The releaseDate=1995 genres=[Comedy, Drama, Romance]
number=12 title=Dracula: Dead and Loving It releaseDate=1995 genres=[Comedy, Horror]
number=13 title=Balto releaseDate=1995 genres=[Animation, Children's]
number=14 title=Nixon releaseDate=1995 genres=[Drama]
I have string like this: "Welcome Vitalii Mckay "
I need to cut from this string my name and surname, it should left in new string: "Mckay, Vitalii".
But it should be good not just for my name, it should works for other names with different length, for example:
"Welcome John Smith " -> "Smith, John"
or
"Welcome Andrea J. " -> "J., Andrea".
String name = "Welcome Vitalii Mckay";
String[] parts = name.split("\\ ");
name = parts[2] + ", " + parts[1];
Based on #Vishal's answer and OP's comment on #Max's answer, I believe this will work:
String name = " Welcome Vitalii Mckay "; // with spaces in the beginning and in the end
String[] parts = name.trim().split(" "); // you don't really need the \\
name = parts[2] + ", " + parts[1];
Just make sure you trim your String input.
Could you just use a delimiter?
i.e. use a delimiter to separate the three strings, and only print out the two needed values (Surname [2]/Firstname [1])
String s = "Welcome Vitalii Mckay";
String[] split = s.split("\\s+");
System.out.println(split[2] + ", " + split[1]);
// "Welcome"
// followed by the not of space one or more times
// then a space
// followed by anything one or more times
Pattern pattern = Pattern.compile("Welcome ([^ ]+) (.+)");
Matcher matcher = pattern.matcher("Welcome Vitalii Mckay");
if (!matcher.matches()) throw new Exception();
String firstName = matcher.group(1); // groups are captured between ()
String lastName = matcher.group(2); // groups are captured between ()
This question already has answers here:
How to capitalize the first letter of a String in Java?
(59 answers)
Closed 8 years ago.
what I'm trying to do is write a method that has one argument and returns a new string that capitalises that string and returns in its parameter.
this is my code so far:
public void input(){
this.printmessage("Dillon", "Francis", "chimes", "chimes from hudson mohawke", "2", "$69.00", "$420.00", "$1337.00");
}
public void printmessage(String firstName, String lastname, String product, String company, String number, String retail, String price, String saving){
UI.println("text " + firstName + ",");
UI.println(text + " " + product + "s text, text text text text -");
UI.println(" ");
}
What I want to do is capitalise the product parameter (chimes) and then return into into the printMessage capitalized if it is used at the beginning of a sentence.
Will something like this work?
public String capitalise(String product){
return Character.toUpperCase(product.charAt(0)) + product.substring(1);
}
I'm really stuck and would love some help.
Thanks.
I've tried this
String pls = (product + " example");
if ( pls.startsWith(product) ) {
product = capitalise(product);
}
UI.println(pls);
but it doesnt print out the capitalised version.
change this line :
UI.println(text + " " + product + "s text, text text text text -");
to:
UI.println(text + " " + capitalize(product) + "s text, text text text text -");
But your code needs a bit more structuring. Focus on even indentation. And if you need the capitalized product later on, you'd better save it before you use it, like
...
product = capitalize(product);
UI.println(text + " " + product + "s text, text text text text -");
...
EDIT:
For this I'm assuming the line is contained in a String called line.
First check if the line begins with product. Then capitalize it.
...
String line = text + " " + product + "s text, text text text text -";
line = line.trim(); // removes whitespaces.
if ( line.startsWith( product ) ) {
product = capitalize ( product ); //or whatever.
}
UI.println(line);
...