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";
Related
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]);
I am trying to have a string that when i print it, has multiple lines and different left indents.
String test = "Zone 0:" +
"Gear{" + "gearType=" + gearType + ", weight=" + weight}" +
"Zone 1:" +
"Gear{" + "gearType=" + gearType + ", weight=" +weight}";
System.out.println(test);
Expected Output: (without the dashes but with a left indent)
Zone 0:
------Gear{gearType=RAIN_JACKET, weight=HIGH}
Zone 1:
------Gear{gearType=SHELTER, weight=HIGH}
You can make use of "\n" new line character and "\t" for tab. Like:
final String test = "Zone 0:\n" + "\tGear{" + "gearType=" + gearType + ", weight=" + weight +"}\n" + "Zone 1:\n"
+ "\tGear{" + "gearType=" + gearType + ", weight=" + weight + "}\n";
As well as after weight there should be + sign and a double quote ". (as in above String)
you can use the "\n" for new line and "\t" for tabulation space :
String test = "Zone 0:\n" + "\tGear{" + "gearType=" +
gearType + ", weight=" + "weight}\n" +
"Zone 1:\n" + "\tGear{" + "gearType=" +
gearType + ", weight=" + "weight}";
output :
Zone 0:
Gear{gearType=test, weight=weight}
Zone 1:
Gear{gearType=test, weight=weight}
You may also refer to the official Formatter documentation. There you'll get all the other options and details for formatting a String in Java.
Presumably you'd want the lines to use the appropriate line terminator for your platform, i.e. \r\n for Windows and \n for Linux.
There are two ways to do that:
Use System.lineSeparator():
String test = "Zone 0:" + System.lineSeparator() +
" Gear{gearType=" + gearType + ", weight=" + weight + "}" + System.lineSeparator() +
"Zone 1:" + System.lineSeparator() +
" Gear{gearType=" + gearType + ", weight=" + weight + "}" + System.lineSeparator();
Use String.format(String format, Object... args) and the %n format specifier:
String test = String.format("Zone 0:%n" +
" Gear{gearType=%s, weight=%s}%n" +
"Zone 1:%n" +
" Gear{gearType=%s, weight=%s}%n",
gearType, weight, gearType, weight);
I'd recommend the second approach, since it's more readable.
May be an idea to rather use a StringBuilder (though from what I understand the Java compiler uses StringBuilder under the hood for String concatenation), so it really becomes more of a readability issue.
StringBuilder output = new StringBuilder()
.append(System.lineSeparator()).append("Zone 0:")
.append(System.lineSeparator()).append("\tGear{gearType=").append(gearType).append(", weight=").append(weight).append("}")
.append(System.lineSeparator()).append("Zone 1:")
.append(System.lineSeparator()).append("\tGear{gearType=").append(gearType).append(", weight=").append(weight).append("}");
System.out.print(output.toString());
For newlines it's good practice to use System.lineSeparator()
I have a segment of code that splits a string into tokens and prints them each out on a new line. I am having a hard time writing a code that determines if a word is a reserved word or not. I have to print "Reserved word is: " if the word is a java keyword, otherwise print "Current word is: ". Here is my code so far:
package projectweek3;
/**
*
* Name -
* Email Address -
* Date -
*
*/
public class Week3Project {
final static String program = "/*\n" +
" * To change this license header, choose License Headers in Project Properties.\n" +
" * To change this template file, choose Tools | Templates\n" +
" * and open the template in the editor.\n" +
" */\n" +
"package testapplication2;\n" +
"\n" +
"import java.util.Scanner;\n" +
"\n" +
"/**\n" +
" *\n" +
" * #author james\n" +
" */\n" +
"public class TestApplication2 {\n" +
"\n" +
" /**\n" +
" * #param args the command line arguments\n" +
" */\n" +
" public static void main(String[] args) {\n" +
" Scanner input = new Scanner(System.in);\n" +
" \n" +
" System.out.println(\"Enter integer #1\");\n" +
" int num1 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #2\");\n" +
" int num2 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #3\");\n" +
" int num3 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #4\");\n" +
" int num4 = input.nextInt();\n" +
" \n" +
" System.out.println(\"Enter integer #5\");\n" +
" int num5 = input.nextInt();\n" +
" \n" +
" //determine the sum\n" +
" int sum = num1 + num2 + num3 + num4 + num5;\n" +
" \n" +
" //this is helpful to make sure your sum is correct\n" +
" System.out.println(\"The sum is: \" + sum);\n" +
" \n" +
" //why doesn't this generate the sum correctly\n" +
" double average = sum / 5;\n" +
" \n" +
" //The average, lets hope its right...\n" +
" System.out.println(\"The average of your numbers is: \" + average);\n" +
" \n" +
" }\n" +
" \n" +
"}\n" +
"";
**public static void main(String[] args)
{
String str = program;
String s = "";
for (int i = 0; i < str.length(); i++) {
s += str.charAt(i) + "";
if (str.charAt(i) == ' ' || str.charAt(i) == '\t' || str.charAt(i) == '\n' || (str.charAt(i) == ' ' && str.charAt(i) == '\n')) {
String currentWord = s.toString();
String res = "int";
if (currentWord.equals(res)) {
System.out.println("Reserved word is: [" + currentWord + "]");
}
else {
System.out.println("Current word is: [" + currentWord + "]");
}
s = "";//Clear the string to get it ready to build next token.
}
}**
I would reconsider the way you're looping through the "program."
Instead of going through character by character, use the Java String.split() function.
String program = "int num1 = input.nextInt();\n";
String[] words = program.split("[\\n\\s\\t]");
for (String word : words) {
System.out.println(word);
}
Output:
int
num1
=
input.nextInt();
EDIT:
Since you can't use String.split(), your looping solution looks good. To check if the current word is reserved, try using Set.contains().
Set<String> reserved = new HashSet<>();
reserved.add("int");
// ...
if reserved.contains(word) {
System.out.println("Reserved word is: " + word);
} else {
System.out.println("Current word is: " + word);
}
That is, assuming you're allowed to use Set.
I am trying to output arrays on a new line through a basic client, server application. However, to accomplish this I have had to use substring to find the # after each word to signal the end of the line. However I want to remove this function and have each section on a new line.
public ClientHandler(Socket socket,Users newUser, int newClientUser)
throws IOException
{
client = socket;
input = new Scanner(client.getInputStream());
output = new PrintWriter(
client.getOutputStream(),true);
user = newUser;
clientUser = newClientUser;
String[] itemName = {user.getItemName(1), user.getItemName(2)};
String[] description = {user.getItemDescription(1), user.getItemDescription(2)};
String[] itemtime = {user.getItemTime(1), user.getItemTime(2)};
output.println(itemName[0] + "#" + itemName[1]
+ "#" + "Welcome To The Auction User:" + clientUser
+ itemName[0] +": "+ description[0] +
"#"+ itemName[1] +": "+description[1]+
"#"+ "Deadline For " + itemName[0] + ": "
+ itemtime[0] + "#" +"Deadline For " +
itemName[1] + ": " + itemtime[1]+"#");
}
private synchronized void getMessage(String response)
{
String message="";
for(int i= count; !response.substring(i, i+1).equals("#"); i++)
{
count = i;
}
}
output.println(itemName[0] + "\n" + itemName[1]
+ "\n" + "Welcome To The Auction User:" + clientUser
+ itemName[0] +": "+ description[0] +
"\n"+ itemName[1] +": "+description[1]+
"\n"+ "Deadline For " + itemName[0] + ": "
+ itemtime[0] + "\n" +"Deadline For " +
itemName[1] + ": " + itemtime[1]+"\n");
Instead of having a "#" signify a new line, you can use "\n". Java will read that from your string as a new line.
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." );