Left hand side of an assignment must be a variable Error - java

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])

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

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 &&.

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 {
...
}

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

If statement always giving the same answer

import java.util.Scanner;
class Practice {
public static void main(String args[]) {
System.out.println("Enter the number of treats you have:");
Scanner treatsScanner = new Scanner(System.in);
int treats = (treatsScanner.nextInt());
System.out.println("Enter the number of hamsters you have:");
Scanner hamstersScanner = new Scanner(System.in);
int hamsters = (hamstersScanner.nextInt());
System.out.println("How many treats does each hamster need?");
Scanner neededTreatsScanner = new Scanner(System.in);
int neededTreats = (neededTreatsScanner.nextInt());
int treatsPerHamster = treats / hamsters;
boolean enoughTreats = treatsPerHamster >= neededTreats;
if (enoughTreats = true) {
System.out.println("There are enough treats for all the hamsters!");
}
else if (enoughTreats = false) {
System.out.println("Oh no! There aren't enough treats!");
}
}
}
Can someone explain to me why this program returns "There are enough treats for all the hamsters!" regardless of whether "neededTreats" > "treatsPerHamster"?
Thank you.
You should use == instead of =
if (enoughTreats == true) {
System.out.println("There are enough treats for all the hamsters!");
}
else {
System.out.println("Oh no! There aren't enough treats!");
}
Remember that == is the comparison operator and = is the assignment operator.
And as Mike mentioned, just having if(enoughTreats) will do the trick for you. No need to use == operator!
As a matter of fact, you don't need the boolean variable enoughTreats at all. You could just write your condition like so:
if (treatsPerHamster >= neededTreats) {
// do one thing
}
else {
// do other
}
You are assigning the value true to enoughtreats.
Try using the equality operator rather than assignment:
if (enoughtreats == true) {
...
}
or simply:
if(enoughtreats) {
...
}
In java, the '=' operator assigns a value to a variable. In this case,
if (enoughTreats = true)
assigns the value 'true' to 'enoughTreats' and then checks if 'enoughTreats' is true (which it always will be).
Instead, you want to put
if (enoughTreats == true)
so that it will check if enoughTreats is true or false.
Use == for equality, not =.
if (enoughTreats = true)
By using =, you are assigning true to enoughTreats. Use the == comparison operator instead.
You need to change these two statements
if (enoughTreats = true)
else if (enoughTreats = false)
into
if (enoughTreats == true)
else if (enoughTreats == false)
You could also shorten the code and get the exact same effect by simply typing this below:
if (enoughTreats)
else
If you put a boolean variable inside of the parenthesis of an if statement by itself, the if statement will check to see if it's true, thus you wouldn't need to type '== true.' You could also replace the else if statement in your code with a simple 'else' because if the enoughTreats variable is not equal to true, the else code will automatically execute without you having to specifically state a condition.
Few things to note and to add to the listed answers
Just one scanner is enough Scanner inputScanner = new Scanner(System.in);
Braces around (...Scanner.nextInt()); is not really necessary
You may need to consider a non zero check for hamsters !
Handle Non Ints & -ve numbers in the input
else if(){} is not required when if(){} has only single boolean check , just an else{ is sufficient

Categories

Resources