Java - Finding a certain string in JTextArea - java

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.

Related

How to explode a string on a hyphen in Java?

I have a task which involves me creating a program that reads text from a text file, and from that produces a word count, and lists the occurrence of each word used in the file. I managed to remove punctuation from the word count but I'm really stumped on this:
I want java to see this string "hello-funny-world" as 3 separate strings and store them in my array list, this is what I have so far , with this section of code I having issues , I just get "hello funny world" seen as one string:
while (reader.hasNext()){
String nextword2 = reader.next();
String nextWord3 = nextword2.replaceAll("[^a-zA-Z0-9'-]", "");
String nextWord = nextWord3.replace("-", " ");
int apcount = 0;
for (int i = 0; i < nextWord.length(); i++){
if (nextWord.charAt(i)== 39){
apcount++;
}
}
int i = nextWord.length() - apcount;
if (wordlist.contains(nextWord)){
int index = wordlist.indexOf(nextWord);
count.set(index, count.get(index) + 1);
}
else{
wordlist.add(nextWord);
count.add(1);
if (i / 2 * 2 == i){
wordlisteven.add(nextWord);
}
else{
wordlistodd.add(nextWord);
}
}
This can work for you ....
List<String> items = Arrays.asList("hello-funny-world".split("-"));
By considering that you are using the separator as '-'
I would suggest you to use simple split() of java
String name="this-is-string";
String arr[]=name.split("-");
System.out.println("Here " +arr.length);
Also you will be able to iterate through this array using for() loop
Hope this helps.

Java- Having trouble figuring out why there's an arrayOutOfBoundsException going on in my cache simulation

This method is supposed to:
Poke through a text file filled with 32 rows of 10 hex strings.
Break them apart using a whitespace in between each as delimiter.
Store the hex strings in an array with 10 indices.
Since I'm simulating memory I then load the array into a simulated Register class.
I've gotten it to this step, but I'm having trouble seeing why this arrayOutOfBounds exception is occurring for the arrayString[] array.
public void setRegister(Register[] r) throws FileNotFoundException{ //pokes through the
//file and extracts hexes
Scanner s = new Scanner("/Users/adpitt/Documents/document.txt"); //macOS path
Register reggie = new Register(); //holding reg
while (s.hasNextLine()) {
String str = s.nextLine(); //slam a line into the string
for(int i = 0; i <= mainMemSize-1; i++){ //iterate through array of registers
for(int j = 0; j <= this.length-1; j++){
String arrayString[] = str.split("\\s+");//smash them to
//pieces, space = delimiter
reggie.reg[j] = arrayString[j];//THIS IS WHERE THE EXCEPTION OCCURS.
//I believe it's in arrayString[j],
//not sure why.
}//complete reggie!
r[i] = reggie;//load reggie into the register array to complete mm
}
}
s.close();
}
Why are you splitting the str in the inner loop? The str value is not changing anywhere inside those for loops. Can you try moving it out of the for loops, and just after String str=s.nextLine();
Also what is this.length? what if this.length-1 is greater than 10 (assuming str.split returns 10 hex strings, as per your initial description)?

Why isn't this code reversing user inputted text?

System.out.println("type something to get it back reversed...");
Scanner sc1 = new Scanner(System.in);
String x = sc1.nextLine();//user input
for(int i = x.length(); i > 0; i--)
{
System.out.print(x.substring(i));
}
In this code, I want to take user-inputted text and output it in reverse order (i.e. dog = god) with a for-loop and the substring method. The above code is non-functional.
For example...
-when I input "dog", I get "gog".
-when I input "computer", I get "rerteruterputermputeromputer"
It never outputs the first letter of the text. I'd be very grateful if somebody could help me out and explain this to me :)
See the API for the String class. The String.substring(int index) method creates a substring from the parameter index to the end of the String (so if x is dog, the x.substring(0) results in 'dog'. Perhaps you wish to use the two parameter substring method. Also note the indexes of the loop, starting at length - 1 and ending at 0
for ( int i = x.length()-1; i >= 0; i-- ){
System.out.print(x.substring(i, i+1));
}
substring(i) returns everything in your string from i to the end. To get the character at position i in a string, use charAt(i).
Also, the last index of the string is x.length()-1. The first is zero. So your loop should be something like:
for (int i = x.length()-1; i>=0; --i) {
System.out.print(x.charAt(i));
}
As copeg explained, substring() returns all characters after the character i. An easier solution would be to use charAt():
for(int i = x.length()-1; i >= 0; i--) {
System.out.print(x.charAt(i));
}

Split string of numbers into individual numbers

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.

Remove chars from string in Java from file

How would I remove the chars from the data in this file so I could sum up the numbers?
Alice Jones,80,90,100,95,75,85,90,100,90,92
Bob Manfred,98,89,87,89,9,98,7,89,98,78
I want to do this so for every line it will remove all the chars but not ints.
The following code might be useful to you, try running it once,
public static void main(String ar[])
{
String s = "kasdkasd,1,2,3,4,5,6,7,8,9,10";
int sum=0;
String[] spl = s.split(",");
for(int i=0;i<spl.length;i++)
{
try{
int x = Integer.parseInt(spl[i]);
sum = sum + x;
}
catch(NumberFormatException e)
{
System.out.println("error parsing "+spl[i]);
System.out.println("\n the stack of the exception");
e.printStackTrace();
System.out.println("\n");
}
}
System.out.println("The sum of the numbers in the string : "+ sum);
}
even the String of the form "abcd,1,2,3,asdas,12,34,asd" would give you sum of the numbers
You need to split each line into a String array and parse the numbers starting from index 1
String[] arr = line.split(",");
for(int i = 1; i < arr.length; i++) {
int n = Integer.parseInt(arr[i]);
...
try this:
String input = "Name,2,1,3,4,5,10,100";
String[] strings = input.split(",");
int result=0;
for (int i = 1; i < strings.length; i++)
{
result += Integer.parseInt(strings[i]);
}
You can make use of the split method of course, supplying "," as the parameter, but that's not all.
The trick is to put each text file's line into an ArrayList. Once you have that, move forwars the Pseudocode:
1) Put each line of the text file inside an ArrayList
2) For each line, Split to an array by using ","
3) If the Array's size is bigger than 1, it means there are numbers to be summed up, else only the name lies on the array and you should continue to the next line
4) So the size is bigger than 1, iterate thru the strings inside this String[] array generated by the Split function, from 1 to < Size (this will exclude the name string itself)
5) use Integer.parseInt( iterated number as String ) and sum it up
There you go
Number Format Exception would occur if the string is not a number but you are putting each line into an ArrayList and excluding the name so there should be no problem :)
Well, if you know that it's a CSV file, in this exact format, you could read the line, execute string.split(',') and then disregard the first returned string in the array of results. See Evgenly's answer.
Edit: here's the complete program:
class Foo {
static String input = "Name,2,1,3,4,5,10,100";
public static void main(String[] args) {
String[] strings = input.split(",");
int result=0;
for (int i = 1; i < strings.length; i++)
{
result += Integer.parseInt(strings[i]);
}
System.out.println(result);
}
}
(wow, I never wrote a program before that didn't import anything.)
And here's the output:
125
If you're not interesting in parsing the file, but just want to remove the first field; then split it, disregard the first field, and then rejoin the remaining fields.
String[] fields = line.split(',');
StringBuilder sb = new StringBuilder(fields[1]);
for (int i=2; i < fields.length; ++i)
sb.append(',').append(fields[i]);
line = sb.toString();
You could also use a Pattern (regular expression):
line = line.replaceFirst("[^,]*,", "");
Of course, this assumes that the first field contains no commas. If it does, things get more complicated. I assume the commas are escaped somehow.
There are a couple of CsvReader/Writers that might me helpful to you for handling CSV data. Apart from that:
I'm not sure if you are summing up rows? columns? both? in any case create an array of the target sum counters int[] sums(or just one int sum)
Read one row, then process it either using split(a bit heavy, but clear) or by parsing the line into numbers yourself (likely to generate less garbage and work faster).
Add numbers to counters
Continue until end of file
Loading the whole file before starting to process is a not a good idea as you are doing 2 bad things:
Stuffing the file into memory, if it's a large file you'll run out of memory (very bad)
Iterating over the data 2 times instead of one (probably not the end of the world)
Suppose, format of the string is fixed.
String s = "Alice Jones,80,90,100,95,75,85,90,100,90,92";
At first, I would get rid of characters
Matcher matcher = Pattern.compile("(\\d+,)+\\d+").matcher(s);
int sum = 0;
After getting string of integers, separated by a comma, I would split them into array of Strings, parse it into integer value and sum ints:
if (matcher.find()){
for (String ele: matcher.group(0).split(",")){
sum+= Integer.parseInt(ele);
}
}
System.out.println(sum);

Categories