How could I split the numbers in the string "542" into individual digits? On my desktop I can split the numbers using String.split("") and it works fine. But when run on Android, I get a NumberFormatException: Invalid int: "".
This is my code:
public void render(int n, SpriteBatch batch) {
String[] numbers = String.valueOf(n).split("");
for(int i = 0; i < numbers.length; i++)
batch.draw(Assets.numbers[0][Integer.valueOf(numbers[i])], pos.x + (50 * i), pos.y);
}
Is there an alternative way?
You can use String.charAt, that will give you a Character. Removing '0' will give you a value from 0 to 9.
public void render(int n, SpriteBatch batch) {
String string = Integer.toString(n);
for(int i = 0; i < string.length(); ++i)
batch.draw(Assets.numbers[0][string.charAt(i) - '0'],
pos.x + (50 * i), pos.y);
}
Your use of String.split("") will always leave the first index empty (that is, the String: ""). This is why you are getting NumberFormatException: Invalid int: "" when trying to run Integer.valueOf(numbers[0]).
Suggest using string.charAt(index) to iterate over the characters in String.valueOf(n) instead.
Splitting on "" will cause the first element of the resulting array to be a blank, because the blank regex matches everywhere, including start of input.
You need to split after every character:
String[] digits = str.split("(?<=.)");
This regex is a look behind that assets there is a character before the match. Look behinds are non-consuming, so you don't lose any input making the split.
Related
I'm creating a simple program that gets 2 certain strings on an input from a JTextArea. It needs to find a non-integer string then finds an integer. All values matching from the same non-integer string will add and display the result in a JTextField. Like in the example below, all numbers who matches "ax" will be added together and the final result will be displayed in the texfield below the label "AX Box" (25 + 5 = 30)
My following code:
JTextField ax, bx, cx, dx;
int totalAX, totalBX, totalCX, totalDX;
String[] lines = textArea.getText().split("\\n"); // split lines
System.out.println(Arrays.toString(lines)); // convert each line to string
for (int i = 0; i < lines.length; i++) {
if (lines.contains("ax") {
// add each numbers.
// for example, 25 + 5
totalAX = totalAX + i;
ax.setText("Total: " +totalAX);
}
}
My problem is that the program cannot find the substring "ax", "bx" and so on. What's the best approach in this? I get errors like:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "ax"
I'm not sure that you're actually splitting the array, the escape sequence for a line jump is \n, you have it as \\n.
You are also only printing the array lines if you need to convert it to String you should be reassigning a value for it like:
for (int i = 0; i < lines.length; i++) {
String line = lines[i].toString();
And I'm pretty sure you don't need the toString() as it should come as a String variable from the textBox
After this you need to find if it contains the "ax" and the index where it is first contained, keep that number and use it to substring the whole line to find the number, so bearing in mind that the number should be in the last place of the string you would be looking at something like this after (inside) the loop:
if (line.contains("ax") {
int theIndex = line.indexOf("ax");
line = line.substring(theIndex);
}
Or in a oneliner:
if (line.contains("ax") {
line = line.substring(line.indexOf("ax"));
}
I used regex to extract numbers from the lines that match your text.
Pattern pattern = Pattern.compile("[0-9]+");
Matcher m;
System.out.println(Arrays.toString(lines));
for (int i = 0; i < lines.length; i++) {
if (lines[i].contains("ax")) {
m = pattern.matcher(lines[i]);
if (m.find()) {
totalAX += Integer.parseInt(m.group());
}
}
}
ax.setText("Total: " +totalAX); //put this line outside of the loop so that it will show the totalAX after all numbers have been read.
Look for patterns like "zip" and "zap" in the string -- length-3, starting with 'z' and ending with 'p'. Return a string where for all such words, the middle letter is gone, so "zipXzap" yields "zpXzp"
Here is a solution i got from someone:
public class Rough {
public static void main(String [] args){
StringBuffer mat = new StringBuffer("matziplzdpaztp");
for(int i = 0; i < mat.length() - 2; ++i){
if (mat.charAt(i) == 'z' & mat.charAt(i + 2) == 'p'){
mat.deleteCharAt(i + 1);
}
}
System.out.println(mat);
}
}
But why is it that the for loop condition (i < mat.length() -2) is not (i < mat.length())????
Because in the loop:
if (mat.charAt(i) == 'z' & mat.charAt(i + 2) == 'p'){
// -----------------------------------^^^^^
If i were bound by i < mat.length(), then i + 2 would be out of bounds.
Because you don't have to reach the end of your sentence since your words are at least three letters long.
"2" stands for "the length except the first word",you just need to check all the positions in the string variable , and treat the positions as the first word of the substring , so just ignore the "length of the substring without the first word".
in your case , the length of "z*p" is 3, you just check all the position in the string , and treat the position as z to check something ,so just ignore "*p" ,which has length 2.
mat.length() will give length 14 and if you check for mat.charAt(i + 2) at the end it will give java.lang.StringIndexOutOfBoundsException because the string counts from index 0 not from 1. If you still want to use mat.length() you have to replace the AND '&' operator with short circuit AND '&&' operator in if condition.
I'd like to count the amount of characters within a string, and cut off any excess characters of the string. I thought of just using a while loop and a char, but I need to pass in a string. I also tried to use the remainder function, but I"m pretty sure it wouldn't work.
So, essentially, a counter for a string and then to limit that string to x amount of characters.
If I were to set the string to a single character, say
String x = "*";
Then implemented a counter in a for loop...
for(int i = 0; i < 6; i++){
???
}
Would that work? I feel like it wouldn't, and that it would just be more effective for me to declare
char x = 'a';
...
I'm trying to make this as vague as possible so that I can take ideas and implement them so it's not like I'm stealing anybody's code for homework, I just need a little help.
String myString = "myString";
int maxLength = 3;
if (myString.length() > maxLength)
myString = myString.substring(0, maxLength);
Result will be "myS"
"I was searching around on the web for a manual code to count the amount of characters within a string, and then to a further extent cut off any excess characters of the string."
Count amount of characters within a string:
int length = stringName.length();
Cutting off extra characters of the string
int maxAmount; //wherever you want to stop
if(length > maxAmount)
{
stringName = stringName.substring(0,stopPoint);
}
I have a string String email="rachitgulati26#gmail.com" so its length is 24.
I want result like rachit************il.com.That means 1/4 of initial same and last 1/4 same.
Just want to convert 1/2 from middle to * with the help of regEX.
Thanks
You could do something like this:
"rachitgulati26#gmail.com".replaceAll("(?<=.{5}).(?=.{5})", "*");
this will replace all characters to * apart from the first and last 5.
In response to your question, you could make this flexible like this:
String email = "rachitgulati26#gmail.com";
int i = email.length() / 4;
email = email.replaceAll("(?<=.{" + i + "}).(?=.{" + i + "})", "*");
Just a word of warning, if you were to start using this in production code, you probably want to create a way of caching these regexes, based on the value of i. This way is for demonstration of the pattern only, and will compile a regex Pattern each time it is used.
One way to do it is to create a string of '*'s that is the correct length, then concatenate on the surrounding parts of the original string. That way you don't have to do any looping:
public static String starize(String str){
char[] middle = new char[str.length()/2];
Arrays.fill(middle, '*');
return str.substring(0, str.length()/4)
+ String.copyValueOf(middle)
+ str.substring(3 * str.length() / 4);
}
You could convert to char array, process and convert back to String:
String email = "rachitgulati26#gmail.com";
char[] a = email.toCharArray();
for (int i = 0, j = a.length >> 2; i < a.length >> 1; i++, j++)
a[j] = '*';
email = new String(a);
Result:
rachit************il.com
You can't identify the middle of a string using a single regular expression unless the lengths have a finite number of values.
I am trying to place spaces in between a number that has been entered in a textfield. I am using the following code:
for(int i = 0; i <= 2; i++)
{
char cijfer = tf1.getText().charAt(i);
char getal1 = tf1.getText().charAt(0);
char getal2 = tf1.getText().charAt(1);
char getal3 = tf1.getText().charAt(2);
}
String uitvoerGetal = getal1 + " " + getal2 + " " + getal3;
I suppose I don't understand the charAt() function yet, does anyone have a link explaining it in a way so I might be able to make this work too? Thanks in advance!
Example:
public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
char result = s.charAt(8);
System.out.println(result);
}
}
This produces the following result:
a
In more Detail From java docs
public char charAt(int index)
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
If the char value specified by the index is a surrogate, the surrogate value is returned.
Specified by:
charAt in interface CharSequence
Parameters:
index - the index of the char value.
Returns:
the char value at the specified index of this string. The first char value is at index 0.
Throws:
IndexOutOfBoundsException - if the index argument is negative or not less than the length of this string.
In straight words You can't. You can't add space in int datatype because int is meant to store the integer value only. Change int to String to store the space in between.
Okay, let's see what's wrong with your code...
Your for-loop is 1-based instead of the standard 0-based. That's not good at all.
You're attempting to assign a char to a String (3 times), the first call to charAt is correct, but for some reason you then switch to using a String?
Finally you're attempting to assign a String to an int, which is just completely nonsensical.
You have a number of problems, but well done on an honest attempt.
First up, the indexes in a string are zero-based, so charAt(0) gives you the first character, charAt(1) gives you the second character, and so on.
Secondly, repeating all your calls to charAt three times is probably unnecessary.
Thirdly, you must be careful with your types. The return value from charAt is a char, not a String, so you can't assign it to a String variable. Likewise, on the last line, don't assign a String to an int variable.
Lastly, I don't think you've thought about what happens if the text field doesn't contain enough characters.
Bearing these points in mind, please try again, and ask for further help if you need it.
Try following code
String text = tf1.getText(); // get string from jtextfield
StringBuilder finalString = new StringBuilder();
for(int index = 0; index <text.length(); index++){
finalString.append(text.charAt(index) + " "); // add spaces
}
tf1.setText(finalString.toString().trim()) // set string to jtextfield