Converting A String to a Boolean -- Java - java

I've been searching around stackoverflow, and I've found a few other questions on converting a string to a boolean, but I can't make it work. Perhaps it is just the way I am trying to use it is incorrect.
Anyways, I am trying to convert two different input strings "M" or "I" in to boolean for use in an if statement. What is basically want the functionality to be is this:
// the text that is retrieved is assumed to be either"M" or "I"
M=Input.getText
I=Input.getText
If M shows the value "M",
do stuff here
else if I shows the value "I",
do stuff here
else if neither above are true,
throw an exception here
I've tried any number of "toBoolean"s and "Boolean.valueof"s, but none of what I try is working.
PS, Sorry for not having actual code to work with, this is my first step, and thus I haven't built anything up around this piece.

You can use String's methods to check for whether it contains a given literal value, equals it, or equals ignoring case.
A draft condition would be:
if ("myValue".equalsIgnoreCase(myText)) {
// TODO
}
else if ("myOtherValue".equalsIgnoreCase(myOtherText)) {
// TODO
}
else {
// TODO
}
Here is the documentation in java.lang.String:
equals
equalsIgnorecase
contains
You also want to check the many other methods, such as startsWith, endswith, etc. etc.

Use this for one boolean:
boolean b = (M.equals("M") || I.equals("I"));
Or this for two boolean:
boolean booleanM = (M.equals("M"));
boolean booleanI = (I.equals("I"));
if(booleanM){
//do stuff here
}else if(booleanI){
//do stuff here
}else{
//do stuff here where both are false
}
This is the faster way if you need to verify more than one time, only one time use this:
if(M.equals("M")){
//do stuff here
}else if(I.equals("I")){
//do stuff here
}else{
//do stuff here where both are false
}

You can simply use boolean b = Input.getText().equalsIgnoreCase("YourTrueString"). This method will detect if the input text is exactly the same as "YourTrueString". If not, it'll return false. This way anything that isn't true becomes false.

From your pseudo code
// the text that is retrieved is assumed to be either"M" or "I"
M=Input.getText
I=Input.getText
If M shows the value "M",
do stuff here
else if I shows the value "I",
do stuff here
else if neither above are true,
throw an exception here
To Java
// In its own method for reuse, in case you want to extend character support
public boolean match(String character, String match) {
return character.equals(match);
}
You can then invoke this simple method
String m = Input.getText();
String i = Input.getText();
if (match(m, "M")) {
do stuff here
} else if (match(i, "I")) {
do stuff here
} else {
throw an exception here
}

Related

How to catch Boolean returned value of a method from another method and do some operations?

I have two methods in the same class.
public Boolean pinValidation(Obj 1, Obj 2){
// Here i have to return Boolean true or false
boolean status = false;
/..... Some Code segments goes here ..
return true;
}
public Payment checkPayment(Obj 1, Obj2){
pinValidation();
// Here if the return value of first method true
if(status == true){
//set of instructions
}
}
What i want to how to catch above return boolean values and do the operation?
any help?
You could do something like:
boolean status = pinValidation();
Or you could simplify by using:
if (pinValidation()) {
//set of instructions
}
Note: use boolean everywhere. No need to mix boolean and Boolean.
First at all, you need to be aware on how to manage conditionals, so let me add some of code about conditionals:
if (true) { //if the condition is true, the code below will be executed
// code to execute here
}
Then you don't need to evaluate someBooleanValue == true simply you need to call it.
if (pinValidation()) {
// code to execute here
}
Second, you need to know differences between Boolean that is an Object which will help you with some methods and boolean that is primitive type and saves a lot of memory then you can use what one is better based on your problem.

Void type error on if statement when I add "&&"

I write this:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Float result = 100f;
if (jCheckBox1.isSelected() == true) {
Float one = Float.valueOf(jTextField1.getText());
result = result / one;
} else {}
and it works fine.
But when I add "&& jTextField1.setDragEnabled(true)" in the if statement I get 'void' type error.
Why's that? And what can I do? Thanks.
I assume your code would look like this, with the added check:
if (jCheckBox1.isSelected() == true && jTextField1.setDragEnabled(true) == true) {
Float one = Float.valueOf(jTextField1.getText());
result = result / one;
} else {}
The problem is, that the setDragEnabled()-method probably does not return an object of boolean type, so the second check just doesn't make sence to the compiler.
So, a possible solution might be
Adjust the check (to whatever logic is needed in your case).
Adjust the method setDragEnabled(), so it returns a boolean (i.e true. in
case, when the text field could be set dragable successfully and false otherwise)
Any set method never returns boolean result. Ideally every setter method returns void, which is not allowed type inside if condition in java.

How to check a boolean method return value in java

I am pretty new to Java what I am trying to do may seem really strange but it is a matter of me understanding a little bit about how Java works more than actually accomplishing a set result.
If I have a boolean method for instance:
public class doThings
{
// imagine the intial value of this variable is set
// and or modified using getters and setters between the declaration
// and the following method
private boolean boolVar;
public boolean doSomething()
{
if(boolVar == true)
{
//does things and then returns true
return true;
}
else
{
return false;
}
}
}
And I want to call this method in another class like so...
public class testDoThings
{
doThings someObject = new doThings;
public static void main(String[] args)
{
someObject.doSomething()
}
}
How do I check (in the class testDoThings) to see if the method has returned true or returned false and print messages accordingly something like this...
public class testDoThings
{
doThings someObject = new doThings;
public static void main(String[] args)
{
someObject.doSomething()
if (doSomething() returns true) // yes I am aware this is not
//valid
{
// print a statment
}
else if (doSomething() returns false) // yes once again not valid
{
// print a different statement
}
}
}
I am aware that you could put these messages in the class containing the method but if I want different messages depending on where the method is called and what it is a called on then putting things in the original class method is not always going to work.
If I am completely off the track here please let me know, if someone can explain this to me though, that would be great!
You can try like this:
if (someObject.doSomething()) //So if your function returns true then the below statement will be executed
{
// print a statment
}
else //This will check for the false condition of your function
{
// print a different statement
}
You can try something like this:
if(someObject.doSomething()){
System.out.print("foo1");
}
else{
System.out.print("foo2");
}
Here's one way:
if(someObject.doSomething() == true){
System.out.print("foo1");
}
else{
System.out.print("foo2");
}
Generally you compare two things using == operator: if (x == y) ... so we have:
if ( someObject.doSomething() == true ) {
//statements
} else {
//statement for the case where result of method call is false
}
BTW instead of if(x == true) you can simply write if(x).
Conditional structures like if, while, do..., etc receive a boolean value, so it isn't necessary to put "boolVar == true". Just doing "if (boolVar)" is enough. As for your example in the doSomething method, just doing "return boolVar;" would do the work, without the need of any ifs, unless you pretend to do some more things on it.
To check a function return value works in the same way. I mean, variables have a value and functions also, the only difference is that variables hold a value while functions calculate or generate a value. So, in your code:
public class testDoThings {
public void check() {
doThings someObject = new doThings();
boolean flag = sameObject.doSomething();
if (flag) {
// print a statment
} else {
//If you want to check falsehood, !flag would do.
// Notice the "!" sign before
// the flag variable?
// It is a NOT sign, so
// NOT true = false
// NOT false = true
// The if will execute its code
// When the result value is true
// So when the function return val is
// false.
// print a different statement
}
}
}
I hope this explanation is enough clear.

How to write (if, if, if) else if none

I'm trying to make a group of if statements, in which each if will print given some argument is true, but an else that will only print if none of the ifs were returned. I don't think an else if would work in this case.
I have some code (the colors are just as examples):
boolean any=false;
if(redStage==2)
{ any=true; System.out.print(redComplete); }
if(blueStage==2)
{ any=true; System.out.print(blueComplete); }
if(greenStage==2)
{ any=true; System.out.print(greenComplete); }
if(any==false)
System.out.print(noneComplete);
Is there anything I can do to eliminate the need for a separate boolean to check whether any of the if's arguments were true?
Edit:
(I just noticed what may be confusing. The code im using isn't actually using return. Instead, it is printing out the results, which means more than one thing can be returned.)
Since you need to processes the stages independently from one another, and more than one can be complete at the same time, your code is as good as it can be.
What follows is my answer to your original question:
You don't need the boolean. Your code is equivalent to:
if (redStage == 2) { return redComplete; }
if (blueStage == 2) { return blueComplete; }
if (greenStage == 2) { return greenComplete; }
return noneComplete;
This makes use of the fact that each if body contains an unconditional return. If this wasn't the case, you could phrase the construct like so:
if (redStage == 2) {
// redComplete
} else if (blueStage == 2) {
// blueComplete
} else if (greenStage == 2) {
// greenComplete
} else {
// noneComplete
}

How Do You Make A Recursive Boolean Method Of "isSubstring(str1, str2)"

if (isSubstring(str1, str2))
System.out.println(str1 + " is a substring of " + str2 + ".")
and here is the method for isSubstring:
public static boolean isSubstring(String str, String target)
{
if (str == target)
return true;
return (isSubstring(str, target.substring(0,5)));
}
That is what I have in code right now and I can't fathom how you would go about solving this. My instructor is requiring us to use recursion so the return MUST call itself. Normally this problem could EASILY be done with only one line of code:
public static boolean isSubstring(String str, String target)
{
return str.contains(target)
}
But I must pointlessly use recursion to solve this and it is EXTREMELY frustrating knowing how trivial this method is and how overly complicated my instructor is forcing us to do this. I don't really know where to start because "return str.contains(target)" doesn't give me a good foundation for how I could try solving this.
A couple things:
First, you have the right idea, but you want to make the 'next' string you search one size smaller than your current string. So if you were looking in the string Hamburger, you'd search amburger second, then mburger. So when you recur, you might try something like return isSubstring(str,target.substring(1)) Right now you appear to be using the number 5 as to take the first 5 characters. That's strange because the first time you do it, (Hamburger to Hambu) you won't ever be able to do it again. And if your original target was "ham" then you'd bomb immediately! Not so good.
Second, it's not enough to test if it's equal. Using the hamburger example, if you were looking for urge, you'd find urger and then go right to rger. You wouldn't ever get urge. So instead of testing for equals, test with beginsWith() instead. (If you were shrinking it from the back, like Hamburger to Hamburge to Hamburg, then you'd use endsWith().)
Lastly, you don't have a good path for what to do if you don't reach the goal. If you have xyzzy for a target, and you're searching for bob, you won't find it. So you need a "base case", which I recommend using as the first line. Something that says "if it would be impossible for the token to be in the target, then let's return false right away".
It's hard and its frustrating, and it seems pointless. But keep in mind he's not trying to teach you to search strings. That's silly, you know how to search strings! He's trying to teach you recursion, which is not easy to "get".
One fix is: Use equals() instead of == while comparing String/Objects. == compares reference equality. equals() compares for content equality.
if (str == target)
should be
if (str.equals(target))
Okay I got it, Asad's advice was useful. Here is a working method for isSubstring:
public static boolean isSubstring(String str, String target)
{
if (target.length() == 0)
return false;
if (str.equals(target))
return true;
else
return (isSubstring(str, target.substring(0,target.length()-1)));
}
I'm not sure if the second "if" should be an "else if" instead.
Compare strings with the equals() method: change
if (str == target)
to
if (str.equals(target))
You know that the function applied to:
base case) An empty string, must return false;
base case) A string starting with the once you are looking for, must return true;
rec case) Else remove the first character and check the rest of the string.
Here the code in Java:
public static boolean isSubstring(final String str1, final String str2) {
if ((str1 == null) || (str2 == null) || str1.isEmpty()) {
return false;
} else if (str1.startsWith(str2)) {
return true;
} else {
return isSubstring(str1.substring(1), str2);
}
}
Test:
public static void main(final String[] args) {
System.out.println(isSubstring("hello this is a simple test", "is a"));
}
Output:
true

Categories