My else statement doesn't seem to function(JAVA) - java

import java.util.Scanner;
import static java.lang.System.*;
public class Whativelearned {
enum MyfirstEnum {one, two, three}
public static void main(String[] args) {
Scanner keyboardinput = new Scanner(in);
MyfirstEnum trolley;
char a1;
out.println("Do you pee in the shower"? Y/N");
a1 = keyboardinput.findWithinHorizon(".", 0).charAt(0);
if (a1=='Y'||a1=='y') {
trolley=MyfirstEnum.one;
out.println("Ewwwwwww");
}
if (a1=='N'||a1=='n') {
trolley=MyfirstEnum.two;
out.println("Well somebody isn't being very honest");
}else {
out.println("You're not so keen on following instructions, are you?");
}
keyboardinput.close();
}
}
I expect my else statement to cover all outcomes except for the cases in the if cases.
As I expect it to act as (!(a1=='Y'||(a1=='y'||a1=='n'||a2=='N'))
but when I run it the listing the else statement seems to be executed in all cases.

Try this
if (a1=='Y' || a1=='y') {
trolley=MyfirstEnum.one;
out.println("Ewwwwwww");
} else if (a1=='N' || a1=='n') {
trolley = MyfirstEnum.two;
out.println("Well somebody isn't being very honest");
} else {
out.println("You're not so keen on following instructions, are you?");
}

The else statement is always specific to one if statement. Therefore, your else clause is executed whenever the last if condition is not met.
To execute your clause only when none of the conditions are met, you need to change your if statements to else if like so:
if (a1 == 'y' || a1 == 'Y') {
// ...
} else if (a1 == 'n' || 'a1 == 'N') {
// ...
} else {
// ....
}
Another way to solve this would be using a switch statement. These are used to compare a variable to a set of constants. You can use them like this:
switch (a1) {
case 'y':
case 'Y':
// ...
break;
case 'n':
case 'N':
// ...
break;
default:
// ...
}
Please read up some more about the switch statement before you try it in other situations.

Just write else befor second for loop:
else if (a1=='N'||a1=='n') {

Code execution is best understood by a dry run.
If you do in your code you will find the first if statement is checked and if its true then its corresponding process is executed.
Now control moves down to execute the next if statement. This if statement checks the condition which os mutually exclusive of the above if. if its true (only in case above is false) then its corresponding process is executed and if its false then the else part process is executed.
You need to use if followed by if else followed by else

Related

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

Magic 8-ball program

I have an assignment for my Java class to program a Magic 8-ball. It is supposed to generate a random number for the response, contain a "while(true)" statement, and a switch statement for the replies. This is what I have so far. I can't seem to figure out how to work the "while(true)" statement in without it repeating infinitely.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String question;
int retry;
int q1;
System.out.print("What is your question for the Magic 8-bit 8-ball? ");
question = input.next();
System.out.print(process());
/*This is where I am having the problem. How do I work a "while(true)" in
* to where this won't infinitely repeat?
*/
}
public static int process() {
Random rand1 = new Random();
int random = rand1.nextInt(9);
int ans = random;
switch (ans) {
default: System.out.println("Does not compute!! Error! Error!");break;
case 1: System.out.println("The answer is.............. 42");break;
case 2: System.out.println("To get to the other side!!!");break;
case 3: System.out.println("Out of memory! Try again!");break;
case 4: System.out.println("Who do you think I am, IBM's Watson?");break;
case 5: System.out.println("Danger Will Robinson!! Danger!!");break;
case 6: System.out.println("What do you think?");break;
case 7: System.out.println("Fatal error.....nahhh just kidding");break;
case 8: System.out.println("Well, this is fun....NOT!");break;
case 9: System.out.println("Um...... 1,000,000,000,000,000,000,000?");break;
}
return ans;
}
}
Hum, the point of a while (true) loop is to be infinite, unless you add a break statement in it.
while (true) {
doStuff();
// if someCondition is true, this will exit the loop
if (someCondition)
break;
}
Note that this is equivalent to
do {
doStuff();
} while (!someCondition);
or
boolean someCondition = false;
while (!someCondition) {
doStuff();
}
It is usually preferrable to not have an infinite loop (while (true) for example) and have an explicit condition instead. Some exceptions exist, for example if the condition is complicated to express or if you want to break the loop at a particular position of the loop and not at the beginning or at the end :
while (true) {
doStuff();
if (someCondition)
break;
doSomeOtherStuff();
}
One of the many possible ways:
Create a a char and assign it to 'Y' (i.e. char continueLoop = 'Y').
Use this to control the while statement (i.e. while(char == 'Y') ).
Ask the user for input and process the input (i.e. System.out.println("Continue? Y/N") and then use Scanner to read the input and assign it to continueLoop.
You can create something similar using booleans.

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

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

character comparison not working

I have to write a program making a 2-D array and printing it out. Then I am supposed to guide a "character" through this maze. so I want to make it move Up/Down/Left/Right. The user would be allowed to type in u/U/d/D/l/L/r/R.
I put in so that it would give me an error if one of those was not typed in. However it still gives me an error if it is typed in correctly.
char move;
System.out.println("Which way do you want to move? U/D/L/R");
move=stdin.nextLine().charAt(0);
while(move != 'u' || move !='U') {
while( move != 'd' || move != 'D'){
while( move != 'l' || move != 'L'){
while(move != 'r' || move != 'R'){
System.out.println("Invalid input. Try again.");
move = stdin.nextLine().charAt(0);
}}}}
Try this:
Scanner stdin;
stdin = new Scanner(System.in);
move = stdin.nextLine().charAt(0);;
move = Character.toUpperCase(move);
while(move !='U' && move != 'D' && move != 'L' && move != 'R' )
{
System.out.println("Invalid input. Try again.");
move = stdin.nextLine().charAt(0);
move = Character.toUpperCase(move);
}
Your current code do not make sense. If I type R (for example), this would make the program to enter in infinite loop. Since, all the condition on the upper while would evaluate true. Thus, not reaching the instruction that will ask for another input (stdin.nextLine()).
You may also try the following (does the same thing in a different way).
Along with other field declarations:
private static final String keySet = "uUdDlLrR";
And inside the method:
char move = stdin.nextLine().charAt(0);
while (keySet.indexOf(move) == -1) {
System.out.println("Invalid input. Try again.");
move = stdin.nextLine().charAt(0);
}
It's just a bit more readable and requires little change in case you wish to modify the set of allowed keys.
The syntax is a little bizarre (why "while" and not "if"?.... and why nested?) ... but basically you want to be testing with '&&' not '||'.
In english: you want if input is not A and input is not B, then error. If you do "or" then it will always error because one of those nots will alway be true.
EDIT:
easy mistake to make --- for style/clarity, I'd suggest:
switch (move) {
case 'u': case 'U':
/*up code*/
break;
case 'd'' case 'D':
/*down code*/
break;
case 'l'' case 'L':
/*left code*/
break;
case 'r'' case 'R':
/*right code*/
break;
default:
System.out.println("Invalid input. Try again.");
break;
}

Categories

Resources