There is an example in my textbook for how to sort string arrays, but I am having a hard time understanding the logic of the code. We have the following array:
String[] words = {"so", "in", "very", "every", "do"};
The method itself is as follows:
public static void sortArray(Comparable[] compTab) {
for (int next=1; next < compTab.length; next++) {
Comparable value = compTab[next];
int this;
for (this = next; this > 0 && value.compareTo(compTab[this-1]) < 0; this--) {
compTab[this] = compTab[this-1];
}
compTab[this] = value;
writeArray(next + " run through: ", compTab);
}
}
This last writeArray call results in the following text being printed for first run through: "1. run through: in so very every do"
OK. Like I said, I have some problems with the logic in this code. If we go through the loop for the first time, this is what I see happening:
We have: Comparable value = compTab[1]. This means that value = "in".
We start the inner loop with this = next (which == 1). Thus, Java will only go through the inner loop once. It turns out that for this first run value.compareTo(compTab[this-1]) is indeed less than 0. Thus we have: compTab[1] = compTab[0]. This means that the word that used to be in position [1] is now replaced with the word that used to be in position [0]. Thus, we now have the word "so" in position [1] of the array.
The next step in the method is: compTab[this] = value. This is where I get confused. This tells me that since this = 1, we here get compTab[1] = value. However, earlier in the method we defined value = "in". This tells me that position [1] in the array yet again assumes the word "in".
The way I see this, the final print out should then be:
"1. run through: so in very every do".
In other words, the way I follow the logic of the code, the final print out of the array is just the same as it was before the method was implemented! Clearly there is some part of my logic here which is not correct. For instance - I don't see how the word that used to be in position [1] is now in position [0]. If anyone can help explain this to me, I would be extremely grateful!
The issue is within the following statement:
The next step in the method is: compTab[this] = value. This is where I
get confused. This tells me that since this = 1, we here get
compTab[1] = value. However, earlier in the method we defined value =
"in". This tells me that position [1] in the array yet again assumes
the word "in".
Since you ran through the loop once (see your statement 2), also the this-- was executed once and therefore this==0.
public class A {
static String Array[]={" Hello " , " This " , "is ", "Sorting ", "Example"};
String temp;
public static void main(String[] args)
{
for(int j=0; j<Array.length;j++)
{
for (int i=j+1 ; i<Array.length; i++)
{
if(Array[i].trim().compareToIgnoreCase(Array[j].trim())<0)
{
String temp= Array[j];
Array[j]= Array[i];
Array[i]=temp;
}
}
System.out.print(Array[j]);
}
}
}
Related
I have a 2d array and I'm trying to find the largest string only in the second column of the 2d array, but for some reason it only gives me the first string in the 2nd column even if there is a bigger string. Here's what I have:
class Main{
public static void main(String[] args) {
String[][] data = {
{"Jeep", "Wrangler", "35000"},
{"Honda", "civic", "25000"},
{"Toyota", "Corolla", "22000"}
};
LargestName(data);
}
public static void LargestName(String[][] a){
String largestN = a[0][1];
for(int i = 0; i < a.length; i++){
if(largestN.compareTo(a[i][1])<0){
largestN = a[i][1] + "";
}
}
System.out.println(largestN);
}
}
Again, I'm trying to compare the strings only in the second column of the 2d array but with what I have it only gives me the first string of the 2nd column "Wrangler", even if there is a larger string in the 2nd column. Please help
I cannot see a flaw in the code. So look at the definition of 'largest string': It is possible that the code really returns exactly that value that you chose in the beginning.
This can be easily tested by choosing a different start value.
On top of that you could add more System.out.println, or even better use a debugger to step through your code. This will give you a very good understanding of how the JVM executes your code.
You need to comapre length, compareTo is not good choice, please look what are you trying to do:
System.out.println("Wrangler".compareTo("civic"));
System.out.println("civic".compareTo("Corolla"));
System.out.println("Corolla".compareTo("Wrangler"));
result:
-12 32 -20
I'm working on an exercise for learning Java where I am supposed to write a method to print to the screen all items that come after the word "category:". This is my attempt at it:
public static void main(String[] args) {
String str = "We have a large inventory of things in our warehouse falling in "
+ "the category:apperal and the slightly "
+ "more in demand category:makeup along with the category:furniture and _.";
printCategories(str);
}
public static void printCategories(String passedString) {
int startOfSubstring = passedString.indexOf(":") + 1;
int endOfSubstring = passedString.indexOf(" ", startOfSubstring);
String categories = passedString.substring(startOfSubstring,endOfSubstring);
while(startOfSubstring > 0) {
System.out.println(categories);
startOfSubstring = passedString.indexOf((":") + 1, passedString.indexOf(categories));
System.out.println(startOfSubstring);
System.out.println(categories);
}
}
So the program should print:
apperal
makeup
furniture
My attempt is that the program should print the substring where it finds the starting index as ":" and the ending index as " ". Then it does the same thing again, only except from starting the very beginning of the variable str, this time it starts from the beginning of the last category found.
Once there are no more ":" to be found, the indexOf (part of startOfSubstring) will return -1 and the loop will terminate. However, after printing the first category it keeps returning -1 and terminating before finding the next category.
The two lines:
System.out.println(startOfSubstring);
System.out.println(categories);
Confirm that it is returning -1 after printing the first category, and the last line confirms that the categories variable is still defined as "apperal". If I comment out the line:
startOfSubstring = passedString.indexOf((":") + 1, passedString.indexOf(categories));
It returns the startOfSubstring as 77. So it is something to do with that line and attempting to change the start of search position in the indexOf method that is causing it to return -1 prematurely, but I cannot figure out why this is happening. I've spent the last few hours trying to figure it out...
Please help :(
There are a couple of issues with the program:
You're searching passedString for (":") + 1 which is the string ":1", probably not what you want.
You should evaluate endOfSubstring and categories inside the loop.
This is probably close to what you want:
public static void printCategories(String passedString) {
int startOfSubstring = passedString.indexOf(":") + 1;
while(startOfSubstring > 0) {
int endOfSubstring = passedString.indexOf(" ", startOfSubstring);
// If "category:whatever" can appear at the end of the string
// without a space, adjust endOfSubstring here.
String categories = passedString.substring(startOfSubstring, endOfSubstring);
// Do something with categories here, maybe print it?
// Find next ":" starting with end of category string.
startOfSubstring = passedString.indexOf(":", endOfSubstring) + 1;
}
}
I have corrected (in a comment) where you set the new value of startOfSubstring
while(startOfSubstring > 0) { // better if you do startOfSubstring != -1 IMO
System.out.println(categories);
// this should be startOfSubstring = passedString.indexOf(":", startOfSubstring +1);
startOfSubstring = passedString.indexOf((":") + 1, passedString.indexOf(categories));
System.out.println(startOfSubstring);
System.out.println(categories);
}
I am stuck on a problem for a very long time which requires me to compute a terms x terms matrix. So, I have 2 arrays which is keywords and sentences as below:
String[] Keywords = {"Human", "Machine", "Interface", "Application" };
String[] Sentence = {"Human is Machine", "Interface of Robot", "Application on Human"};
Next, I have to tabulate them as shown in the figure below.
Logic:
We put a 0 if the row and column is of the same keyword.
In Human(row) x Machine(column) space, we put 1 because these two
words appear in the same sentence once (that is the first sentence
in the array).
In Human(row) x Interface(column), we put 0 because this two words
doesn't exist together in neither of the sentences.
The search is non case sensitive.
And proceed to the next column and then next row.
This is what I've attempted but somehow something is wrong.
public class Test {
public static int [][] matrix;
public static void main(String[] args) throws Exception {
String[] Keywords = {"Human", "Machine", "Interface", "Application" };
String[] Sentence = {"Human is Machine", "Interface of Robot", "Application on Human"};
int [][] matrix = new int[Keywords.length][Keywords.length]; //initialize matrix
System.out.println(Arrays.toString(Keywords));
System.out.println("\n"+ Arrays.toString(Sentence));
for (int i=0;i<Keywords.length;i++)
{
int count = 0;
for (int q=1;q<Sentence.length;q++)
{
if (Keywords[i].contains(Sentence[q]))
{
matrix[i][q] = count++;
}
}
}
System.out.println(Arrays.deepToString(matrix));
}
}
Any help is appreciated. Thanks!
There are some logical errors in your forloop.
With if (Keywords[i].contains(Sentence[q])) you are checking whether the keyword contains the sentence and not whether the opposite holds.
Another thing is that your matrix is based on the Keywords yet you are using the Sentence iterator to indicate the line.
Correct code would be
for (int i=0;i<Keywords.length-1;i++){
for(int j = i+1; j < Keywords.length; j++){
int count = 0;
for (int q=0;q<Sentence.length;q++){
if(Sentence[q].contains(Keywords[i]) && Sentence[q].contains(Keywords[j])){
count++;
}
}
matrix[i][j] = count;
matrix[j][i] = count;
}
}
This will output your example matrix.
There are several mistakes to your program:
if (Keywords[i].contains(Sentence[q]))
this condition checks whether a sentence is contained in a keyword. You want to check the opposite.
matrix[i][q] = count++;
Why do you use this? You want to set the value of the cell to 1, if you find a match. Simply set the value to 1 instead of using a complicated expression that doesn't even work:
matrix[i][q] = 1;
In general:
Whatever IDE you use should provide a debugger. Learn to use it; there's no way to avoid this anyways, if you want to write working code on a larger scale.
for(int j = 1;j<fileArray.size();j++) {
if(str.contains(fileArray.get(end+j))) {
}
}
(assume end is some number such as 30).
The goal of this part is when having a window length of 30 and a fileArray size > 30, check if theres anything after index 30 that matches whatever is inside the window.
ex: "i like to eat piesss aaaabbbbpiesssbbbb"
starting from the beginning of the string add the first 17 characters to a arraylist called window. then i check the rest of the string starting from right after window to see if there's anything that matches. space doesnt match so you add it to the output. keep checking then you see "piesss" matches. Then i replace the second "piesss" with wherever the first "piesss" occurs.
So right now im using fileArray.get(end+j) to check if there's anything that matches within my string(str) except this doesn't really work. Is there a way I could fix this code segment?
The replacement part of your question is still unclear. As is any reasoning to use an ArrayList. I've written some code that does a 5 character window search for a match after splitting the string you provided. Note how with the 30 and 17 values you gave nothing is ever matched (see commented out code). However with tweaked values some matches can be found.
public static void main(String[] args) {
// 1 2 3
//012345678901234567890123456789012345678 <- shows the index
String test = "i like to eat piesss aaaabbbbpiesssbbbb";
// int first = 17;
// int end = 30;
int first = 20;
int end = 37;
String firstHalf = test.substring(0, first);
String secondHalf = test.substring(first, end);
int matchSize = 5;
for (int i = 0; i + matchSize < secondHalf.length() ; i++)
{
String window = secondHalf.substring(i, i + matchSize);
if ( firstHalf.contains(window) )
{
System.out.println(window);
}
}
System.out.println("Done searching.");
}
Displays:
piess
iesss
Done searching.
If this isn't what you meant PLEASE edit your question to make your needs clear.
Very new to Java: Trying to learn it.
I created an Array and would like to access individual components of the array.
The first issue I am having is how to I print the array as a batch or the whole array as indicated below? For example: on the last value MyValue4 I added a line break so that when the values are printed, the output will look like this: There has to be a better way to do this?
MyValue1
MyValue2
MyValue3
MyValue4
MyValue1
MyValue2
MyValue3
MyValue4
The next thing I need to do is, manipulate or replace a value with something else, example: MyValue with MyValx, when the repeat variable is at a certain number or value.
So when the repeat variable reaches 3 change my value to something else and then change back when it reaches 6.
I am familiar with the Replace method, I am just not sure how to put this all together.
I am having trouble with changing just parts of the array with the while and for loop in the mix.
My Code:
public static String[] MyArray() {
String MyValues[] = { "MyValue1", "MyValue2", "MyValue3", "MyValue4\n" };
return MyValues;
}
public static void main(String[] args) {
int repeat = 0;
while (repeat < 7) {
for (String lines : MyArray()) {
System.out.println(lines);
}
repeat = repeat + 1;
if (repeat == 7) {
break;
}
}
}
Maybe to use for cycle to be shorter:
for (int i = 0; i < 7; i++) {
for (String lines : MyArray()) {
// Changes depended by values.
if (i > 3) {
lines = MyValx;
}
System.out.println(lines); // to have `\n` effect
}
System.out.println();
}
And BTW variables will start in lower case and not end withenter (\n). So use:
String myValues[] = {"MyValue1", "MyValue2", "MyValue3", "MyValue4"};
instead of:
String MyValues[] = { "MyValue1", "MyValue2", "MyValue3", "MyValue4\n" };
and add System.out.println(); after eache inside cycle instead of this:
MyValues[n] = "value";
where n is the position in the array.
You may consider using System.out.println() without any argument for printing an empty line instead of inserting new-line characters in your data.
You already know the for-each loop, but consider a count-controlled loop, such as
for (int i = 0; i < lines.length; i++) {
...
}
There you can use i for accessing your array as well as for deciding for further actions.
Replacing array items based on a number in a string might be a bit trickier. A regular expression will definitely do the job, if you are familiar with that. If not, I can recommend learning this, because it will sure be useful in future situations.
A simpler approach might be using
int a = Integer.parseInt("123"); // returns 123 as integer
but that only works on strings, which contain pure numbers (positive and negative). It won't work with abc123. This will throw an exception.
These are some ideas, you might try out and experiment with. Also use the documentation excessively. ;-)