Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am trying to get a Save button to enable/disable based on if the EditTexts actually change, but my string comparison is not working at all.
public void afterTextChanged(Editable editable) {
String newSet = editable.toString();
newSet = newSet.trim();
if(!newSet.equals(ip) || !newSet.equals(port) || !newSet.equals(username) || !newSet.equals(password)){
saveButton.setEnabled(true);
}else{
saveButton.setEnabled(false);
}
}
It keeps telling me the strings are different even though they aren't. Even when I print it out I get exactly the same String back.
Can anyone help me?
Thanks
Probably you want && instead of ||:
public void afterTextChanged(Editable editable) {
String newSet = editable.toString().trim();
saveButton.setEnabled(!newSet.equals(ip) &&
!newSet.equals(port) &&
!newSet.equals(username) &&
!newSet.equals(password));
}
enable saveButton if newSet is not a ip, port, username or password
You should write it like that, way easier to read :
if (!Arrays.asList(ip, port, username, password).contains(newSet))
{
saveButton.setEnabled(true);
}
else
{
saveButton.setEnabled(false);
}
Or :
saveButton.setEnabled(!Arrays.asList(ip, port, username, password).contains(newSet));
newSet can't be equal to all four of these Strings, unless all 4 are equal to each other. Therefore the condition will most likely return false.
If you require that newSet be equal to either one of those 4 Strings, the correct condition would be :
if(!(newSet.equals(ip) || newSet.equals(port) || newSet.equals(username) || newSet.equals(password)))
replace || with &&
if(!newSet.equals(ip) && !newSet.equals(port) && !newSet.equals(username) && !newSet.equals(password))
Reason :
OR(||) If any condition get satisfied it will enter inside the loop.
AND(&&) If all conditions get satisfied then and then only it will enter inside the loop.
In your case you need to satisfy all the conditions, that's why use and operator instead of or operator.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
So, I just started to get my hands dirty on Java this week and I found something rather odd. I'll add the code and then walk you through.
import java.util.Scanner;
public class kids
{
public static void main(String[] args)
{
System.out.println("How old are you, doll?");
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
System.out.println("Doggie lover or a cat person?");
String animal = scanner.nextLine();
if(age < 18 && animal.contains("dog")) // 1st comparison
{
System.out.println("Hello cutie, welcome");
}
else if(age < 18 && animal.contains("cat")) // 2nd comparison
{
System.out.println("Oh, hi"); // This statement gets skipped
}
else if(age < 18 && animal.contains("cat")); // 3rd comparison
{
System.out.println("Hiya, Doggie lover!");
}
}
}
I've attached my output here
Output
So, I gave an input "dogcat" to the string animal. It is pretty clear or at least to me that the three comparisons should return TRUE but my output says otherwise. Seems like only the first and the third comparisons return TRUE but clearly if the third comparison returns TRUE since it contains the string "cat" so does the second comparison. Why is Java skipping my comparison here?
For input dogcat, it only executes the first if condition. Since other two conditions are given as else if conditions, they do not get executed.
Confusion happens because of the typo of having an semicolon just after the 3rd if condition. So the typo makes an empty statement for 3rd if condition.
The statements in the last set of curly braces are not a part of 3rd if condition due to the typo.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have this code...
class Test {
public static void main(String[] args) {
Boolean mySuperBoolean = Boolean.FALSE;
System.out.print("a");
if (mySuperBoolean = Boolean.TRUE) {
System.out.print("b");
}
System.out.print("c");
}
}
I am new to Java, but I knew single equal (=) is used to assign. And double equals (==) is used to check if object is referred to the same location in memory. However, in this case I do not understand how the 'b' is being printed with a single equals, but I understand changing it to a double equals sign will not print it out
if (mySuperBoolean = Boolean.TRUE) will assign Boolean.TRUE to your mySuperBoolean variable and the condition will evaluate to true, hence whatever is inside your if it will always execute
The result of the assignment operator = will be the assigned value. So if (mySuperBoolean = Boolean.TRUE) will always evaluate to true.
Assignment is an expression which resolves to whatever was assigned, in this case(mySuperBoolean = Boolean.TRUE) is an expression which resolves to Boolean.TRUE.
This is really only useful in a few specific situations. One such case is the following idiom:
String line;
while ((line = readLine()) != null) {
//...
}
Or even
i = j = k = 0; // equal to: i = (j = (k = 0))
It's a controversial feature because it allows probable bugs such as yours to compile successfully. To mitigate this, some people will invert the operands (a "yoda condition"):
if (Boolean.TRUE == mySuperBoolean)
This works because if I forget the second equals then the compiler will throw an error because Boolean.TRUE is final and cannot be assigned to.
In essence, what happens here boils down to:
if (Boolean.TRUE) {
System.out.print("b");
}
That assignment puts TRUE into the variable, the variable is boolean, and checked for its current value, end of story.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I just came up with a problem returning a Boolean value in accordance with a given condition. I thought in order to check the given condition for full possibilities I need to use for loop. But when I tried to compile it, it gives me error, possibly because there is uncertainty returning a Boolean value using for loop. Here is an original problem:
Return true if the given string contains a "bob" string, but where the middle 'o' char can be any char.
bobThere("abcbob") → true
bobThere("b9b") → true
bobThere("bac") → false
And here is my code:
public boolean bobThere(String str)
{
for(int i=0; i<str.length()-3; i++)
{
if (str.length()>=4): && str.charAt(i)=='b' && str.charAt(i+2)=='b')
{
return true;
}
else
return false;
else if (str.length()==4 && str.charAt(0)=='b' && str.charAt(2)=='b')
{
return true;
}
else
{
return false;
}
}
}
I just wanted to ask :
1. Can I fix the this code for returning a value. I mean, can I use for loop and return specific value for a given condition? If yes, please could you give me a sample.
2. Or are there any ways other than for loop to solve this problem.
Thanks in advance.
The compiler error is almost certainly because you have an elseif after an else. That's invalid.
Looking at your code, what you seem to want to do is loop through the string, and then return true if you're at the start of a b?b string. I'm not sure why you have your second if condition in there - at the moment your code would check the first and third characters of the string on every iteration of the loop, if the string happens to be exactly four characters long. Pointless, it doesn't need to be there. The check for length isn't necessary at all.
Additionally, your end condition for the loop is currently i < string.length()-3. This means that the final three characters of the string will not be checked. You would need to change this to either i <= string.length()-3 or i < string.length()-2 to solve this.
Your else return false stuff is going to give you a serious problem. Your code will enter the loop once, and then either return true or false, without ever going to the next phase of the loop. What you should do is loop through the string, and if you find what you're looking for, return true. Otherwise, don't return at all, and keep going with the loop. If you get to the end of the loop it means you never found what you were looking for, so you can at that point return false.
Taking those comments into account, your revised code would look like this (please note I haven't compiled or run this):
public boolean bobThere(String str)
{
for(int i = 0; i <= str.length() - 3; i++)
{
if (str.charAt(i) == 'b' && str.charAt(i + 2) == 'b')
{
return true;
}
}
return false;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
Error :
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 2
at java.util.LinkedList.checkElementIndex(LinkedList.java:553)
at java.util.LinkedList.get(LinkedList.java:474)
at InterfacePackage.Main.main(Main.java:116)
Java Result: 1
Code (shortened) :
if(input.length() > 0)
{
if(command.size() == 1)
{
switch(command.get(0).toLowerCase())
{
case "exit":
case "qqq":
active = false;
break;
default:
System.out.println("invalid input, for complete list of commands enter 'help'...");
break;
}
}
else if(command.size() > 1)
{
if(command.get(0).equalsIgnoreCase("shutdown") && command.size()==3)
{
Shutdown shutdown = new Shutdown();
shutdown.Start(command);
}
else if(((command.get(0).equalsIgnoreCase("scan")
&& command.get(1).equalsIgnoreCase("ips"))
|| command.get(3).equalsIgnoreCase("/e"))
&& (command.size()>=2 || command.size()<4))
{
SystemsIPs sips = new SystemsIPs();
sips.Start(command);
}
else
{
System.out.println("invalid input, for complete list of commands enter 'help'...");
}
}
}
The error occurs when the users enters two string within a line that doesn't exist in the else if(command.size() > 1) loop.
For example, if the user would enter : hello world the program produces this error.
So this is a program that does various things based on user input to a console. I've been getting this error and and wanting to know what is causing it. I know I can just catch it, but I really want to know what causing this error.
Your error seems to be caused by
command.get(3).equalsIgnoreCase("/e"))
There is no index 3. Check if that index exists first, before you do that.
You're getting an IndexOutOfBoundsException as it says, and it occurs when you're trying to access a position in a collection/array and that position is empty, you're trying to access to an index that doesnt exist. If you don't want that to happen then force the program to use an Collection with a size more than 3 element.
The problem is in this line:
else if(((command.get(0).equalsIgnoreCase("scan") &&
command.get(1).equalsIgnoreCase("ips")) ||
command.get(3).equalsIgnoreCase("/e")) &&
(command.size()>=2 || command.size()<4))
You are using command.get(3) to retrieve the 3rd element of the LinkedList, but it's not guaranteed that there are at least 3 elements in the list.
So you'd better add a condition command.size() >= 3 before command.get(3).
Ok so here is how I solved the problem :
else if((command.get(0).equalsIgnoreCase("scan") && command.get(1).equalsIgnoreCase("ips")) && (command.size()>=2 || command.size()<4))
So I removed the
|| command.get(3).equalsIgnoreCase("/e"))
... from the code entirely, and improved the case in the separate class that this if statement directs to.
Here is what I did in the separate class...
if(command.size()==3 && command.get(2).equalsIgnoreCase("/e")) { }
else if(command.size()==2) { }
And it works (:
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to figure out how to do something like:
int test = 1;
int test1 = 10;
if (value = test (though) test1) {
}
I've looked at oracles java operators but could not figure out how to do it.
The construct should check if value is between test and test1.
Can anybody tell me how to do this in Java?
if (value >= test && value <= test1)
{
//doSomething
}
Java does not support chained inequalities, ie test <= value <= test1, so instead you can just use two boolean expressions, connected via the boolean and operator, to get a logically equivalent conditional.
You should try something like with logical and operator
if (value > test && value < test1) {
// do something
}
or add >= to add equals comparison too.
It looks like you are looking for range operator that is common in a lot of programming languages, Java not being one of them, but the condition that you are trying to impose on the range will always be the same. You don't need to check every value in the range, merely the endpoints since it is contiguous:
if( value > test && value < test1 ) {
// do something
}
There is no through op in Java. You can do it with a simple if :
if (value >= test && value <= test1) {
// your code
}
This post begged to be clarified.
If you are checking that value is between test1 and test2 then you need:
if(value >= test && value <= test1){
// do stuff
}
Note that you should remove the = signs if value should be strictly between test and test1.
However, if you are checking that value is one of multiple tests from test0 "through" test10 for instance, then pack those tests in a set and check if value is among them:
import java.util.*;
Set tests = new HashSet();
tests.add(test);
tests.add(test1); // similarly for as many as you need
if(tests.contains(value)){
// do stuff
}