I have a JList model (listModelGrid) with items with labels like this:
LastName, FirstName Spouse // e.g. This is 1st list item with labels
Children // e.g. This is 2nd list item with labels
Street // e.g. This is 3rd list item with labels
City, State Postal // e.g. This is 4th list item with labels
I want to replace Labels with ResultSet.getString method like this:
String labels = "";
labels += resultSet.getString("LastName")+", "+resultSet.getString("FirstName")+" "+
resultSet.getString("Spouse") + "\n";
labels += resultSet.getString("Children") + "\n";
labels += resultSet.getString("Street") + "\n";
labels += resultSet.getString("City")+", "+resultSet.getString("State")+" "+
resultSet.getString("Postal");
I have tried it but stuck in loops:
private String getPrintingLabels(ResultSet rs) throws SQLException {
String str = "";
for (int i = 0; i < listModelGrid.getSize(); i++) {
String element = String.valueOf(listModelGrid.getElementAt(i));
String[] lbls = element.split(",\\s");
str += rs.getString(lbls[0])+", ";
for(int j = 1; j < lbls.length ; j++) {
// Stuck on her
}
String[] lbls2 = element.split("\\s");
str += rs.getString(lbls2[0])+" ";
for(int j = 1; j < lbls2.length ; j++) {
// Stuck on her
}
}
return str;
}
Thanks in advance!
The code in your method is written in a little complicated way.
I have used regex and simplified the code you wanted to write and here it is.
private String getPrintingLabels(ResultSet rs) throws SQLException {
Pattern p = Pattern.compile("([a-zA-Z]+)(,? )?");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < listModelGrid.getSize(); i++) {
String element = String.valueOf(listModelGrid.getElementAt(i));
Matcher m = p.matcher(element);
while(m.find()) {
sb.append(rs.getString(m.group(1)));
if (m.group(2) != null) {
sb.append(m.group(2));
}
}
sb.append(System.getProperty("line.separator")); // helps correctly insert a new line for any platform linux/windows/any
}
System.out.println(sb.toString());
return sb.toString();
}
I don't know if you are familiar with regex but by using regex your job is done quite easily. Also, using String concatenation is not a good idea specially when you have to do it quite much hence I have used StringBuild for same purpose. Also used line.separator property so no matter in what platform you run the code it will have appropriate line in your string. Just use my method instead of yours and see if the desired string the one you wanted.
Also in my code, you won't have to manually manage inserting ", " or " " as that is done automatically as it is present in the string.
Also make sure you import these two or any needed imports,
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Related
I haven't been able to find any questions similar to my situation so I hope I'm not missing something.
I have an array of strings. I want to print every 3 strings on their own line with commas and spacing.
Here is my method:
public static void Modify(String stringSearch)
{
ArrayList<String> records = new ArrayList<String>();
try {
File file = new File("Temp.txt");
input = new Scanner(file);
}
catch (IOException ioe) {
ioe.printStackTrace();
}
if (input.hasNext()) {
while (input.hasNext())
{
String firstName = input.next();
String lastName = input.next();
String phoneNumber = input.next();
if ((Objects.equals(firstName, stringSearch)) || (Objects.equals(lastName, stringSearch)) || (Objects.equals(phoneNumber, stringSearch))) {
records.add(firstName);
records.add(lastName);
records.add(phoneNumber);
}
} // end while
}
int size;
size = (records.size()) / 3;
System.out.printf("Found %d records:%n", size);
String[] Array = records.toArray(new String[0]);
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);
}
}
I am converting an arrayList to a string array in order to try and format it. I'm very new to java and am working on a project in a time crunch.
I need it to print exactly like this:
Found 2 records:
1) Garcia, John 505-338-2567
2) John, Joseph 212-780-3342
It is printing like this:
Found 2 records:
GarciaJohn505-338-2567JohnJoseph212-780-3342
Java is an Object-Oriented language, and you should use it.
Create a class representing your Person, with firstName, lastName, and phoneNumber as fields.
Then you create a List<Person> with 2 objects in it, and write a method for printing that list. The System.out.printf() you're already using can help output values in columns like you want.
You probably need to create you own data-structure, with a toString() method that suits your needs.
Something like:
public class PersonalCustomerData {
private String firstName;
private String lastName;
private String phoneNumber;
...
#Override
public String toString() {
return lastName + "," + " " + firstName + " " + phoneNumber;
}
}
And, as #Andreas mentioned in his answer, you also need a Collection<PersonalCustomerData>, that when you iterate over it, you print your fully formatted output:
private Collection<PersonalCustomerData> col;
// init the collection + do stuff...
public void printCustomerData() {
int lineNumber = 0;
for(PersonalCustomerData pcd : col) {
lineNumber++;
System.out.println(lineNumber + ")" + " " + pcd);
}
}
If you don't want to use object to contain your values and stick with your plan of doing. you can use this code to print it with format.
Replace this:
String[] Array = records.toArray(new String[0]);
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);
}
to this:
int numberOfLine = 1; // Counter of words per line
String[] Array = records.toArray(new String[0]);
for(String str : Array) {
String strSperator = "";
switch (numberOfLine) {
case 1:
strSperator = ", ";
numberOfLine++;
break;
case 2:
strSperator = " ";
numberOfLine++;
break;
case 3:
strSperator = "\n";
numberOfLine = 1;
break;
}
System.out.printf("%s%s",str,strSperator);
}
replace this line
for (int s = 0; s < Array.length; s++) {
System.out.printf("%s", Array[s]);`
to something like this. I didn't test out the code so there might be small typos or what not. I think this will do what you want.
As Andreas said, it would be better if you make a person class. It will look more organized and probably easier to understand.
int counter = 1;
System.out.print(records.get(0) + ",\t")
while (counter !=records.size())
{
if(counter %3 ==0)
System.out.println(records.get(counter));
else if(counter% 3== 1)
System.out.print(records.get(counter) + ",\t");
else
System.out.print(records.get(counter)+ "\t");
counter ++;
}
Since your first element will always be first name , 2nd element will be last name and 3rd element is the phone number, I print the first one initially then the modding and the while loop should handle everything I believe.
I have 2 strings
String str1 = "FIRST \n SECOND"
String str2 = "FIRST \n SECOND"
Is it possible for it to be displayed like this?
FIRST FIRST
SECOND SECOND
I do not think that you can do that with simple print statements.
What you can try, on the other hand, would be to have a list of string builders, one for each line. You would then split the string by \n and you place each item in the array in the next string builder.
Once that you would have finished, you would then simply need to traverse the list of string builders and print the content.
So basically (untested code, should give you an idea of what needs doing though):
List<StringBuilders> list = new ArrayList<>();
String str = '...';
String[] parsedLine = str.split("\\n");
for(int i = 0; i < parsedLine.length;i++) {
if(list.size() <= i) list.add(new StringBuilder());
list.get(i).append(parsedLine + "\t");
}
for(StringBuilder sb : list) {
System.out.println(sb.toString());
}
You May use first split and rejoin it using white space. it will work sure.
String finalString = "";
String[] finalStringArray = inputString.split("[\\n]+");
for(int i = 0; i<finalStringArray.lengh; i++){
finalString = finalString+" "+finalStringArray[i];
}
How can I have a var which contains all the records I get from a resultset?
So far I have this code:
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
String resultado = "";
resultado = rs.getString(i);
columnValue += resultado;
}
jTextPane2.setText(jTextPane2.getText() + columnValue + ", ");
}
I want that when resultado gets the value from the rs.getString(i), fills the var columnValue so that I have a var which SHOULD have all the records I get from the rs, but is not working. Any help?
The result I get is:
(id_tlf, cod_area)
1+58, 1+582+104, 1+582+1043+60
so as you see, the first 2 results repeat in every row
Please prefer a StringBuilder to creating lots of String temporary values (they pollute the intern cache for one thing). Next, you don't need to store each column in another local variable. Basically, I would do something like
StringBuilder sb = new StringBuilder();
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
if (i != 1) {
sb.append(", ");
}
sb.append(rs.getString(i));
}
sb.append(System.lineSeparator());
}
jTextPane2.setText(sb.toString());
Note the above clears jTextPane2, if you intend to append then you could change the first line to to something like
StringBuilder sb = new StringBuilder(jTextPane2.getText());
sb.append(System.lineSeparator()); // <-- start the next line... and then iterate rs
Not sure if I understand right, but it could be something like this:
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
String resultado = "";
resultado = rs.getString(i);
columnValue+=resultado;
}
columnValue+=", ";
}
jTextPane2.setText(columnValue);
your problem is your columnValue and your jTextPane.
When you want to add the text to your jTextPane, you are adding the text you already have inside the textpane AND you add add the columnValue text (which is already within the textpane).
Within your for loop, you write the following to get the result:
columnValue+=resultado;
Here you should write
columnValue=resultado;
This should fix your problem.
I hope that I could help you.
Best regards. Levkaz
You are accumulation the column value each inner iteration (without reinitializing to the empty string each outer iteration):
columnValue+=resultado;
And you are accumulation the total message each outer iteration:
jTextPane2.setText(jTextPane2.getText() + columnValue + ", ");
Pick one :-)
I'd recommend using (Java 8) StringJoiner, and only updating jTextPane2 at the end of the loop:
StringJoiner sj = new StringJoiner(", ");
while (rs.next()) {
StringBuilder columnValue = new StringBuilder();
for (int i = 1; i <= columnCount; i++) {
columnValue.append(rs.getString(i));
}
sj.add(columnValue.toString());
}
jTextPane2.setText(sj.toString());
I am trying to insert an element into table from a 2D array.
I have a problem in removing the last comma to write the sql statement in a proper way
This is the code
String m="";
String matInsert = null;
for (int k=0;k<di.mat.length;k++) { //row
for (int j=0;j<di.mat[k].length;j++) {
m+=di.mat[k][j]+", ";
matInsert=new String("INSERT INTO "+ tableName +"("+ff+")"+"values" +"("+m+")");
}
m = m.replaceAll(", $","");
//m=m.substring(0,m.lastIndexOf(","));
System.out.println(matInsert);
stmt1.executeUpdate(matInsert);
}
I tried very much but i did not succeed to remove it
please help.
I commonly use the following structure for this type of thing
String sep = "";
for(...) {
m += (sep+di.mat[k][j]);
sep = ",";
}
It isn't the nicest but it works.
Now, part of the problem in your code is that you are creating matInsert inside the loop then updating m after the loop and not rebuilding it.
Updated code:
String matInsert = null;
for (int k=0;k<di.mat.length;k++) { //row
String m="";
String sep = "";
for (int j=0;j<di.mat[k].length;j++) {
m+= (sep+di.mat[k][j]);
sep = " ,";
}
matInsert="INSERT INTO "+ tableName +"("+ff+")"+"values" +"("+m+")";
System.out.println(matInsert);
stmt1.executeUpdate(matInsert);
}
You can avoid last comma addition with simple logic. It is good idea to omit unnecessary thing on spot, rather than to replace that with another operation.
for (int k=0;k<di.mat.length;k++) { //row
for (int j=0;j<di.mat[k].length;j++) {
m+=di.mat[k][j];
if(j<di.mat[k].length -1){ //This condition will escape you from last comma addition
m+= ", ";
}
}
}
Another point, use StringBuilder#append instead of String + concat to increase the efficiency.
Since m is a String, you can use m.substring(0,m.length()-1) or add and if statement inside the inner loop checking if it is the last index of k and j then don't add a comma at the end.
If you want to remove the last instance of a character in a string, as in delete it, use this:
public class Something
{
public static void main(String[] args)
{
String s = "test";
StringBuilder sb = new StringBuilder(s);
char delval = 'c';
int lastIndex = -1;
for(int i = 0; i < s.length()-1; i++)
{
if(s.charAt(i) == delval)
{
lastIndex = i;
}
}
try{
sb.deleteCharAt(lastIndex);
System.out.println(s);
}
catch(Exception e){
System.out.println("Value not present");
}
}
}
I have string like "align is going to school sad may me". I want to get the sub string after the four spaces. The String will be entered at run time. can anyone suggest me to find the Sub String after some set of spaces......
String st = "align is going to school sad may me";
int i = 0;
String [] strings = new String [15];
StringTokenizer stringTokenizer = new StringTokenizer (st, " ");
while (stringTokenizer.hasMoreElements ())
{
strings [i]= (String)stringTokenizer.nextElement ();
i++;
}
System.out.println ("I value is" + i);
for (int j=4; j<i; j++)
{
System.out.print (strings[j] + " ");
}
I've tried this one and it's working can you please suggest me simple method to find the Sub string after some set of spaces.
st = st.replaceAll("^(\\S*\\s){4}", "");
^ indicates that we remove only from the first character of the string.
\s is any white space. It would also remove, for example, tabulations.
\S is any non white space character.
* means any number of occurrences of the character.
So, \S* is any number of non white space characters before the white space.
{4} is obviously because you want to remove 4 white spaces.
You could also use:
st = st.replaceFirst("(\\S*\\s){4}", "");
which is the same but you don't need the ^.
In case the input string could have less than 4 white spaces:
st = st.replaceAll("^(\\S*\\s){1,4}", "");
would return you the last word of the string, only if the string doesn't end on a white space. You can be sure of that if you call trim first:
st = st.trim().replaceAll("^(\\S*\\s){1,4}", "");
What about using split?
st.split (" ", 5) [4]
It splits string by spaces, into not more than 5 chunks. Last chunk (with index 4) will contain everything after fourth space.
If it is not guaranteed that string contains 4 spaces, additional check is required:
String [] chunks = st.split (" ", 5);
String tail = chunks.length == 5 ? chunks [4] : null;
Tail will contain everything after fourth space or null, is there are less than four spaces in original string.
public static void main(String[] args) {
String st = " align is going to school sad may me ";
String trim = st.trim(); // if given string have space before and after string.
String[] splitted = trim.split("\\s+");// split the string into words.
String substring = "";
if (splitted.length >= 4) { // checks the condition
for (int i = 4; i < splitted.length; i++)
substring = substring + splitted[i] + " ";
}
System.out.println(substring);
}
This may be a overkill but it uses simple string operations (just str.indexOf(' ')).
If you needed for a school project or someting:
String str ="ada adasd dasdsa d adasdad dasasd";
int targetMatch = 4;
int offset = 0;
for(int i = 0 ; i < targetMatch; i++){
int position = str.indexOf(' ', offset);
if(position != -1){
System.out.println("position: "+ position);
offset = position+1;
}
}
String result = str.substring(offset);
System.out.println(result);
For real project... advanced regex would be better.
Here's a trivial and simple implementation that solves your problem:
String s = "I've tried this one and it's working can you please suggest";
int index = -1;
for (int i = 0; i < 4; i++) {
index = s.indexOf(' ', index + 1);
}
System.out.println(s.substring(index + 1));
It will fail if the string starts with a space or if it contains sequences of spaces. But it's a start.
Output: and it's working can you please suggest
public class MySplit {
public static void main(String agsp[]) {
String oldString = "roma h totti milan kaka juve love";
String[] allStrings = oldString.split("\\s");
String newString = "";
for (int i = 3; i < allStrings.length; i++)
newString = newString + " " + allStrings[i];
System.out.println(newString);
}
}
you can also make function like this
public String newSplit(String data, int index){
String[] allStrings = data.split("\\s");
String newString = "";
for (int i = index; i < allStrings.length; i++)
newString = newString + " " + allStrings[i];
return newString
}
The simple way using this piece of code
String thisString="Hello world go to kashmir";
String[] parts = theString.split(" ");
String first = parts[0];//"hello"
String second = parts[1];//"World"
String first = parts[3];//"hello"
String second = parts[4];//"World"