Basically what I need to do is only save the first ten words of a sentence into the Array. I know from my code that all the words will be saved if it is greater than 10, but I only iterate through the loop 10 times so it stops. However, if the sentence has less than 10 words, I need to fill it with an empty string. So I can get it to work if it has 10 or more words. However, I cannot get it to work if there is less than 10 words. Does anyone know of a way to make it work? I have to have an Array size of 10.
String[] tempString = new String[10];
tempString = sentence.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
for(int i = 0; i < tempString.length; i++)
{
System.out.println(tempString[i]);
}
EDIT:
So essentially if I entered the sentence: "one two three four five six seven eight nine ten," it would work. However, if I entered "one, two, three" it would give me an ArrayOutofBoundsException. What I need the other 7 indexes to be filled with is an empty string.
You can use the following :
for(int i = 0; i < 10; i++)
{
if (i < tempString.length)
System.out.println(tempString[i]);
else
System.out.println("");
}
Since you need 10 prints then you iterate 10 times. Each iteration you check that you are still in the splitted string array bound. If not just fill the rest with an empty space as you desire.
do like this
if(tempString.length<10)
tempString = Arrays.copyOf(tempString, 10);
String[] tempString = new String[10];
tempString = sentence.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
The two above lines don't make much sense. The first line creates a new array of length 10 and assigns it to the variable tempString, but the second line says: let's forget about this array, and reasign a new array, containing all the words of the sentence, to the tempString variable.
So you actually need two variable:
String[] result = = new String[10];
String allWords = sentence.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");
// now copy at most 10 elements from allWords to result:
for (int i = 0; i < result.length && i < allWords.length; i++) {
result[i] = allWords[i];
}
// and now initialize the rest of the array with empty strings
for (int i = allWords.length; i < result.length; i++) {
result[i] = "";
}
String[] tempString = Arrays.copyOf(sentence.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+"), 10);
There are 2 ways to achieve this..
Initailize all Strings to empty "" (in a for loop..) before you call the for loop shown in your code.
After looping, if length is less than 10, then set remaining items to ""
if ( tempString.length < 10) ;
int diff = 10 - tempString.length -1;
Loop diff times and add "" each time..
Sorry about the formatting..
Related
I have a task where I need to print words from an array in reverse(the word itself). This is what the task states :
Create an array of words called ‘wordList’ and assign the values ‘Stressed’, ‘Parts’, ‘Straw’, ‘Keep’, ‘Wolf’
Create a string called ‘reversedWord’ and do not assign it a value.
Similar to the above challenge, however, instead of reversing a sentence, reverse the order of the letters
within each string.
a. You will need to create a for-loop to access each word in turn. Immediately within the loop set
‘reversedWord = “”;’
b. Then create another for-loop inside of the first one to iterate backwards through the current
word. Update the value of ‘reversedWord’ on each iteration.
c. Print the reversed word on the screen.
STRETCH CHALLENGE: Handle the word so that it reads properly backwards. (Stressed becomes Dessert)
I don't know wether I'm just not understanding the wording of the task or not, but this is the code I have at the moment:
String[] wordList = {"Stressed", "Parts", "Straw", "Keep", "Wolf"};
String reversedWord;
for (int i = wordList.length; i >= 0; i++) {
reversedWord = "";
for (int j = wordList[i].length() - 1; i >= 0; j--) {
reversedWord += wordList[i].charAt(j);
System.out.println(reversedWord);
}
}
It gives me this error when i run it:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at Main.main(Main.java:22)
Any help explanation would be helpful.
There are a few issues here. In the line
for (int i = wordList.length; i >= 0; i++) {
you are setting i to be the length of the wordList, which is 5. Remember, though, that array indexes start at 0. So the valid indexes of wordList are 0, 1, 2, 3, and 4, but not 5. To fix this, you can just subtract 1 from the length.
for (int i = wordList.length - 1; i >= 0; i++) {
The next problem is that you are increasing i at the end of each loop. Since it seems like you're trying to iterate backwards, you're gonna want to decrease i, not increase it.
for (int i = wordList.length - 1; i >= 0; i--) {
There is a simpler solution using Java's StringBuilder class:
public static void main(String[] args) {
String[] wordList = {"Stressed", "Parts", "Straw", "Keep", "Wolf"};
for (int i = 0; i < wordList.length; i++) {
String word = wordList[i]; // Get the word from array
word = new StringBuilder(word).reverse().toString(); // use StringBuilder to reverse the word
wordList[i] = word; // put word back in the array
}
System.out.println(Arrays.asList(wordList));
}
This outputs
[dessertS, straP, wartS, peeK, floW]
UPDATE:
For the words to read properly (first character in uppercase), You could do something like this:
word = word.toLowerCase();
word = word.replace(word.substring(0,1), word.substring(0,1).toUpperCase());
wordList[i] = word; // put word back in the array
There are more effective ways to do this, but is simpler for you to understand. This obviously outputs:
[Desserts, Strap, Warts, Peek, Flow]
substring(0,1) returns the first character (substring from index 0 to index 1; where the last index is not inclusive) as a String. Then, you are replacing the same substring with the uppercase substring.
So I'm trying to make a program that checks an Array(Array2) to see if it contains numbers from another Array(Array1), and groups them along with the numbers or letters that it's connected with. With the data I put below, I was hoping for it to return something like (14T,6in,4s,3aegr,2o,1ESTfhlmpx), instead it returns 14T,6i,4s,3a,2o,1e. It seems like it's not wanting to iterate all of the other letters and numbers in the array. I tried putting it into a string instead of changing the array to add the numbers which have it, and it showed that the for loop iterated through all of the letters/numbers, but it just won't add it to the array. I've been stuck on this for multiple hours now, and was just curious if someone could help me out with this. 😓
Array1[0] = "14";
Array1[1] = "6";
Array1[2] = "4";
Array1[3] = "3";
Array1[4] = "2";
Array1[5] = "1";
String[] Array2 = new String[18];
Array2[0] = "E1";
Array2[1] = "S1";
Array2[2] = "T14";
Array2[3] = "a3";
Array2[4] = "e3";
Array2[5] = "f1";
Array2[6] = "g3";
Array2[7] = "h1";
Array2[8] = "i6";
Array2[9] = "l1";
Array2[10] = "m1";
Array2[11] = "n6";
Array2[12] = "o2";
Array2[13] = "p1";
Array2[14] = "r3";
Array2[15] = "s4";
Array2[16] = "t4";
Array2[17] = "x1";
for(int a = 0; a < Array1.length; a++){
for(int x = 0; x < Array2.length; x++){
String checkers = Array2[x].substring(1);
// ^^ Gets the letter after exp.
if(checkers.equals(Array1[a])){
Array1[a] += Array2[x].substring(0,1);
}
else{
}
}
}
System.out.println(Arrays.toString(Array1));
}
}
This comparison checkers.equals(Array1[a]) will not be true after the first appending to Array1[a]. To resolve this, it's beter to provide a temporary variable before the nested loop String num = Array1[a]; and compare to this variable:
for (int a = 0; a < Array1.length; a++) {
String num = Array1[a];
for (int x = 0; x < Array2.length; x++) {
String checkers = Array2[x].substring(1);
if (num.equals(checkers)) {
Array1[a] += Array2[x].substring(0,1);
}
}
}
System.out.println(Arrays.toString(Array1));
Output:
[14T, 6in, 4st, 3aegr, 2o, 1ESfhlmpx]
This is because by the time you run if(checkers.equals(Array1[a])) to update Array1[a] a second time (like in the case for "6"), Array1[a] has already been updated with one of its letters (so for "6", Array1[a] becomes "6i"), and although checkers may equal "6", Array[1] now equals "6i". This is what stands in the way of continuously updating Array1[a]. To get around this, you can create a third array Array3 that has all the initial values of Array1. This third array will be used in comparison to checkers.
Replace if(checkers.equals(Array1[a])) with:
if(Array3[a].equals(checkers)).
First of all, never use captial letters for your objects. These should only be used for class definitions.
Now to the case. Use regex and create a dictionary of arrays of the second array. The keys will be the numbers and the values will be the letters connected to those numbers. After that you can write out this info however you want:
import re
match_dict = {}
# Construct the match dict
for letter_digit in array2:
# Use regex for string matching
match_obj = re.match( r'([a-zA-Z]+)([0-9]+)', letter_digit, re.M|re.I)
letter = match_obj.group(1)
digit = match_obj.group(2)
if digit in match_dict:
match_dict[digit].append(letter)
else:
match_dict[digit] = [letter]
# Get only letters that match with array1
array1_matches = {}
for digit in array1:
if digit in match_dict:
array1_matches[digit] = match_dict[digit]
else:
# No idea what you want to do if there's no match
array1_matches[digit] = None
# Print everything
for key, value in array1_matches.items():
if value is not None:
print(key, end='')
for letter in value:
print(letter, end='')
print(",", end='')
I haven't tested the code myself, but it should do what you're after.
This is my assignment. I am not allowed to use if statements.
Write a program NumStrings.java that receives two strings through the command line as
input and then prints out the number of times the second string occurs as a substring in the
first.
My bad code:
public class Test {
public static void main(String[] args) {
String a = "HelloHelloHelloHello";
String b = "Hello";
int times = 0;
for(int i=0; i <= a.length()-5; i++){
for (int z=4; z<=(a.length()-1) && a.compareTo(b)==0; z++){
times = times +1;
}
}
System.out.print(times);
}
}
Here is the correct way to do it, using subString() (documentation here: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)):
String a = "HelloHelloHelloHello";
String b = "Hello";
int times = 0;
for (int i = 0; i <= a.length() - b.length(); i++) {
String substring = a.subString(i, i + b.length());
if (substring.equals(b)) {
times = times + 1;
}
}
System.out.println(times);
And here is a way to do it without if statements... Which I don't recommend. But if you have to do it that way, this will work.
String a = "HelloHelloHelloHello";
String b = "Hello";
int times = 0;
for (int i = 0; i <= a.length() - b.length(); i++) {
String substring = a.substring(i, i + b.length());
for (int j = 0; substring.equals(b) && j < 1; j++) {
times = times + 1;
}
}
System.out.println(times);
Look at it this way: you don't have to count how often you find the second string in the first String, because you always have to check if you found it or not. So, to avoid all sorts of conditions or if statements, consider using firstString.split(secondString).
split(someString) will return you an array of remaining substrings once you "split" the base string everytime it finds your substring:
String first = "bababa";
String second = "a";
String[] substrings = first.split(second);
now substrings will look like this: ["b", "b", b"] because every a has been removed and the rest put in separate Strings.
Next you have to check the size of the array and you'll see how often your first String was split.
int count = substrings.length; // 3
However, this is not the end of it because we still have the following case:
String first = "bababaa";
With the above solution you would get an array of size 3: ["b", "b", "b"]. The last occurrence of a will only be removed without leaving any substring behind (not even an empty one '').
So you can take advantage of another (slightly different) split():
first.split(second, limit);
Where limit is the maximum number of occurrences the method tries to find. So how often can you find your second string in the first one? As many letters the first string has: int limit = first.length
first.split(second, first.length); // will produce [b, b, b, , ]
Can you see what happens? there are two empty strings at the end where there where two a. You get an array of substrings for everything that is found before or after the occurrence of the second String.
Naturally, when you split the string ba you would get ["b", ] so 2 substrings. But you don't care about the b just the "commas" in the middle (for every a a ,).
first.split(second, first.length).length -1; // that's how many commas there are, and thats how many second strings there are
EDIT
(thanks #saka1029 !) So, the "split" method still misses something when first="aaa" and second="aa" because it counts only 1 not 2 occurrences.
To correct that I thought of looping through the whole first string and checking only for the very first occurrence, and then removing the first letter and continuing (since OP already accepted another answer, I just post my code):
String first = "ZZZ";
String second = "ZZ";
int counter = 0; // counts the number of occurrences
int n = first.length(); // needs to be fixed, because we'll change the length of the first string in the loop
for(int i = 0; i < n; i++){ // check the first string letter by letter
String[] split = first.split(second, 2); // we want one substring and the rest (2 in total) like: ['', 'Z'] when we cut off the first 'ZZ'
counter += split.length - 1; // now add the number of occurrences (which will be either 0 or 1 in our case)
first = first.substring(1); // cut off the first letter of the first string and continue
}
System.out.println("counter = " + counter); // now we should get 3 for 'ZZZ'
I'm not allowed to use methods from any class except String and IO Class
So my code snippet is:
String line = reader.readLine();
while (line != null) {
String[] elements = line.split(",");
// Array could be too big if there are multiple occurances of
// the same number
// Array length + 1 because I can't use the 0 and with a input line of
// 1,2,3 for example would be the length 3 but I would have the
// numbers 0,1,2 in the Array as my index.
String[][] placeholderMatrix = new String[elements.length+1][elements.length+1];
for(int i = 0; i < elements.length-1; i++){
placeholderMatrix[(int)elements[i]][(int)elements[i+1]] = 1;
}
line = reader.readLine();
}
In the File I'm getting are only numbers like that: 1,2,3,4,5,8,7,4
So in my splitted String Array are only Numbers but now if I want to use them as my index for my Matrix(placeholderMatrix)
My problem is in my for loop where I want to use them as my Index I can't use them because it is a String Array. Normally I would use Integer.parseInt but I'm not allowed to :/
Any ideas on how I can implement them as my Index? and any Idea how I can get the perfect length of my Matrix? Because If I get the following numbers: 1,2,2,2,3 My Matrix should only have the numbers:
0 1 2 3
1
2
3
But if I'm using elements.length+1 for the length of my Matrix I would get the numbers 0 1 2 3 4 5
Hope you could understand my problem. Sorry for my bad english and Thanks in advance.
Edit: SO i got another problem with that. If I implement the method(parseInt) of Dici and am using it in the line "placeholderMatrix[parse(elements[i])][parse(elements[i+1])] = 1;" I'm getting the error ArrayOutOfBounce because my defined Array is just the length of my splitted String Array elements. But if I define it with Integer.MAX_VALUE as my length I get a memory error because it is too big. Any ideas?
Edit2: My Task:
I have to take a row of Numbers seperated by ",". (I will split it with the String split method to get only the numbers) Now I have to create a Matrix(2 dimensional Array) and look for the number at the index i of my new String Array and the number at the index i + 1 and have to take the first Number as my column and th second as my row (or vice versa) and implement at that point a 1. Now are my Numbers I will get from 1 to Integer.MAX_VALUE so I would have to create such a big Matrix but this isn't possible because I get the MemoryError.
Error: java.lang.OutOfMemoryError: Requested array size exceeds VM limit
at Test.main(Test.java:29)
To understand what I have to do: http://de.wikipedia.org/wiki/Adjazenzmatrix the image at the right but for numbers from to Integer.MAX_VALUE so my 2D Array has to be defined with the length of Integer.MAX_VALUE?
Edit:
So Dici asked for an example:
My Sequence could be: 1,2,5,4
So my Matrix should be:
Hope this is what you wanted Dici
But the numbers I can get from the sequence are 1 to Integer.MAX_VALUE
For converting strings to integers, you can simply implement your own integer parser, it is not complicated. You can start with this and improve it if needed.
public int parseInt(String s) {
int n = 0;
int pow = 1;
for (int i=s.length() - 1 ; i>=0 ; i--) {
String si = String.valueOf(s.charAt(i);
if (si.matches("[0-9]")) {
n += pow*(s.charAt(i) - '0');
pow *= 10;
} else if (si.matches("+|-") && i == 0)
n *= s.charAt(i) == '+' ? 1 : -1;
else
throw new NumberFormatException();
}
return n;
}
Then, I'll handle the second part of your problem. If Integer.MAX_VALuE is one of your input values, you cannot possibly allocate an Integer.MAX_VALUE x Integer.MAX_VALUE matrix. What you need to do is assign contiguous ids to your input values and record the ids in a map so that you can access easily the index of the matrix corresponding to one node value. Here is an example to get you to understand :
public void someMethod() {
int id = 0;
Map<Integer,Integer> idMap = new HashMap<>();
String[] split = reader.readLine().split(",");
int [] nodes = new int[split.length];
for (int i=0 ; i<nodes.length ; i++) {
nodes[i] = parseInt(split[i]);
if (!idMap.containsKey(nodes[i]))
idMap.put(nodes[i],id++);
}
// the map is now constructed, it should probably be stored in an attribute
int[][] placeholderMatrix = new int[nodes.length][nodes.length];
for(int i = 0; i < nodes.length; i++){
if (i > 0) placeholderMatrix[idMap.get(nodes[i])][idMap.get(nodes[i-1])] = 1;
if (i < nodes.length-1) placeholderMatrix[idMap.get(nodes[i])][idMap.get(nodes[i+1])] = 1;
}
}
There are other ways to do it, let me know if this solution is ok
You could do something like:
String keyword = "1,2,3,4,5,8,7,4";//input line from file
String replacedKeyword = keyword.replaceAll("[^\\d]", "");//except numbers replace all. Assuming one digit numbers only.
String[][] placeholderMatrix = new String[replacedKeyword.length()+1][replacedKeyword.length()+1];
char keys[] = replacedKeyword.toCharArray();
for (int i = 0; i<keys.length - 1; i++) {
placeholderMatrix[keys[i] - '0'][keys[i + 1] -'0'] = "1";
}
I couldn't really understand what you want exactly. but, if that going to help a simple method to convert String number to int:
int toInt(String number) {
int num = 0;
for (int i=0; i<number.length(); i++) {
num = num*10 + (number.charAt(i)-'0');
}
return num;
}
Hi i got the following code which i use to get some integers from a string. I am separating successfully the negative and positive integers by combining the string with the next number if the char at the index is "-" and i can put the numbers in an integer array...
//degree is the String i parse
String together="";
int[] info=new int[degree.length()];
int counter=0;
for (int i1 = 0; i1 < degree.length(); i1++) {
if (Character.isSpace(degree.charAt(i1))==false){
if (Character.toString(degree.charAt(i1)).equalsIgnoreCase("-")){
together="-";
i1++;
}
together = together + Character.toString(degree.charAt(i1));
info[counter]=Integer.parseInt(together);
}
else if (Character.isSpace(degree.charAt(i1))==true){
together ="";
counter++;
}
But i go this strange problem....the string looks exactly like "4 -4 90 70 40 20 0 -12" and the code parses and puts the integers into the array only to the "0" number i mean i get all the number negatives and positives into my array except the last "-12" number... any ideas?
I think there's a much simpler solution to your problem:
// First split the input String into an array,
// each element containing a String to be parse as an int
String[] intsToParse = degree.split(" ");
int[] info = new int[intsToParse.length];
// Now just parse each part in turn
for (int i = 0; i < info.length; i++)
{
info[i] = Integer.parseInt(intsToParse[i]);
}