Remove last comma java - java

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");
}
}
}

Related

How do I exclude capitalizing specific words in a String?

I'm new to programming, and here I'm required to capitalise the user's input, which excludes certain words.
For example, if the input is
THIS IS A TEST I get This Is A Test
However, I want to get This is a Test format
String s = in.nextLine();
StringBuilder sb = new StringBuilder(s.length());
String wordSplit[] = s.trim().toLowerCase().split("\\s");
String[] t = {"is","but","a"};
for(int i=0;i<wordSplit.length;i++){
if(wordSplit[i].equals(t))
sb.append(wordSplit[i]).append(" ");
else
sb.append(Character.toUpperCase(wordSplit[i].charAt(0))).append(wordSplit[i].substring(1)).append(" ");
}
System.out.println(sb);
}
This is the closest I have gotten so far but I seem to be unable to exclude capitalising the specific words.
The problem is that you are comparing each word to the entire array. Java does not disallow this, but it does not really make a lot of sense. Instead, you could loop each word in the array and compare those, but that's a bit lengthy in code, and also not very fast if the array of words gets bigger.
Instead, I'd suggest creating a Set from the array and checking whether it contains the word:
String[] t = {"is","but","a"};
Set<String> t_set = new HashSet<>(Arrays.asList(t));
...
if (t_set.contains(wordSplit[i]) {
...
Your problem (as pointed out by #sleepToken) is that
if(wordSplit[i].equals(t))
is checking to see if the current word is equal to the array containing your keywords.
Instead what you want to do is to check whether the array contains a given input word, like so:
if (Arrays.asList(t).contains(wordSplit[i].toLowerCase()))
Note that there is no "case sensitive" contains() method, so it's important to convert the word in question into lower case before searching for it.
You're already doing the iteration once. Just do it again; iterate through every String in t for each String in wordSplit:
for (int i = 0; i < wordSplit.length; i++){
boolean found = false;
for (int j = 0; j < t.length; j++) {
if(wordSplit[i].equals(t[j])) {
found = true;
}
}
if (found) { /* do your stuff */ }
else { }
}
First of all right method which is checking if the word contains in array.
contains(word) {
for (int i = 0;i < arr.length;i++) {
if ( word.equals(arr[i])) {
return true;
}
}
return false;
}
And then change your condition wordSplit[i].equals(t) to contains(wordSplit[i]
You are not comparing with each word to ignore in your code in this line if(wordSplit[i].equals(t))
You can do something like this as below:
public class Sample {
public static void main(String[] args) {
String s = "THIS IS A TEST";
String[] ignore = {"is","but","a"};
List<String> toIgnoreList = Arrays.asList(ignore);
StringBuilder result = new StringBuilder();
for (String s1 : s.split(" ")) {
if(!toIgnoreList.contains(s1.toLowerCase())) {
result.append(s1.substring(0,1).toUpperCase())
.append(s1.substring(1).toLowerCase())
.append(" ");
} else {
result.append(s1.toLowerCase())
.append(" ");
}
}
System.out.println("Result: " + result);
}
}
Output is:
Result: This is a Test
To check the words to exclude java.util.ArrayList.contains() method would be a better choice.
The below expression checks if the exclude list contains the word and if not capitalises the first letter:
tlist.contains(x) ? x : (x = x.substring(0,1).toUpperCase() + x.substring(1)))
The expression is also corresponds to:
if(tlist.contains(x)) { // ?
x = x; // do nothing
} else { // :
x = x.substring(0,1).toUpperCase() + x.substring(1);
}
or:
if(!tlist.contains(x)) {
x = x.substring(0,1).toUpperCase() + x.substring(1);
}
If you're allowed to use java 8:
String s = in.nextLine();
String wordSplit[] = s.trim().toLowerCase().split("\\s");
List<String> tlist = Arrays.asList("is","but","a");
String result = Stream.of(wordSplit).map(x ->
tlist.contains(x) ? x : (x = x.substring(0,1).toUpperCase() + x.substring(1)))
.collect(Collectors.joining(" "));
System.out.println(result);
Output:
This is a Test

Is there an easy way to eliminate the final comma in my output? Number Seperator

For another assignment i needed to program a "number seperator", that splits any given int value into all of its digits and returns it to the main class as a String.
I have the program up and running but there's a small problem with my output.
public class NumberSeperator {
static String splitNumber(int zahl) {
String s = Integer.toString(zahl);
return s;
}
public static void main(String args[]) {
System.out.println("Input a Number: ");
int zahl = readInt();
String ziffern = splitNumber(zahl);
for (int i = 0; i < ziffern.length(); i++) {
System.out.print(ziffern.charAt(i) + ",");
}
}
}
The output of 1234 should be: 1,2,3,4
and the actual output is: 1,2,3,4,
At the risk of sounding extremely stupid, is there an easy fix to this?
How about printing first element without comma and rest in form ,nextElement like
one, two, three
^^^---------------- - before loop
^^^^^----------- - loop iteration
^^^^^^^---- - loop iteration
It can be achieved like:
if(ziffern.length()>0){
System.out.print(ziffern.charAt(0));
}
for(int i=1; i<ziffern.length(); i++){
System.out.print(", "+ziffern.charAt(i));
}
OR you can convert ziffern to String[] array first and use built-in solution which is: String.join(delimiter, data)
System.our.print(String.join(",", ziffern.split("")));
When it's the last iteration, just don't add it.
In the last iteration, it will make the comma empty so that you won't see it after the last value.
String comma=",";
for (int i = 0; i < ziffern.length(); i++) {
if (i == ziffern.length()-1) {
comma="";
}
System.out.print(ziffern.charAt(i) + comma);
}
with Java 8 and streams you can do it in a single command:
String join = Arrays.asList(ziffern.split(""))
.stream()
.collect(Collectors.joining(","));
System.out.println(join);
or with just plain java 8:
String join = String.join(",", ziffern.split(""));
System.out.println(join);
A simple one liner will do your job:
static String splitNumber(int zahl) {
return String.join(",", String.valueOf(zahl).split(""));
}
Quite often this occurs when you know you have at least two items to print. So here is how you could do it then.
String ziffern = splitNumber(zahl);
String output = ziffern[0];
for (int i = 1; i < ziffern.length(); i++) {
output = "," + ziffern[i];
}
System.out.println(output);
You can just output the string without the last character.
Your modified code should be:
public class NumberSeperator {
static String splitNumber(int zahl) {
String s = Integer.toString(zahl);
return s;
}
public static void main(String args[]) {
int zahl = 1234;
String s="";
String ziffern = splitNumber(zahl);
for (int i = 0; i < ziffern.length(); i++) {
s+=ziffern.charAt(i) + ",";
}
System.out.println(s.substring(0,s.length()-1));
}

replace split string in JLIST element using ResultSet SQLITE

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;

I want to print a formatted array in java

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.

Java: how do icheck if a certain character is within a string, then print out the position it is in relative to the string?

What I am trying to do, is create a method, that has a string and a character as parameters, the method then takes the string and searches for the given character. If the string contains that character, it returns an array of integers of where the character showed up. Here is what I have so far:
public class Sheet {
public static void main(String[] args) {
String string = "bbnnbb";
String complete = null;
//*******
for(int i = 0; i < string.length(); i++){
complete = StringSearch(string,'n').toString();
}
//********
}
public static int[] StringSearch(String string, char lookfor) {
int[]num = new int[string.length()];
for(int i = 0; i < num.length; i++){
if(string.charAt(i)== lookfor){
num[i] = i;
}
}
return num;
}
}
The method works fine, and returns this:
0
0
2
3
0
0
What I am trying to do, is make those into 1 string so it would look like this "002300".
Is there any possible way of doing this? I have tried to do it in the starred area of the code, but I have had no success.
just do
StringBuffer strBuff = new StringBuffer();
for(int i = 0; i<str.length(); i++)
{
if(str.charAt(i) == reqChar)
{
strBuff.append(str.charAt(i));
}
else
{
strBuff.append('0');
}
}
return str.toString();
Just add the result to the existing string with the += operator
String complete = "";
for(...)
complete += StringSearch(string,'n').toString();
I would just use java's regex library, that way it's more flexible (eg if you want to look for more than just a single character). Plus it's highly optimized.
StringBuilder positions = "";
Pattern pattern = Pattern.compile(string);
Matcher matcher = pattern.matcher(lookfor);
while(matcher.find()){
positions.append(matcher.start());
}
return positions;
Updated with StringBuilder for better practices.
public static String StringSearch(String string, char lookfor) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < string.length; i++){
if(string.charAt(i) == lookfor)
sb.append(i);
else
sb.append("0");
}
return sb.toString();
}
Then you can just call it once, without a for loop. Not sure why you call it for every character in the string.
complete = StringSearch(string,'n');

Categories