Java recursion method returns wrong value - java

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"); }

Related

Program Keeps Out Printing Both Messages

I have some code going on here, I'm trying to get the user to input a Letter,
Number, or a Symbol, I have them all working, but when I enter a Letter, it
outprints both the "You have entered a Letter" and "You have entered a
Symbol" But thing is, I never entered a Symbol in the first place, just a
Letter. Heres how it looks:
Enter a SINGLE character:
D
You entered a LETTER!
You entered a SYMBOL!
import static java.lang.System.*;
import java.util.*;
public class Java1304
{
public static void main(String[] args)
{
new Problem();
}
}
class Problem
{
char letter;
public Problem()
{
input();
process();
output();
}
void input()
{
Scanner scan = new Scanner(in);
out.println("Enter a SINGLE character:");
letter = scan.nextLine().charAt(0);
}
void process()
{
if(Character.isLetter(letter))
{
out.println("You entered a LETTER!");
}
if(Character.isDigit(letter))
{
out.println("You entered a NUMBER!");
}
if(!Character.isLetter(letter) || !Character.isDigit(letter))
//else
out.println("You entered a SYMBOL!");
}
void output()
{
out.println();
out.println();
out.println();
}
}
Your desired behavior is not reflected in the code you wrote. The statement !Character.isLetter(letter) || !Character.isDigit(letter) evaluates to true if either the character is not a letter OR not a number (as || is the logical operator for or).
Going back to your example, if you type "A", Character.isDigit(letter) evaluates to false, so !Character.isDigit(letter) evaluates to true, so !Character.isLetter(letter) || !Character.isDigit(letter) evaluates to true.
Based on your example, your if block could be better written as:
if(Character.isLetter(letter)){
out.println("You entered a LETTER!");
} else if(Character.isDigit(letter)){
out.println("You entered a NUMBER!");
} else {
out.println("You entered a SYMBOL!");
}
De Morgan's laws strike again! The || is your culprit. It needs to be && for your case.
Your second if statement is true because !Character.isLetter(letter) is true. The || is a logical or. That means if one of the statements is true it enters the if clause.
So just change the last if for an else and you should be fine.
Your problem is that last if statement- let's step through your use case there:
you enter D.
isLetter('D') is true so it prints
isDigit('D') is false so that doesn't print
!isLetter('D') && !isDigit('D') is the same as
! true || ! false (evaluating the method calls) which is the same as
false || true (evaluating the !'s) which is the same as
true (evaluating the ||) so it prints.
To fix it, you can change your || to &&, or put back the else clause you have commented out. I personally think the else clause is a better solution because it clearly communicates your idea that what's not a letter and not a digit must be a symbol without having to explicitly check for each one.
if(!Character.isLetter(letter) || !Character.isDigit(letter))
You used OR instead of AND, so letter "D" will pass when you check for !Character.isDigit(letter)
In the last if statement, change the || to &&.

JAVA Comparing two Strings isn't working

So here's a snippet of code I'm working on:
String direction = s.readLine();
System.out.println(direction);
if (direction.equals("up") != true && direction.equals("down") != true &&
direction.equals("left") != true && direction.equals("right") &&
direction.equals(null) != true) {
System.out.println("Invalid Solution file");
System.exit(0);
}
What it is supposed to do is read a line from a text file (using a BufferedReader) and then if the line isn't either a valid direction or blank then it should print "Invalid Solution" and exit.
The problem is that no matter what the direction string is the if statement still runs. I put in a println to check whether the direction was being read correctly but it seems absolutely fine. So why isn't the code working as intended?
Part of your problem is readability. Fix that and your problem is 90% solved:
private static List<String> DIRECTIONS = Arrays.asList("up", "down", "left", "right");
then
if (!DIRECTIONS.contains(direction)) {
System.out.println("Invalid Solution file");
System.exit(0);
}
The other 10% was how to check for null, which is direction == null, but if you use this code you don't need to, because contains(null) will conveniently return false.
You code is much more complex than it is needs to.
Consider this instead:
Set<String> validDirections = new HashSet<>(Arrays.asList("up", "down", ...
if (validDirections.contain(direction.toLowerCase()) {
// good ...
} else {
// bad ..
}
You can make validDirections a global constant for example; so it could be used in other places as well.
What I am trying to explain here is: your code is low-level. Low level code is hard to write, read, maintain and extend. Programming is always about creating good abstractions. Or vice versa: if you don't use abstractions, you end up with pretty abstract code, like the one you are showing here!
For example: if you need another direction, you have to put into your already way too complicated if condition. In my solution, you just put it into the statement that builds that Set.
Finally: your error message, is saying nothing. So, that string is bad; but why is it? Wouldn't it be better to at least print the string that caused the error?!
Here && direction.equals("right") I think you have done a mistake since it is on contradiction with the rest :
direction.equals("up") != true &&
direction.equals("down") != true &&
direction.equals("left") != true
You test the negation in the most of conditions but direction.equals("right") tests the affirmation.
Try it , it's the same thing but less verbose and more readable :
if (direction !=null && !direction.equals("up") &&
!direction.equals("down") &&
!direction.equals("left") &&
!direction.equals("right") ){
System.out.println("Invalid Solution file");
System.exit(0);
}
First, you should not use != true with a boolean statement, it is bad form. Rewrite like this:
direction !=null &&
!direction.equals("up") &&
!direction.equals("down") &&
!direction.equals("left") &&
!direction.equals("right")
Your error was that you did not include the != true part on one of your statements within the compound if. Replace with the above code to solve the issue.
I'm confused why you are using !=true when your .equals method already returns a boolean. Try this.
String direction = s.readLine();
System.out.println(direction);
if ( direction!=null && !direction.equals("up") && !direction.equals("down")&& !direction.equals("left")&& direction.equals("right")){
System.out.println("Invalid Solution file");
System.exit(0);
}
Try the following code:
boolean match = false;
if (direction.equals("up"))
{ match = true; }
if (direction.equals("down"))
{ match = true; }
if (direction.equals("left"))
{ match = true; }
if (direction.equals("right"))
{ match = true; }
if (direction.equals(null))
{ match = true; }
if (match == false){
System.out.println("Invalid Solution file");
System.exit(0);
}
You might also want to trim the direction string after reading from file.
The quals method returns a boolean so the result does not need to be compared with the true or false value. Also, I would start with null comparison - boolean expressions in Java are shortened so if this part will be fulfilled rest of the expression is not evaluated. The correct expression might look like this:
 
if (direction == null || (!direction.equals("up") && !direction.equals("down") && !direction.equals("left") && !direction.equals ("right "))) {
}
But this code is not readable. You could use enums or list of Strings like below
List<String> directions = Arrays.asList("up", "down", "left", "right");
String direction = "readValue"
if (!directions.contains(direction)) {
System.out.println("Invalid direction");
System.exit(0)
}

How to use a boolean with two meanings within an if, nested if, else statement

Ok, So when I run the code, after typing in no or anything that which is false, my program doesn't jump to the Else statement at the bottom (Outside of the nested if_Else statement) What am I doing wrong? I tried initiating it with else if (yes!=true) or Else (!yes), I mean you name it, including changing the initial arguments and imputing ( yes==true ^ no==true) however, defining another boolean variable to no and set to true as well!
import java.util.Scanner;
public class Flights
{
public static void main(String args[]){
String txt;
boolean yes=true;
Scanner type=new Scanner(System.in);
int days;
System.out.println("Is this a round trip? ");
txt=type.next();
if(yes==true){
System.out.println("How many days in advance do you plan to book your flight?: ");
days=type.nextInt();
if(days>180)
System.out.println("Error: Flights can't be booked for more than 180 days out");
else if( days<=180 && days>=14)
System.out.println("Your flight cost is: $275");
else if(days<14 && days>=7)
System.out.println(" Your flight cost is: $320");
else if(days<7)
System.out.println("Your flight cost is: $440");
}
else
{
System.out.println("Enter your discount code");
}
}
}
Well, you initiate the yes variable to true, and didn't update it whatsoever before you start the conditional statement where you compare the value of yes to true. That's the issue.
This is where you begin:
boolean yes=true;
and then you wait for user typing in, but do not update the yes value, instead, you go ahead and check it like this.
if(yes==true){
}
This results in the else statement will never be reached.
What you could do is, following this line:
txt=type.next();
You can update the value of the yes variable, something like this:
txt=type.next();
yes = (txt != null) && "yes".equals(txt.toLowerCase());
if(yes==true){
//...
} else {
}
Hope this helps.
For your program to make a decision based on the user input, you have to look at the value of txt.
Change your code to something like this:
yes = txt.equalsIgnoreCase("yes");
if (yes == true) {
...
} else {
...
}
Or even shorter:
if (txt.equalsIgnoreCase("yes")) {
...
} else {
...
}

Left hand side of an assignment must be a variable Error

Please don't mind the logic of the code; I just want help understanding the error, which seems to occur at the last else statement.
package day1.samples;
import java.util.Scanner;
public class Horscope {
public static void main(String[] args) {
// TODO Auto-generated method stub
String [] Birth={"January","February","March"};
System.out.println("Please Enter Your BirthMonth");
Scanner input =new Scanner(System.in);
String X;
X=input.nextLine();
if (X==Birth[0]) {
System.out.println("Your Horoscope is Gemini");
} else if(X==Birth[1]) {
System.out.println("your Horscope is libra");
} else (X==Birth[2]) {
System.out.println("Your horscope is Leo");
}
}
You need to remove the else condition. Only else if can have condition. You can also change the last else to else if.
X=input.nextLine();
if (X.equals(Birth[0])) {
System.out.println("Your Horoscope is Gemini");
} else if(X.equals(Birth[1])) {
System.out.println("your Horscope is libra");
} else {
System.out.println("Your horscope is Leo");
}
Also you don't compare strings with == you should use .equals more details click here
EG:
X.equals(Birth[0])
It should be .equals
} else if (X.equals(Birth[2])) {
Here:
} else (X==Birth[2]) {
should be
} else if (X==Birth[2]) {
Besides == should not be used instead of equals method. I'm just answering about the cause of Left hand side of an assignment must be a variable error.
Else don't have condition checking part. Remove () in front of else.
Or
Use another ladder of else if simply put if before braces.
And other than logic use X.equals("some value") to compare values rather == compares references.
You don't need to specify the condition for the last condition in an if...else ladder. You can either use else if (condition) or just the else.
You are getting the error as your syntax is wrong by using else (condition). Hope this helps.
Also, you should always use the equals() method to check if two strings are equal as it compares the original content of the string. It compares the values of string for equality.
Hence, in your case it should be -
X.equals(Birth[2])

How can I return to the start of the class in Java?

Here's what I'm working on: I have been working on a program in Java for a while now and I still have come to the ultimatum that I cannot do one thing, return to the start of the code - I always end up with a syntax error here or there.
I'm no pro so don't hate on me if this is an easy question!
Here's my code:
import java.util.Scanner;
public class Name {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int Name;
int Confirmation = 5;
System.out.print("What Game Would You Like To Buy? Type '9' for Help. Type '0' To View The Selection Of Games Available: ");
System.out.println("");
Name = keyboard.nextInt();
if (Name == 0) {
System.out.println("Fantasy World (0.99). Type '1' to Purchase.");
System.out.println("Sir Wags A Lot (0.99). Type '2' to Purchase.");
System.out.println("Take a Path (1.99). Type '3' to Purchase.");
// (plus a few more calls to println)
}
if (Name == 9) {
System.out.println("Help:"
+ "All games are corresponded to a single integer ranging from 1 to 8. Type 0 in the main bar too see the range of games."
+ "Too see this help message, type 9."
+ "For more information on each game, type the number followed by that number again. For example, I would type 22 too see more information on Sir Wags A Lot.");
}
if (Name == 1) {
System.out.println("Fantasy World is £0.99, are you sure you want to pay? Type '1' for Yes or '0' for No: ");
Confirmation = keyboard.nextInt();
}
if (Confirmation == 1) {
System.out.print("Thank You For Purchasing!");
}
if (Confirmation == 0) {
System.out.print("Ok, Come Again!");
}
if (Name == 11) {
System.out.println("Fantasy World:");
System.out.println("Title: Fantasy World");
System.out.println("Genre: RPG");
System.out.println("Description: Where you can live your dreams");
System.out.println("Price: £0.99");
}
if (Name == 22) {
System.out.println("Sir Wags A Lot:");
// (plus more println calls)
}
if (Name == 33) {
System.out.println("Take a Path:");
// (plus more println calls)
}
if (Name == 44) {
System.out.println("River Clear Up:");
// (plus more println calls)
}
if (Name == 55) {
System.out.println("PinBall:");
// (plus more println calls)
}
if (Name == 66) {
System.out.println("Ghost Girl:");
// (plus more println calls)
}
if (Name == 77) {
System.out.println("Dress Up:");
//(plus more println calls)
}
if (Name == 88) {
System.out.println("Where Is My Hat?:");
//(plus more println calls)
}
}
}
So basically, the variable is that the user types in a double digit integer to activate the bottom sub-classes. Say I want more info on 'Fantasy World':
I type 11 in the input console, it displays the text - maybe I want to buy the game but obviously, I don't want to restart the whole program - could I make it easier to just add some more code to the bottom of each sub-class that will return it to the integer input at the top again?
I've tried as easiest as possible to explain my situation.
You basically just need to put your code inside a do-while loop. You can read about it here. The program will keep running until the condition for the while statement is true.
You can add a loop - a do-while, or while- that will run forever (while(true)). Add another input type to your conditions which will be the exit code. If your exit code is 99, then when the user types 99 you can return; and that will end your program.
Here's the quickest fix:
Rename your main function to programLoop
Make a new main function that says this:
code:
public static void main(String args[]) {
while(true) {
programLoop(args);
}
}
The proper fix is to read up on how loops works, so you understand how the program flows.

Categories

Resources