I'm trying to split a string into an array. This should be fine as str.split(" ") should work fine, however the string is actually in the form of "xyz 100b\nabc 200b\ndef 400b". I'm wondering what the best way to handle this is. I also need to return 4 strings in the format they gave. Below is how I'm trying it now, but it's not splitting the array up correctly. My goal is to get the array split to ["xyz", "100b", "abc", "200b", "def", "400b"]
public static String solution(String words){
String array[] = words.split(" ");
/*
There's a lot of other code manipulating the array to get 4 figures in the
end. This doesn't matter, it's just splitting the array and the return that
is my issue
In the end I will have 4 integers that I want to return in a similar way
that they gave them to me.
*/
return "answer 1" + String.valueOf(num1) + "b\n" +
"answer2 " + String.valueOf(num2) + "b\n" +
"answer 3" + String.valueOf(num3) + "b\n" +
"answer4 " + String.valueOf(num4) + "b\n";
}
EDIT:
String array [] = str.split("\n| ") will split the array as I needed, thank you A.Oubidar
I hope i understood your question right but if you're looking to extract the number and return them in the specific format you could go like this :
// Assuming the String would be like a repetition of [word][space][number][b][\n]
String testString = "xyz 100b\nabc 200b\ndef 400b";
// Split by both endOfLine and space
String[] pieces = testString.split("\n| ");
String answer = "";
// pair index should contain the word, impair is the integer and 'b' letter
for (int i = 0; i < pieces.length; i++) {
if(i % 2 != 0 ) {
answer = answer + "answer " + ((i/2)+1) + ": " + pieces[i] + "\n";
}
}
System.out.println(answer);
This is the value of answer after execution :
answer 1: 100b
answer 2: 200b
answer 3: 400b
You should put this code in the "return" instead of the one you already have:
return "answer 1" + array[0] + "b\n" +
"answer 2 " + array[1] + "b\n" +
"answer 3" + array[2] + "b\n" +
"answer 4 " + array[3] + "b\n";
The split() method takes one regular expression as argument. This: input.split("\\s+") will split on whitespace (\s = space, + = 1 or more).
Your question is unclear, but if you're supposed to extract the '100', '200', etc, regular expressions are also pretty good at that. You can throw each line through a regular expression to extract the value. There are many tutorials (just google for 'java regexp example').
Related
I want to know why we concatenate a dummy string with a variable while printing its value.
Eg.
system.out.print(var + " ");
Concatenation with an empty string is a technique some developers use to convert any value to a string. It's unnecessary with System.out.print as that accepts any value anyway. I prefer using String.valueOf anyway:
String text = String.valueOf(variable);
This is clearer in terms of the purpose being converting a value to a string, rather than concatenation.
However, in the case you've given, it's possible that the developer wasn't just using concatenation for that purpose - but actually to get the extra space. For example:
int var1 = 1, var2 = 2, var3 = 3;
System.out.print(var1 + " ");
System.out.print(var2 + " ");
System.out.print(var3 + " ");
Those will all print on the same line:
1 2 3
Other options include:
Using a StringBuilder to build up the string before printing it
Putting it all into a single System.out.print call: System.out.print(var1 + " " + var2 + " " + var3);
Using printf instead: System.out.printf("%d %d %d", var1, var2, var3);
Extremely sorry. The question was l1.setText(var+" "); and it is done because a text field cannot take an integer value, so we concatenate a dummy string at the end of it, so the integer value in var can be printed.
Thank you all for helping me out!
For example if I have a text file showing different integers, but if it comes across a value where it has a letter for example, it would throw a NumberFormatException. I have seen many times where a try-catch statement would be used, but is there any other way to handle this exception besides that? Here is an example for a txt file called "data" (Note that there are three integers separated by whitespace)
545F6 6 100
12N45 A 50
would the following code work?
while (data.hasNextLine()){
data.nextInt();
if (!data.hasNextInt()){
System.out.println("The number " + data.next() + " is invalid");
data.next();
}
}
I am beginner in Java so I was curious if there was another way to ignore the strings, and show that it is invalid if it does not return an integer.
You might want to give a try to regular expressions and use them in simple loop that checks if in the given strings separated by whitespace characters, there are only digits present (I added some more explanations in comments):
String a = "545F6 6 100";
String b = "12N45 A 50";
List<String> results = new ArrayList<>(); // here you will store matching numbers
for(String str : a.split("\\s+")) { // for each String that you get after splitting source String at whitespace characters...
if(str.matches("\\b[\\d]+\\b")) { //check if that String matches given pattern: word boundary-only digits-word boundary
results.add(str); // it there is a match, add this String to results ArrayList
} else {
System.out.println("The number " + str + " is invalid");
}
}
System.out.println("Valid numbers: " + Arrays.toString(results.toArray())); // just to print results
results.clear();
System.out.println();
for(String str : b.split("\\s+")) {
if(str.matches("\\b[\\d]+\\b")) {
results.add(str);
} else {
System.out.println("The number " + str + " is invalid");
}
}
System.out.println("Valid numbers: " + Arrays.toString(results.toArray()));
Output that you get from these loops:
The number 545F6 is invalid
Valid numbers: [6, 100]
The number 12N45 is invalid
The number A is invalid
Valid numbers: [50]
You might want to read more about how to use regular expressions in Java API documentation of the class Pattern here.
I have the following code for a class:
public class sqrt
{
public sqrt()
{
char start = 'H';
int second = 3110;
char third = 'w';
byte fourth = 0;
char fifth = 'r';
int sixth = 1;
char seventh = 'd';
float eighth = 2.0f;
boolean ninth = true;
String output = new String(start + second + " " + third + fourth +
fifth + sixth + seventh + " " + eighth + " " + ninth);
System.out.println(output);
}
}
The required output is:
H3110 w0r1d 2.0 true
However, this outputs the following:
3182 w0r1d 2.0 true
I can only assume this is because it sees the numerical (ASCII) value of char 'H' and adding it to int 3110.
My question is:
Shouldn't new String() convert each item within to a string and concatenate them?
If I change the output to:
String output = start + second + " " + third + fourth +
fifth + sixth + seventh + " " + eighth +
" " + ninth;
It does the same thing, and adds the value of char and int together before concatenating the rest.
I know I can overcome this by adding a "" + before start, and I suppose that explains why it is seeing the ASCII value of char 'H' (because it looks at the next value, sees it's an int, and goes from there?), but I'm confused as to why the new String() isn't working as intended.
PS, I want to write better questions, and I know I am still a bit of a beginner here, so any advice in that regard would be appreciated as well. PMs are more than welcome, if anyone is willing to take the time to help.
PPS, If I figure out why this is, I will post the answer myself, but I am really trying to learn this, and I'm just very confused.
I can only assume this is because it sees the numerical (ASCII) value of char 'H' and adding it to int 3110.
That's perfectly correct.
Shouldn't new String() convert each item within to a string and concatenate them?
The String constructor has no control over this, because the expression start + second + " " + ... is evaluated before.
The concise approach here is to use a StringBuilder. It has methods to accept all primitive types and arbitrary objects.
String output = new StringBuilder().append(start).append(second).append(' ')
.append(third).append(fourth).append(fifth).append(sixth).appends(seventh)
.append(' ').append(eighth).append(' ').append(ninth).toString();
or
StringBuilder builder = new StringBuilder();
builder.append(first);
builder.append(second);
builder.append(' ');
builder.append(third);
builder.append(fourth);
builder.append(firth);
builder.append(sixth);
builder.append(seventh);
builder.append(' ');
builder.append(eighth);
builder.append(ninth);
String output = builder.toString();
Shouldn't new String() convert each item within to a string and concatenate them?
new String() has nothing to do with it. First we evaluate the expression. Then we pass the value of the expression to the String constructor.
So first of all we're adding a char to an int; this is integer addition. Then the result of that (3112) is converted to string so it can be concatenated to the string " ". Thereafter at least one operand is a String therefore concatenation applies.
I'm confused as to why the new String() isn't working as intended.
It's working as intended, which is to initialize a new String object representing the data passed to it.
Shouldn't new String() convert each item within to a string and
concatenate them?
Currently, you're using this overload of the String constructor which states:
Initializes a newly created String object so that it represents the
same sequence of characters as the argument; in other words, the newly
created string is a copy of the argument string.
Essentially, as the string you passed to the String constructor is 3182 w0r1d 2.0 true the new string object is a copy of that. Nothing else is performed.
you can use the code below since characters cannot be changed to string inherently
so:
String output = new String(String.valueOf(start) + second + " " + third + fourth +
fifth + sixth + seventh + " " + eighth + " " + ninth);
I have:
String s=" \"son of god\"\"cried out\" a good day and ok ";
This is shown on the screen as:
"son of god""cried out" a good day and ok
Pattern phrasePattern=Pattern.compile("(\".*?\")");
Matcher m=phrasePattern.matcher(s);
I want get all the phrases surrounded by "" and add them to an ArrayList<String>. It might have more than 2 such phrases. How can I get each phrase and put into my Arraylist?
With your Matcher you're 90% of the way there. You just need the #find method.
ArrayList<String> list = new ArrayList<>();
while(m.find()) {
list.add(m.group());
}
An alternative approach, and I only suggest it because you did not explicitly say you must use regex matching, is to split on ". Every other piece is your interest.
public static void main(String[] args) {
String[] testCases = new String[] {
" \"son of god\"\"cried out\" a good day and ok ",
"\"starts with a quote\" and then \"forgot the end quote",
};
for (String testCase : testCases) {
System.out.println("Input: " + testCase);
String[] pieces = testCase.split("\"");
System.out.println("Split into : " + pieces.length + " pieces");
for (int i = 0; i < pieces.length; i++) {
if (i%2 == 1) {
System.out.println(pieces[i]);
}
}
System.out.println();
}
}
Results:
Input: "son of god""cried out" a good day and ok
Split into : 5 pieces
son of god
cried out
Input: "starts with a quote" and then "forgot the end quote
Split into : 4 pieces
starts with a quote
forgot the end quote
If you want to ensure that there is an even number of double quotes, ensure the split result has an odd count.
Why does the split method not return an array with 2 elements?
for(int i = 0; i < temparray.size(); i++)
{
if (temparray.get(i).contains("_"))
System.out.println("True" + temparray.get(i).length() + " " + temparray.get(i));
String[] temp = temparray.get(i).split("_");
System.out.println(temp[0]);
//System.out.println(temp[1]);
//friendsOld.add(new Friend(temp[0],temp[1]));
}
If I uncomment either of the lines, I get ArrayOutofBoundsException: 1. The println always returns True, the length of the String, and then a String with _ located within the String - NOT at the end.
I've tried negative parameters for .split(), converting the String to char arrays and breaking the String using indexOf() to find the location of _ then splitting it manually using substring(). There might be something wrong with the String itself but here is the code for the array of Strings: ArrayList<String> temparray = new ArrayList<String>();.
It seems that you forgot the braces after the if-statement:
if (temparray.get(i).contains("_")) {
System.out.println("True" + temparray.get(i).length() + " " + temparray.get(i));
String[] temp = temparray.get(i).split("_");
System.out.println(temp[0]);
System.out.println(temp[1]);
friendsOld.add(new Friend(temp[0],temp[1]));
}
The way you wrote it, the string is splitted even when it doesn't contain an underscore. Only the output of "True [...]" is limited to strings containing one.
You should start using the debugger - it will display the values of variables when hitting an exception breakpoint allowing you to further track down the bugs in your code.
Did you mean to put all of that code in braces?
for(int i = 0; i < temparray.size(); i++)
{
if (temparray.get(i).contains("_")) {
System.out.println("True" + temparray.get(i).length() + " " + temparray.get(i));
String[] temp = temparray.get(i).split("_");
System.out.println(temp[0]);
//System.out.println(temp[1]);
//friendsOld.add(new Friend(temp[0],temp[1]));
}
}
Your if condition only applies to the next line. Therefore, if the temparray.get(i) does not contain a '_', you only get a single result from split.