Im doing a Java course and in one exercise I have to create three ArrayLists, ask the user to fill the first two with Integers, and then compare both ArrayLists.
The values that donĀ“t repeat are added to the third ArrayList. I already declared the ArrayLists, used Scanner to allow the user to fill the ArrayLists, and that part works.
The problem comes when I try to compare both ArrayLists. I get all sort of alerts in this line ("the if statement is redundant", "Integer values compared using == or !=","Flip operands of the binary operator", "Invert if").
I suspect that what I wrote after the if statement is not very clean, and that I could get some comments about that (Im not an expert in Java), but I do not understand the alerts that the IDE displays. The code compiles and runs just fine until it hits the nested loops. Please help! Thanks.
//Checking for values that dont repeat
for(int i=0;i<listVector1.size();i++){
for(int j=0;j<listVector2.size();i++){
if(listVector1.get(i)==listVector2.get(j)){//Im getting an alert here
repeats=true; //this boolean was previously declared
} else {
repeats=false;
}
if(repeats==false){
int newValue=listVector1.get(i);
listVector3.add(newValue);
}
}
}
First of all, you have a mistake in the second for loop. I expect you want increment j.
Second is comparing you must explicit cast your values from the array or use function equals.
Third your if statement must be out of your second loop. Because I expect you want to add number in third array only one time as it you find.
for(int i = 0; i < listVector1.size(); i++) {
for(int j = 0; j < listVector2.size(); j++) {
if (listVector1.get(i).equals(listVector2.get(j))) {
repeats = true;
break;
} else {
repeats = false;
}
}
if(!repeats){
int newValue=listVector1.get(i);
listVector3.add(newValue);
}
}
This is the real problem here.
Integer values compared using == or !=
The == operator compares the two object's reference. But what you actually want to do is compare the values stored in the reference.
So, you need to use the equals operator.
Or you could explicitly cast one of the values to int and use == on the values like
if(listVector1.get(i) == ((int)listVector2.get(j))){
repeats=true;
} else {
repeats=false;
}
For more reading, you'd google difference between == and equals operator.
Related
So i am using string.split because i need to take certain parts of a string and then print the first part. The part size may vary so I can't use substring or a math formula. I am attempting to store everything I need in the string array to then selectively print what I need based on the position, this much I can control. However, I am not sure what to do because I know when I do a split, it takes the two parts and stores them in the array. However, there is one case where I need that value in the array untouched. I'm afraid if I do
format[0] = rename
That it will overwrite that value and mess up the entire array. My question is how do I assign a position to this value when I don't know what the position of the others will be? Do I need to preemptively assign it a value or give it the last possible value in the array? I have attached a segment of the code that deals with my question. The only thing I can add is that this is in a bigger loop and rename's value changes every iteration. Don't pay to much attention to the comments, those are more of reminders for me as to what to do rather than what the code is suppose to do. Any pointers, tips, help is greatly appreciated.
String format[];
rename = workbook.getSheet(sheet).getCell(column,row).getContents();
for(int i = 0; i < rename.length(); i++) {
//may need to add[i] so it has somewhere to go and store
if(rename.charAt(i) == '/') {
format = rename.split("/");
}
else if(rename.charAt(i) == '.') {
if(rename.charAt(0) == 0) {
//just put that value in the array
format = rename;
} else {
//round it to the tenths place and then put it into the array
format = rename.split("\\.");
}
} else if(rename.charAt(i) == '%') {
//space between number and percentage
format = rename.split(" ");
}
}
Whenever you assign a variable it gets overwritten
format[0] = rename
Will overwrite the first index of this array of Strings.
In your example, the 'format' array is being overwritten with each iteration of the for loop. After the loop has been completed 'format' will contain only the values for the most recent split.
I would suggest looking into using an ArrayList, they are much easier to manage than a traditional array and you can simply just iterate through the split values and append them at the end.
I am trying to overwrite the compareTo in Java such that it works as follows. There will be two string arrays containing k strings each. The compareTo method will go through the words in order, comparing the kth element of each array. The arrays will then be sorted thusly. The code I have currently is as follows, but it does not work properly.
I need a return statement outside the for-loop. I'm not sure what this return statement should return, since one of the for-loop return statements will always be reached.
Also, am I using continue correctly here?
public int compareTo(WordNgram wg) {
for (int k = 0; k < (this.myWords).length; k++) {
String temp1 = (this.myWords)[k];
String temp2 = (wg.myWords)[k];
int last = temp1.compareTo(temp2);
if (last == 0) {
continue;
} else {
return last;
}
}
}
You want to compare the two string at the same location:
int last = temp1.compare(temp2);
Java compiler mandates all the end points must have a return statement. In your case you must return 0 at end so when both arrays contain completely equal strings the caller will know they are equal.
You should start listening to your compiler, because after looking at your code for 1 minute, I spotted two undefined states: this.myWords.length is 0 and the two words are equal.
Also, I personally find it very difficult to handle multiple method exit points with all possibilities for input considered and rather insert a single returning statement which makes debugging easier and the results more predictable. In your case for example, I would collect the results of compareTo in a collection if they differ from 0 so that after the for-loop has finished, you could decide at the state of this collection if 0 (empty collection) or the first value in the collection could be returned. I like this more formal approach, because it enforces you to think set-like as in "Give me all comparing results where compareTo results in anything else but 0. If this list is empty, the comparing result is 0, otherwise it is the first element of the list."
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. ;-)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
(This may be a duplicate, I was not aware of .equals. My apologies.)
I was messing around in Java today when I decided to make a 4 character string generator. I have the program generate every possible combination of characters that I defined. This isn't for a project, I just wanted to see if this was possible. My problem lies with the string checking. I'll post the code first.
String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
char[] chars = text.toCharArray();
String name = "Mike";
String pass;
outerLoop:
for (int a = 0; a < chars.length; a ++) {
for (int b = 26; b < chars.length; b++) {
for (int c = 26; c < chars.length; c++) {
for (int d = 26; d < chars.length; d++) {
pass = chars[a]+""+chars[b]+""+chars[c]+""+chars[d];
System.out.println(pass);
if (pass == name){
System.out.print("password");
break outerLoop;
}
}
}
}
}
The nested if will check if pass is equal to Mike. If it is, then it prints password and will break the for loop.
Is pass = chars[a]... the correct way to do this? When I tested it without the if, I had it print out pass and it printed all of the combinations correctly. It did print Mike, but it did not catch in the if.
I also changed the nested for loops so they start with the lower case because the program was taking a while to run when I made minor changes.
if (pass == name){
should be
if (pass.equals(name)){
use String.equals() method to check string equality. == operator simply checks if two reference variables refer to the same object. equals() method checks if two strings are meaningfully equal.
Strings should be compared using equals()
This comes up at least once per day. There should be a "close question" option dedicated to it. Nevertheless, here goes again...
The == operator tests if the two operands are the same instance.
The .equals() method compares the values of the two operands, but only if the class has implemented this method (which String does), otherwise it behaves the same as == (which is how the Object class implements it).
public static int seqSearch(int numRecords, String[] stuName,
double[] stuGpa, String nameKey, double gpaKey)
for(int i = 0; i < numRecords; i++)
if(stuName[i] == nameKey && stuGpa[i] == gpaKey)
return i;
return -1;
So, how would I used an if statement to control this? I'm doing sequential search to find if the name is found in the array and if the gpa is in the array, then it should return the position it was found in (i). But, all it does do is return -1 and print out that none were found.
You have two separate problems here:
You should be comparing strings using the equals() method (or one of it's kin) - otherwise you are comparing whether two strings are the same reference (instance) rather than equivalent sequences of characters.
You should avoid comparing doubles using == as equality for doubles is more nuanced. Check out this paper for more information about why.
See this question about why using == for floating point comparison is a bad idea in java.
Aside from that, I would also mention that your implementation makes the assumption that both stuName and stuGpa are arrays of the same length. This could easily not be the case ... and is probably something worth asserting before you begin iterating over the arrays.
Strings must be compared with .equals in Java, not ==.
if(stuName[i].equals (nameKey) && stuGpa[i] == gpaKey)
You probably want
if (stuName[i].equals(nameKey) && stuGpa[i].equals(gpaKey))
if(stuName[i] == nameKey is unlikely to be right, you are comparing object identities not string content. Try if(stuName[i].equals(nameKey)
You are comparing two Strings.
Strings are immutable.
Please use "equalsIgnoreCase()" or "equals()" to compare Strings
See examples here
http://www.java-samples.com/showtutorial.php?tutorialid=224
An essential problem is that
stuName[i] == nameKey
Is only comparing whether the objects are the same String Object in memory.
You actually want to use nameKey.equals(stuName[i]), to compare the actual string values.
And you might want to use .equalsIgnoreCase for case insensitivity.
The following is correct for the if statement. stuName[i] is a string so compare with .equals. stuGpa[i] is a double so use ==.
if(stuName[i].equals(nameKey_ && stuGpa[i] == gpaKey)
Your problem is not the conditional if statement, but the conditional operator ==. == refers to the pointer value of the object where as the .equals method returns something computed by the object.
Like everyone has said before, switch your == to .equals in this next line:
public static int seqSearch(int numRecords, String[] stuName,
double[] stuGpa, String nameKey, double gpaKey)
for(int i = 0; i < numRecords; i++)
if(stuName[i].equals(nameKey) && stuGpa[i] == gpaKey)
return i;
return -1;
To actually answer the question about the control of the if statement...
I believe what you're doing is fine with the the multiple return statements, BUT...
I personally prefer one entry point and only one exit point for my methods. It always feels dirty to me having multiple exit points.
So, I would consider the following code instead:
public static int seqSearch(int numRecords, String[] stuName, double[] stuGpa, String nameKey, double gpaKey)
int value = -1;
for(int i = 0; i < numRecords; i++) { // Don't forget your braces, they aren't required, but wait until you add a newline and forget to add them...
if(some.boolean().equals(comparison.here())) {
value = i;
break;
}
}
return value;
}
Best of Luck.