How to use String.format() in Java to replicate tab "\t"? - java

I'm printing data line by line and want it to be organized like a table.
I initially used firstName + ", " + lastName + "\t" + phoneNumber.
But for some of the larger names, the phone number gets pushed out of alignment
I'm trying to use String.format() to achieve this effect. Can anyone tell me the format syntax to use?
I tried String.format("%s, %s, %20s", firstName, lastName, phoneNumber), but that's not what I want. I want it to look like this:
John, Smith 123456789
Bob, Madison 123456789
Charles, Richards 123456789
Edit:
These answers seem to work for System.out.println(). But I need it to work for a JTextArea. I'm using textArea.setText()
Worked it out. JTextArea doesn't use monospaced fonts by default. I used setFont() to change that, and now it works like a charm. Thank you all for the solutions.

consider using a negative number for your length specifier: %-20s. For example:
public static void main(String[] args) {
String[] firstNames = {"Pete", "Jon", "Fred"};
String[] lastNames = {"Klein", "Jones", "Flinstone"};
String phoneNumber = "555-123-4567";
for (int i = 0; i < firstNames.length; i++) {
String foo = String.format("%-20s %s", lastNames[i] + ", " +
firstNames[i], phoneNumber);
System.out.println(foo);
}
}
returns
Klein, Pete 555-123-4567
Jones, Jon 555-123-4567
Flinstone, Fred 555-123-4567

Try putting the width into second placeholder with - sign for right padding as:
String.format("%s, %-20s %s", firstName, lastName, phoneNumber)
This will give the specified width to the second argument(last name) with right padding and phone number will start after the specified width string only.
EDIT: Demo:
String firstName = "John";
String lastName = "Smith";
String phoneNumber = "1234456677";
System.out.println(String.format("%s, %-20s %s",firstName, lastName, phoneNumber));
prints:
John, Smith 1234456677

The only alternative is loop the names list, calculate the maximum length of the String, and add whitespaces as needed after every name to ensure that all the numbers begin at the same column.
Using tabs has the disavantage that you cannot know a priori how many whitespace are equivalent to a tab, since it is dependent of the editor.

Related

Splitting a String with different inputs Java

Input = computer science: harvard university, cambridge (EXAMPLE)
Prompt: Use a String method twice, to find the locations of the colon and the comma.
Use a String method to extract the major and store it into a new String.
Use a String method to extract the university and store it into a new String.
Use a String method to extract the city and store it into a new String.
Display the major, university, and city in reverse, as shown below, followed by a newline.
I was thinking I could just use substring(); but the input entered from the user varies and so the indexes are all different. I am still learning and am stumped on how to do this one. Does substring let you somehow use it without knowing the specific index? Or do I have to use a whole different method? Any help would be awesome. BTW this is HW.
Assuming the input string has format: <major>: <university>, <city>
String has a set of indexOf() methods to find the position of a character/substring (returns -1 if the character/substring is not found) and substring to retrieve a subpart of the input from index or between a pair of indexes.
Also, String::trim may be used to get rid of leading/trailing whitespaces.
String input = "computer science: harvard university, cambridge";
int colonAt = input.indexOf(':');
int commaAt = input.indexOf(',');
// or int commaAt = input.indexOf(',', colonAt + 1); to make sure comma occurs after the colon
String major = null;
String university = null;
String city = null;
if (colonAt > -1 && commaAt > -1) {
major = input.substring(0, colonAt);
university = input.substring(colonAt + 1, commaAt).trim();
city = input.substring(commaAt + 1).trim();
}
System.out.printf("Major: '%s', Univ: '%s', City: '%s'%n", major, university, city);
Output:
Major: 'computer science', Univ: 'harvard university', City: 'cambridge'

Splitting a String and then displaying a portion of that split (last name part)

Hey I'm having an issue with the following problem. I understand how to split the formalName variable (a first " " last name) but now I'm having trouble just displaying the last name so I can generate the formalName ("Mr./Ms. " lastName) can anyone help?
Complete the generateFormalName method so that… you return the formal
name (Mr. or Ms. + last name) given a full name and gender (Strings)
as parameters.
--You can assume a valid name & gender (any case allowed) is passed in. Example 1: ("Bob Smith", "MaLE") passed in should generate "Mr.
Smith" Example 2: ("Maggie May", "feMALE") passed in should generate
"Ms. May"
Tip 1: You are given a String formalName initialized to the empty
String -- you will want to concatenate other Strings onto this to
produce the full formalName.
Tip 2: Write your algorithm in English first.
Tip 3: Think of all of the methods at your disposal and which could be
helpful.
split() function returns you an array of strings. You need to get second element from the array. You can try something like this:
String fullName = "John Smith";
String lastName = fullName.split(" ")[1];
String formalName = "Mr./Ms. " + lastName;

Java Webdriver count first name without last name

I'm writing a selenium webdriver java test and trying to count the number of names that appear without the last name following it.
For example, any time "John Smith" appears, it wouldn't be counted, but if it was a sentence like "John did this", since Smith didn't appear, it would increase the count.
Unfortunately at this point, trying to read/count from a WebElement is returning a 0 no matter what I do, but I know either way I wouldn't be excluding the last name entries. Any suggestions welcome!
Current code:
//get string from WebElement text
`String john = JohnSmith.getText();
int johnCount =0;
while (john.contains("john")){
johnCount++;
//this line starts from the substring after the first john
john = john.substring(john.indexOf("john") + "john".length());
}
My first thought is to do something simple like replace "John Smith" with "" and then count the instances of "John". One simple way to count the instances is to split the string using "John" and count them.
A simple example:
String s = "This is John Smith. John is walking in the park. John likes coffee. His name is John Smith.";
s = s.replaceAll("John Smith", "");
int count = s.split("John").length - 1;
System.out.println(count); // 2
EDIT:
... or better yet, turn it into a function that can be reused easily...
public int countFirstNames(String firstName, String lastName, String searchText)
{
searchText = searchText.replace(firstName + " " + lastName, "");
return searchText.split("John").length - 1;
}
and call it like
String s = "This is John Smith. John is walking in the park. John likes coffee. His name is John Smith.";
System.out.println(countFirstNames("John", "Smith", s)); // 2

Formatting toString method

I have a toString() method from my class that takes the information from the object and puts it into a string to be printed.
This is what it should look like:
Susan 70 <Average C
Alexander 80 >Average B
, but I'm having trouble formatting my toString() method. This is what it looks like this right now which is very unorganized.
public String toString() {
return ("\n" + fullName +
" " + relativeScore +
" " + testScore);
}
I would normally use printf, but since it's a return statement I can't use it. Any help would be much appreciated.
Depending on what you want to achieve, you could simply use String#format, for example:
System.out.println(String.format("%-10s %d %10s %5s", "Susan", 70, "<Average", "C"));
Which outputs
Susan 70 <Average C
For more details have a look at this example and Formatter
String.format method returns a new String object, so you can use it rather than printf, for instance:
public String toString() {
return String.format("%s\t%3d\t%s", fullName, relativeScore, testScore);
}
You could use String.format() and do it just like you would do with printf()
return String.format("whatever comes here");
you're doing it wrong way. Susan is 5 letter word and Alexander is 9 letter word. So if susan is followed by 10 white spaces then alexander should be followed by 10-9+5= 6 white spaces. You should consider the length of fullname in your code.

Splitting String according to multiple String in java

I just beginning to learn java, so please don't mind.
I have string
String test="John Software_Engineer Kartika QA Xing Project_Manager Mark CEO Celina Assistant_Developer";
I want to splitting based of position of Company={"Software_Engineer", "QA","Project_Manager","CEO ","Assistant_Developer"};
EDITED:
if above is difficulties then is it possible??? Based or {AND, OR)
String value="NA_USA >= 15 AND NA_USA=< 30 OR NA_USA!=80"
String value1="EUROPE_SPAIN >= 5 OR EUROPE_SPAIN < = 30 "
How to split and put in hashtable in java. finally how to access it from the end. this is not necessary but my main concern is how to split.
Next EDIT:
I got solution from this, it is the best idea or not????
String to="USA AND JAPAN OR SPAIN AND CHINA";
String [] ind= new String[]{"AND", "OR"};
for (int hj = 0; hj < ind.length; hj++){
to=to.replaceAll(ind[hj].toString(), "*");
}
System.out.println(" (=to=) "+to);
String[] partsparts = to.split("\\*");
for (int hj1 = 0; hj1 < partsparts.length; hj1++){
System.out.println(" (=partsparts=) "+partsparts[hj1].toString());
}
and
List<String> test1=split(to, '*', 1);
System.out.println("-str333->"+test1);
New EDIT:
If I have this type of String how can you splitting:
final String PLAYER = "IF John END IF Football(soccer) END IF Abdul-Jabbar tennis player END IF Karim -1996 * 1974 END IF";
How can i get like this: String [] data=[John , Football(soccer) ,Abdul-Jabbar tennis player, Karim -1996 * 1974 ]
Do you have any idea???
This will split your string for you and store it in a string array(Max size 50).
private static String[]split = new String[50];
public static void main(String[] args) {
String test="John -Software_Engineer Kartika -QA Xing -Project_Manager Mark -CEO Celina -Assistant_Developer";
for (String retval: test.split("-")){
int i = 0;
split[i]=retval;
System.out.println(split[i]);
i++;
}
}
You can make a string with Name:post and space. then it will be easy get desire value.
String test="John:Software_Engineer Kartika:QA Xing:Project_Manager"
I am unable to comment as my reputation is less. Hence i am writing over here.
Your first Question of String splitting could be generalized as positional word splitting. If it is guaranteed that you require all even positioned string, you could first split the string based on the space and pull all the even position string.
On your Second Question on AND & OR split, you could replace all " AND " & " OR " with single String " " and you could split the output string by single space string " ".
On your third Question, replace "IF " & " END" with single space string " " and I am not sure whether last IF do occurs in your string. If so you could replace it too with empty string "" and then split the string based on single space string " ".
First classify your input string based on patterns and please devise an algorithm before you work on Java.
I would suggest you to use StringBuffer or StringBuilder instead of using String directly as the cost is high for String Operation when compared to the above to.
try this
String[] a = test.replaceAll("\\w+ (\\w+)", "$1").split(" ");
here we first replace word pairs with the second word, then split by space
You can take a set which have all positions Like
Set<String> positions = new HashSet<String>();
positions.add("Software_Engineer");
positions.add("QA");
String test="John Software_Engineer Kartika QA Xing Project_Manager Mark CEO Celina Assistant_Developer";
List<String> positionsInString = new ArrayList<String>();
Iterator<String> iterator = positions.iterator();
while (iterator.hasNext()) {
String position = (String) iterator.next();
if(test.contains(position)){
positionsInString.add(position);
break;
}
}

Categories