An if inside my If JAVA - java

i'm having a problem about the if inside my if, because it does not read the if inside my if. It does only print the "if and goto detected" once i type for example ("if 1 goto A") then next line ("A:") . Supposedly when the program finds ":" it should print there's a colon but it won't print on mine .Please help me.
public turing() {
String[] input = inputArea.getText().split("\n");
for(int i=0;i<input.length;i++){
if(input[i].startsWith("if")==true && (input[i].contains("goto")==true)){
System.out.print("If and Goto detected");
if(input[i].contains(":")==true){
System.out.print("There's a Colon");
}
}
}
}

You dont't close the if about "if" and "goto" before you open the one about ":", so ":" will only be reported if an "if" or "goto" is present.

You need to use another if because right now the program will only reach System.out.print("There's a Colon"); if if, goto, and : are in the string. This would make your code as follows:
public turing() {
String[] input = inputArea.getText().split("\n");
for(int i=0;i<input.length;i++){
if(input[i].startsWith("if")==true && (input[i].contains("goto")==true)){
System.out.print("If and Goto detected");
}
if(input[i].contains(":")==true){
System.out.print("There's a Colon");
}
}
}

Your input is wrong.
if 1 goto A prints If and Goto detected as it has an if and a goto. It doesn't print the colon part, as there is no colon.
Next your input is A:, it has no if and no goto, so it never passes the first if and will never reach the inner if.
If you enter if 1 goto A: then it will print both outputs.
So either change your input or change your logic. If you want to check for the colon independently, then you have to change the code like this:
public turing() {
String[] input = inputArea.getText().split("\n");
for(int i=0;i<input.length;i++){
if(input[i].startsWith("if") && (input[i].contains("goto"))){
System.out.print("If and Goto detected");
}
if(input[i].contains(":")){
System.out.print("There's a Colon");
}
}
}

code is missing a closing bracket.
if you want the colon to be detected in all case, put the closing bracket after the first println, as in
if (element.startsWith("if") == true
&& (element.contains("goto") == true)) {
System.out.print("If and Goto detected");
}
if (element.contains(":") == true) {
System.out.print("There's a Colon");
}
otherwise, to get the colon only when in the if
if (element.startsWith("if") == true
&& (element.contains("goto") == true)) {
System.out.print("If and Goto detected");
if (element.contains(":") == true) {
System.out.print("There's a Colon");
}
}

Related

Java recursion method returns wrong value

I have a bit of a problem with this recursion method. I'm fairly new to Java.
This method checks if an input is either "exit" only or "start" followed by two times either "user" or "easy".
It works fine except for the return. If I enter a wrong input and then a right on it returns the previous wrong input with which I obviously can't continue working, why is that?
I've had this problem before but always somehow managed to avoid it.
You might notice that I print out a valid commadnd right when it's validated, this works fine and produces the result I need. But when printing out the return of the function on line 2 the above mentioned problem takes place. I've added numbers to the printed strings so I can recognize which is which.
I have tried returning immediately when there's a valid command but I still need that retrun at the end since the function gives me an error if return statements are exclusively in conditional statements so the problem persists.
Thanks for any help!
public static void main(String[] args) {
System.out.println(setup() + "3");
}
static String setup() {
System.out.print("Input command: ");
String command = input.nextLine();
String[] split = command.split(" ");
if(!(command.equals("exit") || split.length == 3)) {
System.out.println("Invalid parameters!");
setup();
}
else {
if(command.equals("exit")) {
System.out.println("Valid parameters! Exit");
System.out.println(command + "2");
}
else if(split[0].equals("start") && (split[1].equals("easy") || (split[1].equals("user")) && split[2].equals("easy") || split[2].equals("user"))) {
System.out.println("Valid parameters! Start");
System.out.println(command + "1");
}
else {
System.out.println("Invalid parameters!");
setup();
}
}
return command;
}
first of all I think that you meant to call the recusive call as
return setup()
second of all when using conditional operator (&&, ||) you should use () for make sure you get the logic condition you expect.
if you will update it to :
return setup instead of setup()
validate what you wrap the right part of condition with Parenthesis():
else if (split[0].equals("start") && ((split[1].equals("easy") || split[1].equals("user")) && (split[2].equals("easy") || split[2].equals("user")))) { System.out.println("Valid parameters! Start"); System.out.println(command + "1"); }

Confused on how to use || and && in the same if statement. Can anyone spot the problem?

I am confused on how to use || and && in the same if statement.
What I am trying to do is have it print something if the string starts with an "D" or an "O", and if one is true check if the string has a character length of two.
Example: if the string is "DE" it will print something. However, if it is "SE" it will not print anything.
else if( (answer.startsWith("D") || answer.startsWith("O"))
&& (answer.length() == 2) ) {
//print something
}
Java is applying a "short circuit" to your logic. It does the first part (starts with "D" or "O") and if that's true it proceeds to the second part (length is 2). However if the first part evaluates to false then it never even bothers to execute the second part.
So your "SE" string will never go into the "print something" bit because it doesn't meet your first criteria of starting with D or O. And based on your description of what the logic should be, that is correct.
If you actually mean that if it starts with "D" or "O" OR is 2 characters long then your logic statement should have been:
else if( answer.startsWith("D") || answer.startsWith("O")
|| (answer.length() == 2 ) {
//print something
}
Edit: Oops, just pasted the original code in the first time...!
I would check first the length and after the two conditions e.g.
else if (answer.lenght()==2) {
if (answer.startsWith("D") || answer.startsWith("O"){
//print something that lenght is 2 and starts with D or O
}
}
}
In that case you have to check length first because && will true if left side and right side both true
else if( (answer.length() == 2)&&(answer.startsWith("D") || answer.startsWith("O"))
{
//your logic
}

Okay, still having trouble with else if method in Java

import java.util.Scanner;
public class SherlockHolmes {
String answer = "Watson";
String response = " ";
int tries = 0;
int tries = 3;
Scanner input = new Scanner(System.in); {
System.out.print("Enter the name of Sherlock's partner, and dear friend.");
response = input.nextLine();
tries++;
if (response.equals("Watson"))
else
while (tries <= 3)
System.out.print("Ooooh, sorry kid! Try again!"); {
System.out.println("Yes, that's right, Barrel Rider.");
break;
} else if (tries == 3) {
System.out.println("Ooooo, sorry kid. But, it looks like you're S.O.L!");
break;
}
}
}
My biggest question is why I'm getting two errors with this method, the error
being: SherlockHolmes.java:16: error: 'else' without 'if'
else
^
SherlockHolmes.java:24: error: 'else' without 'if'
else if(tries == 3)
^
2 errors
I put if code in every line, yet its telling me : "Else without if" for both entries of "else". I am kind of frustrated, and I don't slagging get how Java thinks I have no if when it is clearly there!
What am I doing wrong that Java thinks I have no if code fashioned in?
If you want an if statement with an empty body, you NEED curly braces in Java. Honestly, you should just have way more braces in your code. I strongly suggest reading up on Java coding conventions http://www.oracle.com/technetwork/java/codeconventions-150003.pdf
Example:
if (response.equals("Watson"))
else while (tries <= 3)
For that empty if to compile, you need:
if (response.equals("Watson")) {
}
else while (tries <= 3) {
// loop body
}
You have many syntax errors.
First, you cannot attach an else-if to a while block. Second, if you're trying to make it so that if the response does not equal "Watson", then use the "not equal to" operator, which is simply "!" (an exclamation mark).
Control flow is made up of
if (condition) {} Must be used once, and must be first
else if (condition) {} as many times as you want, optional, must be in between else and if if included
else {} optional, must be last and used once if included
Curly braces and order are mandatory. In Java, it is best practice, and usually required to put curly braces around all blocks: if, while, for. Another thing you need to know is that while loops are not the same as conditionals. They can't be attached to else or else if statements. So your while loop needs to change to
while (tries <= 3) {
...
}
Do this similarly with the conditional statements.
System.out.print("Enter the name of Sherlock's partner, and dear friend.");
response = input.nextLine();
tries++;
while (tries <= 3) {
if (response.equals("Watson")) {
System.out.println("Yes, that's right, Barrel Rider.");
}
else {
System.out.print("Ooooh, sorry kid! Try again!");
break;
}
if (tries == 3) { // If the while loop finishes
System.out.println("Ooooo, sorry kid. But, it looks like you're S.O.L!");
break;
}

Why if-else if-else if Statement in Java doesn't behave like Wiki said?

Here is what i want.
If word.length() > 0 then delete or insert word.
So, we can structure the code like this:
if(word.length()>0){
if(action.equals("insert")){
insert(word);
}
else if(action.equals("delete")){
delete(word);
}
}
However, the above nested if is hard to read, so we can do
if(word.length()>0 && action.equals("insert")){
insert(word);
}
else if(word.length()>0 && action.equals("delete")){
delete(word);
}
However, the above code repeats word.length() 2 times which lead to duplicates & that is not good. So if we try
if(word.length()>0){
System.out.println("ok to insert or delete");
}
else if(action.equals("insert")){
insert(word);
}
else if(action.equals("delete")){
delete(word);
}
however, the above code will do the Insert or Delete even if word.length==0.
That quite confusing, cos in wiki http://en.wikipedia.org/wiki/Conditional_(programming), they said:
"Only the statements following the first condition that is found to
be true will be executed. All other statements will be skipped."
if condition1 then
--statements
elseif condition2 then
-- more statements
elseif condition3 then
-- more statements;
...
else
-- other statements;
end if;
What wiki said mean, if condition1 ==true then do the condition2, but if if condition1 ==false then skip all following conditions (condition2,3,...)
But that does not happen in Java?
I am confused??
It will work rewriting your code like:
if(word.length()==0){
System.out.println("word length is 0");
} else if(action.equals("insert")){
insert(word);
} else if(action.equals("delete")){
delete(word);
}
And it is read as: if word length is 0 it will print "word length is 0" otherwise: if action is equals to "insert" it will invoke method insert otherwise if action is equals to "delete" then invoke delete method.
Each if structure has one statement that is executed if the given condition is true. And only this statement is executed, {} could be used to group more statements (block of code). So it is right to say that in a structure of if-elseif only the statements following the first condition that is found to be true will be executed.
The first condition has one block for the true case and one statement (if structure) for the else case. The same for the second condition, and the 3rd has just a block for the true case. Another way to see the statements separations would be:
if(word.length()==0){
System.out.println("word length is 0");
} else
if(action.equals("insert")){
insert(word);
} else
if(action.equals("delete")){
delete(word);
}
using block for the true and false case you would have something like:
if(word.length()==0){
System.out.println("word length is 0");
} else {
if(action.equals("insert")){
insert(word);
} else {
if(action.equals("delete")){
delete(word);
}
}
}
the result is the same.
You misread the wiki. But if you don't like option 1 (which I think is fine) then make the insert and delete methods look at the word length:
public void insert(String word) {
if( word == null || work.isEmpty() ) return
}
Then you have:
if( "insert".equals(action) ){
insert(word);
}
else if( "delete".equals(action) ){
delete(word)
}
I used "insert".equals(action) instead of action.equals("insert") just in case "action" is null.
The wiki is correct, you just have your conditions backwards.
"however, the above code will do the Insert or Delete even if word.length==0."
Not quite. The code will do the insert or delete only if word.length == 0. If word.length > 0, it will print the message, then the insert and delete blocks will be skipped.
It should probably be:
if(word.length() == 0) //if condition1 is true, we will skip all the other blocks after this one
{
System.out.println("Cannot insert or delete");
}
else if(action.equals("insert")) //okay, condition1 must have been false at this point
{
insert(word);
}
else if(action.equals("delete")) //and condition2 must have been false at this point
{
delete(word);
}
if(word.length()>0){
System.out.println("ok to insert or delete");
}
else if(action.equals("insert")){
insert(word);
}
else if(action.equals("delete")){
delete(word);
}
here you do two diffrent checks thats the problem
first you check the word length and then you check for the action
I think the best way you can do it is like you first did it
if(word.length()>0){
if(action.equals("insert")){
insert(word);
}
else if(action.equals("delete")){
delete(word);
}
}

My if statement ALWAYS returns true, no matter what

This just is't making sense to me at all.
This is my code:
boolean that = false;
if (that == true);
{
System.out.println("That is " + that);
}
And yet it will print the line even though my output is
That is false
I'm doing this in java and I'm using Eclipse galileo, so each time I compile/run my program it saves it so the compiler should be getting updated version of my program.
What's going on?
A common mistake. Remove the ; at the end of the if statement.
BTW I always write the following if I use brackets and I use the code formatter of the IDE.
if (that == true) {
System.out.println("That is " + that);
}
This means if you have a mis-placed ; or { it can be more obvious.
Remove the ;
boolean that = false;
if (that == true)
{
System.out.println("That is " + that);
}
otherwise the print is always executed.
It's because of the semicolon you have here:
if (that == true);
Remove that semicolon ! It causes the code to do nothing after checking the conditional (that == true) - technically it's an "empty statement" - i.e. we can have a loop like so:
for (int i = 0; ; i++){
System.out.println("Thanks" );
}
And it would go forever!
Try it like this:
boolean that = false;
if (that)
{
System.out.println("That is " + that);
}
Notice the extra semi-colon after the if in your code? That's why.
The logical test is closed by the semi-colon, then the next block is always executed.
If you remove the semi-colon it'll match your intuition.
if (that == true);
// ^ The extra colon you dont need

Categories

Resources