The below code throws me StringIndexOfBoundException
if (custom.getUser().equals("0") || custom.getUser().equals("")) {
vital.add(new Pair<String, String>("User", "-"));
} else {
vital.add(new Pair<String, String>("User", custom.user() + "F" + "\n" + custom.getName().subString(0,1));
}
Displaying the first character of the String. The below code is working fine, but i am not sure whether its the correct way of doing it.
String name = "";
if (custom.getUser().equals("0") || custom.getUser().equals("")) {
vital.add(new Pair<String, String>("User", "-"));
} else if (!custom.getName().equals("")) {
name = custom.getName().substring(0, 1);
} else {
vital.add(new Pair<String, String>("User", custom.user() + "F" + "\n" + name));
}
First, from where do you get the exception?
custom.getName().subString(0,1) throws a StringIndexOfBoundException only if custom.getName() is empty. But if it's empty, the code will not enter the else branch, so you can't be getting the exception.
Second, the second way is not equivalent to the first: if custom.getName() is neither empty nor "0" nothing is added to vital.
I feel this is an improvement:
if (custom.getUser().equals("0") || custom.getUser().isEmpty()) {
vital.add(new Pair < String, String > ("User", "-"));
} else {
// limit scope of variable to else-branch
String name = "";
// check empty string with isEmpty
if (!custom.getName().isEmpty()) {
name = custom.getName().substring(0, 1);
}
// add a new Pair in any case
vital.add(new Pair < String, String >
("User", custom.user() + "F" + "\n" + name));
}
You've just got a logic error in the first block. You can enter the block with an empty string (custom.getName().equals("")), which means that custom.getName().length() == 0. So when you try to get the first character with substring(0,1) it throws a StringIndexOfBoundException. Just change the conditional to something like this:
if (custom.getUser().equals("0") || custom.getName().length() > 0) {
In the else if condition you need to check if the string "custom.getName().length() >= 2".
Related
public String onGoogleCommand(String[] args) {
if(args.length == 0){
return "Type in a question after the google command!";
}
if(args.length >= 1){
return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];
}
return "What?";
}
What I am asking about is the part where I say return "https://www.google.com/#q=" + args[0] + "+" + args[1] + "+" + args[2];. Obviously, this probably isn't the best way to code a search function, but how can I automate this so that the words from the String[] args automatically get put into my return statement with "+" between each of the words so that it would return something like https://www.google.com/#q=please+help+me+with+this+question?
Though there is already an accepted answer, I am giving some alternatives:
Java 8 String join
If you are using Java 8, it already provides a join method that you can make use of:
return "https://www.google.com/#q=" + String.join("+", args);
(If you are using Java < 8, there are still lots of similar util you can find, like Commons Lang)
Join with Loop
It is also not difficult to write a proper and concise loop for this:
StringBuilder result = new StringBuilder("https://www.google.com/#q=");
boolean first=true;
for (String arg : args) {
result.append(first? "" : "+").append(arg);
first = false;
}
return result;
Yet other form, as someone in comment seems does not like a boolean flag:
StringBuilder result = new StringBuilder();
for (String arg : args) {
result.append(result.length() == 0 ? "https://www.google.com/#q=" : "+")
.append(arg);
}
return result;
By using Arrays.toString and replace you can achieve the result you want
String array[] = {"please", "help", "me"};
String output = "https://www.google.com/#q=" + Arrays.toString(array).
replace("[", "").
replace("]", "").
replace(", ", "+");
System.out.println(output);
output
https://www.google.com/#q=please+help+me
You can use the below method :
public static String join(String[] array, String separator) {
if (array == null) {
return null;
} else {
if (separator == null) {
separator = "";
}
if (array.length <= 0) {
return "";
} else {
StringBuilder buf = new StringBuilder(array.length * 16);
for (int i = 0; i < array.length; ++i) {
if (i > 0) {
buf.append(separator);
}
if (array[i] != null) {
buf.append(array[i]);
}
}
return buf.toString();
}
}
}
It's actually imported from org.apache.commons.lang3; package
Example :
public static String onGoogleCommand(String[] args) {
if (args.length == 0) {
return "Type in a question after the google command!";
}
if (args.length >= 1) {
return "https://www.google.com/#q=" + join(args, "+");
}
return "What?";
}
You could iterate over the args[] array and build your query string:
public String onGoogleCommand(String[] args) {
if(args == null || args.length == 0) {
return "Type in a question after the google command!";
}
StringBuilder queryString = new StringBuilder("https://www.google.com/#q=");
queryString.append(args[0]);
for (int i=1; i < args.length; ++i) {
queryString.append("+").append(args[i]);
}
return queryString.toString();
}
You just need to use a foreach loop, something like this can help:
if(args.length >= 1){
String finalStr="";
for(String currentStr:args){
finalStr+=currentStr+"+";
}
finalStr= finalStr.substring(0, finalStr.length()-1);
}
Using this code you will have your search in finalStr, just append it's value to your URL, as you can see the symbol "+" is added after each element and I always remove the last element ("+") because it's unnecessary at the end of the String.
Basically I've built up a string and I need to put an if statement on when to use a comma and a space. So basically I need it be after the first element and not on the last element.
This is what my current code is:
And the output it returns is
"thing1thing2thing3"
I want to make the output to be
"thing1, thing2, thing3"
And I need an if statement as part of the requirements on when to place the commas and spaces.
Thanks in advance.
This might be a little advanced for you, but it's very easy when using Java 8 (if things is a Collection:
return Optional.of(things.stream()
.filter(thing -> thing.getCategory() == things.STUFF)
.collect(Collectors.joining(", ")))
.orElse("nothing");
If you're using Java 7, then you can do it manually:
StringBuilder sb = new StringBuilder();
for (Thing thing : things) {
if (things.getCategory() == some.STUFF){
sb.append(thing.getName()).append(", ");
}
}
if (s.isEmpty()) {
return "nothing";
}
return sb.delete(sb.length() - 2, sb.length()).toString();
I'd use a for-loop rather than a for-each loop - only because I see it as eliminating the need for an additional counter variable. This is how I'd approach the problem.
String[] things = {"thing 1", "thing 2", "thing 3", "thing 4"};
for(int i = 0; i < things.length; i++)
{
if(i < things.length - 1)
{
System.out.print(things[i] + ", ");
}
else
{
System.out.print(things[i] + ".");
}
}
There are a few unclear things about the question, so the code below is based on what I have understood so far.
String s = "";
boolean isComma = true; // true = comma, false = space.
for (Thing thing : things)
{
if (things.getCategory() == thing.STUFF)
{
//Check if there already exists an entry within the String.
if (s.length() > 0)
{
//Add comma or space as required based on the isComma boolean.
if (isComma)
{
s += ", ";
}
else
{
s += " ";
}
}
s += thing.getName();
}
}
if (s.equals(""))
{
s += "nothing";
}
return s;
I'd like to check if some character is between 2 other chars.
For example, given the following String:
String myString = "Hello, my name is 'Tesda', and this is 'ASDfs'."
I want to check if the 'S' in "ASDfs" is between '' or not, also keeping in mind I want to check every '', not jump directly to the second ''.
I've tried a silly code (I'm not familiar with this at all, as I didn't need it until now), which is:
boolean isBetween;
if (!MyString.substring(MyString.indexOf("'"), MyString.indexOf("'")).contains("S"))
isBetween = true;
Well, this didn't work and I don't understand how to make it perfectly.
Also, I want to replace that S with another letter, but I want only between the '', not the one after "my name is", I thought about getting the index of the letter, if it's inside '', then replace that letter in that specific index, is that possible?
Using the provided answer, I've made the following code ( which why i posted this question for ) :
String NewText = "Hello, My NAme is 'Ba', i'm from 'LA' ";
boolean contains = false;
int indexOfS = -1;
String MyString_temp = NewText;
while (MyString_temp.length() >= 0) {
int first = MyString_temp.indexOf("\'");
if(first == -1)
{
break;
}
int second = MyString_temp.substring((first + 1)).indexOf("\'");
second = second + first + 1;
if(second == -1)
{
break;
}
contains = MyString_temp.substring(first,second).contains("A");
if (contains) {
break;
}
MyString_temp = MyString_temp.substring((second + 1));
}
Log.i("ResultTest","Index is: " + indexOfS + " - Text is: " + MyString_temp);
if(!contains){
Log.i("ResultTest", "Yes " + i);
Log.i("ResultTest","TeF: " +NewText.replace(NewText.substring(indexOfS,indexOfS+1),"Test"));
} else
Log.i("ResultTest", "No " + i);
Output
Index is: -1 - the text here ..
Failed to output, invalid index
Consider using regular expressions. Your example could be as simple as
MyString.matches("\'S\'");
EDIT: Updated answer for updated question: Your initial code block looked like it might have done the trick, however you must remember that indexOf() only returns the first occurence of what you need. This could work:
String MyString_temp = MyString;
String lookingFor = "S";
String separator = "\'";
boolean contains = false;
int indexOfLooking = -1;
while (MyString_temp.length() >= 0) {
int first = MyString_temp.indexOf(separator);
if(first == -1) {
break;
}
int second = MyString_temp.substring(first + 1).indexOf(separator);
second += first + 1;
if(second == -1) {
break;
}
indexOfLooking = MyString_temp.substring(first, second).indexOf(lookingFor);
contains = (indexOfLooking >= 0)
if (contains) {
break;
}
MyString_temp = MyString_temp.substring(second + 1);
}
After the while loop, contains has your answer, and indexOfLooking has the location of S.
With Apache Commons you can use the following method:
StringUtils.substringBetween(str, "'");
to get an String[] with all results use this:
StringUtils.substringsBetween(str, "'", "'");
In the following code
for (UserSelection userSelection : filterList) {
String filterName = checkForDataHolder(userSelection
.getCriteriaName());
csvRow.append(filterName + ":");
List<String> list = userSelection.getCriteriaValues();
String filterval = "";
csvRow.append(DATA_DELIMITER);
for (String value : list) {
filterval += checkForDataHolder(value) + ", ";
}
if (filterval.indexOf(",") != -1) {
filterval = filterval.substring(0, filterval
.lastIndexOf(","));
}
csvRow.append(DATA_HOLDER + filterval + DATA_HOLDER);
csvRow.append(NEW_LINE);
}
This line filterval += checkForDataHolder(value) + ", ";
causes Concatenation of strings within a loop which creates a StringBuffer for each concatenation. When placed in a loop, this can result in the creation and collection of large numbers of temporary objects.
How do I create a StringBuffer before entering the loop, and append to it within the loop ?
Also in the following code
final StringBuffer csvRow = new StringBuffer();
csvRow.append(NEW_LINE);
csvRow.append(" ");
I want to Replace the string literal with a character literal to improve performance
consider the following code
public void writeHeader(List<String> headerColList) throws IOException {
this.header = headerColList;
String val;
try {
final StringBuffer csvRow = new StringBuffer();
for (int i = 0; i < header.size(); i++) {
if (i > 0) {
csvRow.append(DATA_DELIMITER);
}
val = checkForDataHolder(headerColList.get((i)));
if (!StringUtil.isEmpty(val)) {
csvRow.append(DATA_HOLDER + val + DATA_HOLDER);
}
}
if(!isHeaderProcessed) {
if(this.header != null) {
writer.write(csvRow.toString());
writer.write(NEW_LINE);
}
isHeaderProcessed = true;
}
} catch (Exception e) {
log.error(e);
}
}
I want to consider catching a more specific class of exception (one or more subclasses of Exception).which is the best option here ?
for (String value : list) {
filterval += checkForDataHolder(value) + ", ";
}
if (filterval.indexOf(",") != -1) {
filterval = filterval.substring(0, filterval
.lastIndexOf(","));
}
What's going on here? seems to be a very inefficient of taking off the trailing space. Maybe this is faster:
bool Appended = false;
for (String value : list) {
if(Appended) { filterval += " ";}
filterval += checkForDataHolder(value) + ",";
Appended = true;
}
Things like scanning along a string are more time consuming than using " " instead of ' '.
The exception is really your choice. Are you expecting more than memory allocation errors?
How do I create a StringBuffer before entering the loop, and append to it within the loop?
StringBuilder sb = new StringBuilder();
for ..... { }
String filterval = sb.toString();
I want to Replace the string literal with a character literal to improve performance?
So what keeps you from writing ' ' instead of " "? By the way, it wouldn't probably improve performance in any noticeably way. In the case of NEW_LINE, I am not sure if this is a character or a string constant, but note it may be a string constant with a length greater 1, like "\r\n".
I want to consider catching a more specific class of exception (one or more subclasses of Exception).which is the best option here ?
The best option is to catch the exceptions that may actually occur and that you can handle.
I'd like to retrieve whatever is in quotes that someone enters as a string, i'm assuming it's substring that I need but i'm not sure how.
When the user inputs a string mixed with words and numbers all separated by one space:
hey 110 say "I am not very good at Java" but " I can fish pretty well"
Then I want to be able to take the "I am not very good at Java" and the "I can fish pretty well" and print out what's inside the quotes so there can be multiple quotes in the string.
right now I have if( userInput=='"') then I do something with substring but i'm not sure what.
I can't use split, trim, tokenizer, regex or anything that would make this really easy unfortunatley.
it's all in this method where I try to identify if something in the string is a word, number or a quote:
public void set(String userInput)// method set returns void
{
num=0;// reset each variable so new input can be passed
String empty="";
String wordBuilder="";
userInput+=" ";
for(int index=0; index<userInput.length(); index++)// goes through each character in string
{
if(Character.isDigit(userInput.charAt(index)))// checks if character in the string is a digit
{
empty+=userInput.charAt(index);
}
else
{
if (Character.isLetter(userInput.charAt(index)))
{
wordBuilder+=userInput.charAt(index);
}
else
{
if(userInput.charAt(index)=='"')
{
String quote=(userInput.substring(index,);
}
}
//if it is then parse that character into an integer and assign it to num
num=Integer.parseInt(empty);
word=wordBuilder;
empty="";
wordBuilder="";
}
}
}
}
Thanks!
Try the next:
public static void main(String[] args) {
String input = "\"123\" hey 110 say \"I am not very good at Java\" but \" I can fish pretty well\"";
int indexQuote = -1;
boolean number = true;
String data = "";
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (Character.isWhitespace(ch)) {
if (data.length() > 0 && indexQuote == -1) {
if (number) {
System.out.println("It's a number: " + data);
} else {
System.out.println("It's a word: " + data);
}
// reset vars
number = true;
data = "";
} else if (indexQuote != -1) {
data += ch;
}
} else if (ch == '"') {
if (indexQuote == -1) {
number = false;
indexQuote = i;
} else {
System.out.println("It's a quote: " + data);
// reset vars
number = true;
data = "";
indexQuote = -1;
}
} else {
if (!Character.isDigit(ch)) {
number = false;
}
data += ch;
if (data.length() > 0 && i == input.length() - 1) {
if (number) {
System.out.println("It's a number: " + data);
} else {
System.out.println("It's a word: " + data);
}
}
}
}
}
Output:
It's a word: hey
It's a number: 110
It's a word: say
It's a quote: I am not very good at Java
It's a word: but
It's a quote: I can fish pretty well
I'm not sure if this quite what you are looking for, but it will strip down the quoted parts in steps...
String quote = "I say: \"I have something to say, \"It's better to burn out then fade away\"\" outloud...";
if (quote.contains("\"")) {
while (quote.contains("\"")) {
int startIndex = quote.indexOf("\"");
int endIndex = quote.lastIndexOf("\"");
quote = quote.substring(startIndex + 1, endIndex);
System.out.println(quote);
}
}
Which outputs...
I have something to say, "It's better to burn out then fade away"
It's better to burn out then fade away
Updated
I don't know if this is cheating or not...
String quote = "I say: \"I have something to say, \"It's better to burn out then fade away\"\" outloud...\"Just in case you don't believe me\"";
String[] split = quote.split("\"");
for (String value : split) {
System.out.println(value);
}
Which outputs...
I say:
I have something to say,
It's better to burn out then fade away
outloud...
Just in case you don't believe me
Updated
Okay, fake String#split
StringBuilder sb = new StringBuilder(quote.length());
for (int index = 0; index < quote.length(); index++) {
if (quote.charAt(index) == '"') {
System.out.println(sb);
sb.delete(0, sb.length());
} else {
sb.append(quote.charAt(index));
}
}
Updated
Okay, this is basically fake split with options...
String quote = "blah blah 123 \"hello\" 234 \"world\"";
boolean quoteOpen = false;
StringBuilder sb = new StringBuilder(quote.length());
for (int index = 0; index < quote.length(); index++) {
if (quote.charAt(index) == '"') {
if (quoteOpen) {
System.out.println("Quote: [" + sb.toString() + "]");
quoteOpen = false;
sb.delete(0, sb.length());
} else {
System.out.println("Text: [" + sb.toString() + "]");
sb.delete(0, sb.length());
quoteOpen = true;
}
} else {
sb.append(quote.charAt(index));
}
}
if (sb.length() > 0) {
if (quoteOpen) {
System.out.println("Quote: [" + sb.toString() + "]");
} else {
System.out.println("Text: [" + sb.toString() + "]");
}
}
Which generates...
Text: [blah blah 123 ]
Quote: [hello]
Text: [ 234 ]
Quote: [world]
Know, I don't know how you are storing the results. I would be tempted to create some basic classes which were capable of storing the String results and add them to a List so I could maintain the order and maybe use a flag of some kind to determine what type they are...
Iterate over the string and use a temporary int variable to store when the quoted string started. When you see that it ends, you can extract that substring and do what you want with it.
Use StringUtils.subStringBetween
public class MyTestSecond {
public static void main(String...args){
String a = "hey 110 say \"I am not very good at Java\"";
// Method 1
if(a.contains("\""))
System.out.println(a.substring(a.indexOf("\""),a.lastIndexOf("\"")+1));
//Method 2
String[] array = a.split(" ");
for(int i=0;i<array.length;i++){
if(array[i].startsWith("\""))
System.out.println(a.substring(a.indexOf("\""),a.lastIndexOf("\"")+1));
}
}
}
public String getNextQuote(int index, String sentence){
return sentence.substring(sentence.indexOf("\"", index + 1), sentence.indexOf("\"", index + 2));
}
usage: call the method with an index as parameter. This index resembles the index of the last " that you've encountered.
Afterwards, it will return everything between the next two quotes.