How to detect polynomials in Java - java

Suppose I have a polynomial -x^2 + 2x - 1 = 0. It is read from a file.
I have the code that analyzes each character of the polynomial.
I want to create an extra step that compacts the polynomial(so the white spaces gets eliminated) so I can check if the string is in fact a polynomial which I can easily do by just checking the last 2 index of the polynomial which is the equal sign and the zero like this: (=0)
Problem is some polynomial length have different lengths which gave me the thought to use an ArrayList. Problem is I cannot declare my ArrayList to be of type Character to store each character in the sequential index of an ArrayList.
public void createEquationNoWhiteSpaces(){
// it cannot be done because there is no ArrayList of characters
textArrayList = new ArrayList<String>();
for(int i = 0; i < text.length(); i++){
// Store the characters of the polynomial in an ArrayList
// because each polynomial has different length
if(text.charAt(i) != ' ')
textArrayList = text.charAt(i);
}
}

If you want to use an array, you can certainly declare an ArrayList<Character>. However, you might want to use a StringBuilder instead of a list for this purpose anyway.

st.replaceAll("\\s","")
removes all whitespace in string st

Related

How to replace first and middle char in string

I need to replace first and middle char in string but without builder and etc, just with replace but idk how to make it.
String char = JOptionPane.showInputDialog(null, "Input string with more than 3 char");
if (char.length() < 3) {
JOptionPane.showMessageDialog(null, "Wrong input");
I just made this code and that is it, idk how to continue.
Example: input - pniut
I tried with smth like char.length / 2 but cant.
You can convert your string to a character array, and then swap the characters at 0 and middle position. Then convert the array back to String. e.g. I hard coded 2 here but like you mentioned in comments, you will need to figure out the character at the middle position.
String str = "input";
int mid = -1;
if(str.length() % 2 == 0) {
str.length() / 2 - 1
} else {
str.length() / 2;
}
char[] arr = str.toCharArray();
char temp = '0';
temp = arr[0];
arr[0] = arr[mid];
arr[mid] = temp;
String.valueOf(arr);
The value of the middle character, you will need to find out, like you said in the comments.
Since String objects are immutable, converting the original String to a char[] via toCharArray(), replace the characters, then making a new String from char[] via the String(char[]) constructor would work as shown below:
char[] c = character.toCharArray();
// Change characters at desired indicies
c[0] = 'p'; // first character
c[character.length()/2] = 'i'; // approximate middle character
String newString = new String(c);
System.out.println(newString); // "pniut"
Simple answer: not possible (for generic cases).
Meaning: all variants of String.replace() work by replacing one thing with another. There is no notion of using an index anywhere. So you can't say "replace index 1 with A" and "index 3 with B".
The simply solution is to push the string into a char[], to then swap/replace individual characters via index.
I'm betting the goal of the lesson is to learn how to use the API. So would start here Java API. Go to java.lang.String.
I would focus on the .toCharArray() method and the constructor that takes a char[] as an argument. You need to do this because a String is immutable, and cannot be changed. A char[], however can be altered, allowing you to modify the first and middle slots. You can then take your altered array and convert it back into a String.

modify empty characters in a character array

I'm attempting to take in a string from the console of a certain length and set the empty characters in the string to an asterisk.
System.out.println("Enter a string of digits.");
someString = input.next();
if(someString.matches("\\d{0,9}")) {
charArr = someString.toCharArray();
for ( char digit: charArr) {
if(!Character.isDefined(charArr[digit])){
charArr[digit] = '*';
}
}
System.out.printf("Your string is: %s%n", new String(charArr));
This code is throwing an array index out of bounds exception and I'm not sure why.
for ( char digit: charArr) will iterate over each character from charArr.
Thus, digit contains a character value from charArr.
When you access the element from charArr by writing charArr[digit], you are converting digit from datatype char to int value.
For example, you have charArr = new char[]{'a','b','c'}.
charArr['a'] is equivalent to charArr[97] but charArr has size of length 3 only.
Thus, charArr cannot access the element outsize of its size and throws ArrayIndexOutOfBoundsException.
Solution: loop through the array index wise rather than element wise.
for(int i = 0; i < charArr.length; i++) {
// access using charArr[i] instead of charArr[digit]
...
}
Think you could do it in one line with:
newString = someString.replaceAll("\\s", "*");
"\s" is the regex pattern for a whitespace character.
I think you're mixing your for blocks. In your example, you're going over every character in your someString.toCharArray() so you can't do !Character.isDefined(charArr[digit]) because digit is a char, not an int. You can't take the index of an array with a char.
If you're checking purely if a character is a space, you can simply do one of the following:
if (digit != ' ')
if (!Character.isWhiteSpace(digit)
if (Character.isDigit(digit))
This loop statement:
for (char digit: charArr) {
iterates the values in the array. The values have type char and can be anything from 0 to 65535. However, this statement
if (!Character.isDefined(charArr[digit])) {
uses digit as an index for the array. For that to "work" (i.e. not throw an exception), the value needs to be in the range 0 to charArr.length - 1. Clearly, for the input string you are using, some of those values are not acceptable as indexes (e.g. value >= charArr.length) and an exception ensues.
But you don't want to fix that by testing value is in the range required. The values of value are not (from a semantic perspective) array indexes anyway. (If you use them as if they are indexes, you will end up missing some positions in the array.)
If you want to index the values in the array, do this:
for (int i = 0; i < charArr.length; i++) {
and then use i as the index.
Even when you have fixed that, there is still a problem with your code ... for some usecases.
If your input is encoded using UTF-8 (for example) it could include Unicode codepoints (characters) that are greater than 65535, and are encoded in the Java string as two consective char values. (A so-called surrogate pair.) If your string contains surrogate pairs, then isDefined(char) is not a valid test. Instead you should be using isDefined(int) and (more importantly) iterating the Unicode codepoints in the string, not the char values.

Splitting an array by 16 characters then putting each of the parts into an array

It's a very simple problem but at the moment my brain is fried from working on other parts of this project so I need help. I have a string of a size of a multiple of 16(example: size 16, 32, 48 etc.) I need to break that string into smaller strings of length 16 and place them into an array of size string.length()/16
For example we'll say my string(appendSourceBinary) is: "1000101101001001"
Here's my non working code:
String[] holding = new String[appendSourceBinary.length()/16];
int counter;
for(int z = 0; z < appendSourceBinary.length(); z++){
holding[z] = appendSourceBinary.substring(z, z+16);
}
There is a regex to do this just using split:
String[] array = appendSourceBinary.split("(?<=\\G.{16})");
The regex splits on points in the string proceeded (asserted using a look behind) by the end of the last match (\G) followed by 16 characters (.{16}). Conveniently, \G is initially set to start of input.
Some test code:
String appendSourceBinary = "A234567890123456B234567890123456C234567890123456";
String[] array = appendSourceBinary.split("(?<=\\G.{16})");
Arrays.stream(array).forEach(System.out::println);
Output:
A234567890123456
B234567890123456
C234567890123456
You could do it in two lines, without a loop, like this:
String appendSourceBinary = "10101010101010101010101010101010";
String[] split = appendSourceBinary.replaceAll("([01]{16})", "$1x").split("x");
I've used a regular expression search and replace to find each group of sixteen characters in the string and to replace them with themselves followed by an x. Then I've split the string on the x, leaving an array containing the groups of 16 characters.
If you add a simple loop to output the results:
for (int i = 0; i < split.length; i++)
System.out.println(split[i]);
you'll find the output is
1010101010101010
1010101010101010
Which is the original 32 char string I used split in two 16 char strings. Any remainder will be returned as the last element of the array. If there are less than 16 chars in the input string they'll be returned as the first and only array entry.

Inserting a char (a to z) in between each character in a word

I am working on a spell checker. I have implemented the hash table which takes in the word list, but now I have to write five techniques that are used to generate possible word suggestions. One of them is
Swapping adjacent characters
Insert a character in between each character
For example:
I have the word "bob"... I wanna be able to insert a char in between (a-z)b (a-z)o (a-z)b(a-z) to see if I can get a new word that could be a possible suggestion for the miss spelled word
This is what I did so far...but doesn't work
public static void main(String[] args) {
String word = "evelina";
char[] wordCharArr = word.toCharArray();
for(int i=0; i < wordCharArr.length ; i++) {
//char temp1 = wordCharArr[i];
for(char j = 'A'; j <= 'Z' ; j++) {
word.substring(j);
}
}
}
What I did was add some code which makes an ArrayList (essentially an unlimited array), and then fills it with all of the possibilities found from switching around one letter. It also prints out each one, but you can remove that.
The only changes I made were:
1.Adding the ArrayList
2.Fixing your outer loop; It is one character short (Bob requires 4 iterations, not 3)
3.Adding in additional sub-string segments to account for the rest of the word.
Elements can be retrieved by words.get(a); where 'a' is a int within the bounds of the Array-list. Don't forget the import statement, import java.util.*;
This would also be more efficient then Jeff's solution, because instead of having to check the entire dictionary, and then remove every single element from the dictionary like suggested below, it would simply have to check the dictionary with all of the ~100 possibilities. Because a dictionary is in alphabetical order, it can be searched very quickly, but removing each entry (nearly 100000 words) would be less efficient.
import java.util.*;
public class spellcheck {
public static void main(String[] args) {
String word = "evelina";
char[] wordCharArr = word.toCharArray();
ArrayList<String> words = new ArrayList<String>();
for(int i=0; i <= wordCharArr.length ; i++) {
for(char j = 'A'; j <= 'Z' ; j++) {
words.add(word.substring(0,i) + j + word.substring(i,wordCharArr.length));
System.out.println(word.substring(0,i) + j + word.substring(i,wordCharArr.length));
}
}
}
}
Your problem is in your for loop. Instead of only looping through every other letter of the word you're checking. You're looping through EVERY letter including the original. The outer for loop should be slightly different.
There is another option, but i'm not sure if it's easier or harder to implement (it sounds easier to me at least). Rather than looping over every character and inserting it into the word, you could build a simple query mechanism like so:
Input: b?ob
So your algorithm would be something like:
1) Start with your entire word list
2) Remove all words that don't start with b
3) You can "ignore" the ?
4) Remove all words that don't have a 'o' in the 3rd position
5) Remove all words that don't have a 'b' in the 4th position
6) Return the results
Then you go through each of the options
Input 2: bo?b
Input 3: bob?

String Manipulation in java

I have one array of strings. I want to get each of string, divide it in to 3 parts (number-string-number), and put each part in another array. At last I want to have 3 arrays which two of them store numbers and one of them stores strings. The number of spaces between numbers and strings are not fixed.
the format of the strings in the first array is:
-2.2052 dalam -2.7300
-3.0511 dan akan -0.1116
It will be great if you help me with a sample code.
Here's the algorithm you could implement :
Create your 3 output arrays. They should all have the same length as the original string array
iterate through your original array.
for each string, find the index of the first space character and the index of the last space character. (look into the javadoc of the String class for methods doing that)
extract the substring before the first space, the substring between the first and last space, and the substring after the last space. The javadoc should help you.
Convert the first and third substring into an int (see the javadoc for Double for how to do it)
store the doubles and the string into the ouput arrays.
You can use indexOf and lastIndexOf to achieve this. Try following:
String arrayWithStringAndNumber[] = new String[2];
arrayWithStringAndNumber[0] = "-2.2052 dalam -2.7300";
arrayWithStringAndNumber[1] = "-3.0511 dan akan -0.1116";
String numArray1[] = new String[2];
String numArray2[] = new String[2];
String strArray[] = new String[2];
String temp;
for (int i = 0; i < arrayWithStringAndNumber.length; i++) {
temp = arrayWithStringAndNumber[i];
numArray1[i]=temp.substring(0,temp.indexOf(" "));
numArray2[i]=temp.substring(temp.lastIndexOf(" ")+1);
strArray[i]=temp.substring(temp.indexOf(" ")+1,temp.lastIndexOf(" "));
}
Make sure all arrays are of same length.
For num arrays use type whatever you want. I think you may need double and then you can easily parse the value to fit in it.
Hope this helps.
You can use indexOf(int ch) and lastIndexOf(int ch) of String object to find the first and last whitespace character and divide the string using these two indexes. You can also trim the middle string part if needed.
So:
String[] input; // given
Double[] firstNumbers = new Double[input.length];
String[] middleParts = new String[input.length];
Double[] secondNumbers = new Double[input.length];
for(int i = 0; i < input.length; i++) {
String line = input[i];
int firstWhitespace = line.indexOf(" ");
int lastWhitespace = line.lastIndexOf(" ");
String firstNumber = line.substring(0, firstWhitespace);
String middlePart = line.substring(firstWhitespace, lastWhitespace+1);
String secondNumber = line.substring(lastWhitespace+1, line.length());
// parse numbers to double, add to an array
firstNumbers[i] = Double.parseDouble(firstNumber);
middleParts[i] = middlePart;
secondNumbers[i] = Double.parseDouble(secondNumber);
}
Usually every programming language has functions for operating on strings data. Common set of functions is
length (or len) - to get length of string
find (or indexOf or somthing like this) - to find position of character of substring
substring (or substr) - to get substring of N characters from postion P
often
left/right - to get substring of N characters from left or right string's side
Trim/leftTrim/rightTrim - to trim from left and/or right string's side all space-characters or given as function parameter character.
Always as you need to operate on strings data, try to read documentation or google. You always will find information at Internet. Good luck!

Categories

Resources