Can someone look at my code and tell me whats wrong? - java

So my requirement is to display a message showing yours and your friend's initials in lower case (ie. "mf and js are friends").
Here's my code
String myFullName = "Daniel Camarena";
String friendsFullName = "John Smith";
System.out.println( myFullName.toLowerCase().charAt(0)
+ myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );
The output I get is
199 and js are friends.

myFullName.toLowerCase().charAt(0) + myFullName.toLowerCase().charAt(7)
are working on ascii integer value and hence 199
The reason strings addition works for the second name is because that is part of the string formed due to this:
+ " and "
Quick fix, add an empty string at start
System.out.println("" + myFullName.toLowerCase().charAt(0)
+ myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );

System.out.println( "" + myFullName.toLowerCase().charAt(0) + myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );
Append the blank string to convert it to String and then it will start doing concanetation . As '+' is overloaded operator it is doing addition till it encounters String.

You can use following code :
String myFullName = "Daniel Camarena";
String friendsFullName = "John Smith";
String[] arrMyFullName = myFullName.toLowerCase().split(" ");
String[] arrFriendsFullName = friendsFullName.toLowerCase().split(" ");
String message = "";
for(String s : arrMyFullName)
message += s.charAt(0);
message += " and ";
for(String s : arrFriendsFullName)
message += s.charAt(0);
message += " are friends.";
System.out.println( message );
Above code also work if name is more than 2 words.

Try:
System.out.println( "" + myFullName.toLowerCase().charAt(0)
+ myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );

With this one you can have any name of friends. Instead of correcting the index which differs for each name.
String myFullName = "Daniel Camarena";
String friendsFullName = "John Smith";
String[] myNameSplit = myFullName.split(" ");
String myFirstInitial = String.valueOf(myNameSplit[0].charAt(0));
String myLastInitial = String.valueOf(myNameSplit[1].charAt(0));
String[] myFriendNameSplit = friendsFullName.split(" ");
String myFriendFirstInitial = String.valueOf(myFriendNameSplit[0].charAt(0));
String myFriendLastInitial = String.valueOf(myFriendNameSplit[1].charAt(0));
System.out.println(myFirstInitial+myLastInitial + " and " + myFriendFirstInitial+myFriendLastInitial+ " are friends");

It is adding ASCII value of d and c in output to avoid that do as following.
String myFullName = "Daniel Camarena";
String friendsFullName = "John Smith";
System.out.println( myFullName.toLowerCase().charAt(0)
+""+ myFullName.toLowerCase().charAt(7)
+ " and "
+ friendsFullName.toLowerCase().charAt(0)
+ friendsFullName.toLowerCase().charAt(5)
+ " are friends." );

Related

Regex: Only returns message string - That's starts with messages and string between parent message curly brace

I want to get all the message data only. Such that it should look for message and all the data between curly braces of the parent message. With the below code, I am getting service details too along with message which I don't want. Any suggestion on this experts thanks in advance.
String data = "/**\r\n" +
" * file\r\n" +
" */\r\n" +
"syntax = \"proto3\";\r\n" +
"package demo;\r\n" +
"\r\n" +
"import \"envoyproxy/protoc-gen-validate/validate/validate.proto\";\r\n" +
"import \"google/api/annotations.proto\";\r\n" +
"import \"google/protobuf/wrappers.proto\";\r\n" +
"import \"protoc-gen-swagger/options/annotations.proto\";\r\n" +
"\r\n" +
"option go_package = \"bitbucket.com;\r\n" +
"option java_multiple_files = true;\r\n" +
"\r\n" +
"schemes: HTTPS;\r\n" +
"consumes: \"application/json\";\r\n" +
"produces: \"application/json\";\r\n" +
"responses: {\r\n" +
"key:\r\n" +
" \"404\";\r\n" +
"value: {\r\n" +
"description:\r\n" +
" \"not exist.\";\r\n" +
"schema: {\r\n" +
"json_schema: {\r\n" +
"type:\r\n" +
" STRING;\r\n" +
"}\r\n" +
"}\r\n" +
"}\r\n" +
"}\r\n" +
"responses: {\r\n" +
"key:\r\n" +
" \"401\";\r\n" +
"value: {\r\n" +
"description:\r\n" +
" \"Wrong user.\";\r\n" +
"schema: {\r\n" +
"json_schema: {\r\n" +
"type:\r\n" +
" STRING;\r\n" +
"};\r\n" +
"example: {\r\n" +
"value:\r\n" +
" '{ \"message\": \"wrong user.\" }'\r\n" +
"}\r\n" +
"}\r\n" +
"}\r\n" +
"}\r\n" +
"\r\n" +
"message message1 {\r\n" +
" message message2 {\r\n" +
" enum Enum {\r\n" +
" UNKNOWN = 0; \r\n" +
" }\r\n" +
" }\r\n" +
" string id = 1;\r\n" +
" string name = 3;\r\n" +
" string account = 4;\r\n" +
"}\r\n" +
"\r\n" +
"message User{\r\n" +
" string firstName = 1 ;\r\n" +
" string lastName = 2 ;\r\n" +
" string middleName = 3 [(validate.rules).repeated = { min_items: 0 }];\r\n" +
"}\r\n" +
"\r\n" +
"service Userlogin{\r\n" +
" rpc Login(User) returns (APIResponse);\r\n" +
"}";
List<String> allmsg = Arrays.asList(data.replaceAll("(?sm)\\A.*?(?=message)", "").split("\\R+(?=message)"));
I am expecting response like below in my array list of string with size 2.
allMsg.get(0) should be
message message1 {
message message2 {
enum Enum {
UNKNOWN = 0;
}
}
string id = 1;
string name = 3;
string account = 4;
}
allMsg.get(1) should be
message User{
string firstName = 1 ;
string lastName = 2 ;
string middleName = 3 [(validate.rules).repeated = { min_items: 0 }];
}
Use a Pattern that matches a "message" and stream the match results to a List:
List<String> allmsg = Pattern.compile("(?ms)^message.*?^}")
.matcher(data)
.results() // stream the MatchResults
.map(MatchResult::group) // get the entire match
.collect(toList()); // collect as a List
See live code demo.
Regex breakdown:
(?ms) turns on flags s, which makes dot also match newlines, and m, which makes ^ and $ match start and end of each line
^message matches start of a line (not start of input, thanks to the m flag) then "message"
.*? reluctantly (ie as little as possible) matches any characters (including newlines, thanks to the s flag). Adding the ? to make the quantifier reluctant stops the match from consuming multiple "messages".
^} matches start of a line (not start of input, thanks to the m flag) then "}"
See live regex demo.
This will work even if "messages" are not contiguous with each other, ie they may be interspersed with other constructs (your example doesn't have this situation, but the linked demos do).
You should see you other question.
Pattern.compile("(?s)^message(.(?!message|service))*");
If message can appear after message
"message message1 {\r\n" +
You must adapt the regex.

To split fullname into Salutation,Firstname and lastname in java

I am receiving full name, i need to split this into Salutation, Firstname and lastname.
for eg.
Steve Emond==> Steve as Firstname , Emond as lastname(here Salutation is Empty)
Mr Chris Barker ==> Mr as Salutation, Chris as Firstname , Barker as lastname
Justin ==> Justin as lastname(Salutation and Firstname are empty)
Note: received Miss,Mr,Mrs as Salutation values.
Code:
String FirstName="";
String fullName="Barker";
String[] nameArray=fullName.split(" ");
if(nameArray.length<3)
{
System.out.println("Salutation: " + nameArray[0]);
System.out.println("LastName: " + nameArray[1]);
System.out.println("FirstName: " + FirstName);
}else if(nameArray.length>=3){
System.out.println("Salutation: " + nameArray[0]);
System.out.println("LastName: " + nameArray[nameArray.length - 1]);
for (int index = 1; index < nameArray.length - 1; index++) {
FirstName = FirstName + " " + nameArray[index];
}
System.out.println("FirstName: " + FirstName.trim());
}
The above code works fine when all values given in input( ie Mr Chris Barker ), for the remaining case it failed. can anyone provide me the solution for this?
Method 1:
String fullName="Steve Emond";
String[] nameArray=fullName.split(" ");
if(nameArray.length==1)
{
System.out.println("LastName: " + nameArray[0]);
}else if(nameArray.length==2){
System.out.println("FirstName: " + nameArray[0]);
System.out.println("LastName: " + nameArray[1]);
}
else if(nameArray.length==3){
System.out.println("Salutation: " + nameArray[0]);
System.out.println("FirstName: " + nameArray[1]);
System.out.println("LastName: " + nameArray[2]);
}
Using Regex Method 2:
String fullName="Mr Justin raj Savarimuthu";
Pattern pattern = Pattern.compile(new String ("(Mr\\s|Miss\\s|Mrs\\s)"));
if(fullName.matches("(Mr\\s|Miss\\s|Mrs\\s).*"))
{
System.out.println("Salutation:"+fullName.substring(0,fullName.indexOf(' ')));
fullName=pattern.split(fullName)[1].trim();
}
String[] parts = fullName.split(" ");
String firstName="";
for(int i=0;i<parts.length-1;i++)
{
firstName=firstName+parts[i]+" ";
}
if(firstName!="")
System.out.println("FirstName:"+firstName);
System.out.println("LastName:"+parts[parts.length-1]);

Formatting a return string

I am trying to format this return string to display ratings at one decimal place.
return String.format(title + "," + genre + "," + releaseYear + "(" + (getRating() == -1 ? "No ratings" : getRating()) + "): " + numOfDeaths + " deaths");
I keep getting an error saying too few parameters passed.
You want java.text.DecimalFormat.
DecimalFormat df = new DecimalFormat("0.0##");
String result = df.format(getRating());
return String.format(title + "," + genre + "," + releaseYear + "(" + (getRating() == -1 ? "No ratings" : result) + "): " + numOfDeaths + " deaths");

How to split a NAME and ADDRESS, and print them separately

I'm starting with this String:
"NAME-RAHUL KUMAR CHOUDHARY ADDRESS-RAJDHANWAR DISTRICT-GIRIDIH STATE-JHARKHAND PIN CODE-825412"
I want to split the name and address, and print it like this:
NAME:RAHUL KUMAR CHOUDHARY , DDRESS-RAJDHANWAR DISTRICT-GIRIDIH STATE-JHARKHAND PIN CODE-825412. like this
This is what I have so far:
String str_colArow3 = colArow3.getContents();
//Display the cell contents
System.out.println("Contents of cell Col A Row 3: \""+str_colArow3 + "\"");
if(str_colArow3.contains("NAME"))
{
}
else if(str_colArow3.contains("ADDRESS"))
{
}
String string = "NAME-RAHUL KUMAR CHOUDHARY ADDRESS-RAJDHANWAR DISTRICT-GIRIDIH STATE-JHARKHAND PIN CODE-825412";
String[] parts = string.split("-");
string = "Name: " + parts[1].substring(0, parts[1].length() - 7)
+ "\nAdress: " + parts[2] + " - " + parts[3]
+ "\nPin Code: " + parts[5];
Something like this. Check out the split() method for strings, your string is a bit poorly formatted to use this, though. You have to adjust for your own needs.
Edit: Better way to do this, with different string input.
String string = "RAHUL KUMAR CHOUDHARY:RAJDHANWAR:GIRIDIH:JHARKHAND:825412";
String[] parts = string.split(":");
string = "Name: " + parts[0] + "\n"
+ "Address: " + parts[1] + "\n"
+ "District: " + parts[2] + "\n"
+ "State: " + parts[3] + "\n"
+ "Pin Code: " + parts[4] + "\n";

Break up the text on the page

I have a string
String str = "line1"+"\n" +
"line2"+"\n" +
"line3"+"\n" +
"line4"+"\n" +
"line5"+"\n" +
"line6"+"\n" +
"line7"+"\n" +
"line8"+"\n" +
"line9"+"\n" +
"line10"+"\n" +
"line11"+"\n" +
"line12"+"\n" +
"line13"+"\n" +
"line14"+"\n" +
"line15"+"\n" +
"line16"+"\n" +
"line17"+"\n";
I want to get out of it an array of strings
String str1 = "line1"+"\n" +
"line2"+"\n" +
"line3"+"\n" +
"line4"+"\n";
String str2 = "line5"+"\n" +
"line6"+"\n" +
"line7"+"\n" +
"line8"+"\n";
String str3 = "line9"+"\n" +
"line10"+"\n" +
"line11"+"\n" +
"line12"+"\n";
String str4 = "line13"+"\n" +
"line14"+"\n" +
"line15"+"\n" +
"line16"+"\n";
String str5 = "line17"+"\n";
if I do so
String[] str1 = str.split("\n");
I get an array of strings, in which only one line, and I need it for a few
instead of the string I will have the file from which I plan to read the text in a row
for splitting string with particular format you need to specify regular expression
so in your case regular expression will be ("\r\n")
Look Here

Categories

Resources