import javax.swing.JOptionPane;
public class Insurance {
final static String INPUT_GENDER = "Please enter your gender: (Male or Female)";
final static String MALE = "male";
final static String FEMALE = "female";
static String gender;
public static void main(String args[])
{
do
{
gender = JOptionPane.showInputDialog(INPUT_GENDER).toLowerCase();
System.out.println(gender);
}
while(!gender.equals(MALE) && !gender.equals(FEMALE));
}
}
The above piece of code is the beginning to a revision assignment, but I came across something I don't understand. The user is asked to enter their gender, as "Male" or "Female", and the program should only continue if the input satisfies one of these inputs. This is done by comparing the input to the final strings for MALE and FEMALE.
What I don't understand is why it only works using && in the while statement. I expected it to need ||, because we want it to continue if the input matches either of the two gender strings. I understood that && should only allow the code to continue if both arguments are true.
TL;DR
while(!gender.equals(MALE) && !gender.equals(FEMALE)); //This works
while(!gender.equals(MALE) || !gender.equals(FEMALE)); //This does not work
while(gender.equals(MALE) || gender.equals(FEMALE)); //This does not work
&& is a logical and operator
|| is the logical or operator
Using De Morgan, the following:
while(!gender.equals(MALE) && !gender.equals(FEMALE))
Can be translated to:
while(!(gender.equals(MALE) || gender.equals(FEMALE)))
(note the additional parenthesis and the placement of the ! before them).
Both the above mean that the gender is neither MALE or FEMALE.
Your other code:
while(!gender.equals(MALE) || !gender.equals(FEMALE))
The above means - gender is not MALE or gender is not FEMALE.
while(gender.equals(MALE) || gender.equals(FEMALE));
Similarly, the above means - gender is MALE or gender is FEMALE.
In English: "when not FEMALE or MALE, do again"
then in Java do{...}while(!(FEMALE || MALE));
and !(A||B) is equal to !A && !B
In your do-while loop you want prompt the user to re-enter his/her gender if the gender entered is neither MALE nor FEMALE.
So the while condition would be that if both gender.equals(MALE) and gender.equals(FEMALE) return false then you would re-prompt the user i.e. the loop will iterate.
That means if not of gender.equals(MALE) and not of gender.equals(FEMALE) both are true then your loop should iterate.
Hence,
while(!(gender.equals(MALE)) && !(gender.equals(FEMALE)))
&& is Java's logical AND operator
|| is Java's logical OR operator
for example:
boolean a = true;
boolean b = false;
boolean c = a && b; // c is false
boolean d = a || c; // d is true
Additionally, ! is Java's logical NOT operator. It is used for negating boolean expressions:
boolean p = true;
boolean q = !p; // q is false
It is also worth noting that x && y will result in the same logical value as !(!x || !y).
Similarly, x || y can be rewritten as !(!x && !y)
Related
I want to make my do loop run while the input the user made is not equal to the required letters (a-i) For some reason,even when i input the proper letters, it loops forever.
I've tried using switch cases as well as != inside the comparison.
Here is my code:
do {
System.out.println("Please enter the location of your battleship, starting with the first letter value. Make sure it is from the letters a-i.");
lL1=in.nextLine();
if (!lL1.equals("a")||!lL1.equals("b")||!lL1.equals("c")||!lL1.equals("d")||!lL1.equals("e")||!lL1.equals("f")||!lL1.equals("g")||!lL1.equals("h")||!lL1.equals("i")){
System.out.println("Invalid Input. Try again.");
}//End if statement
}while(!lL1.equals("a") || !lL1.equals("b") || !lL1.equals("c") || !lL1.equals("d") || !lL1.equals("e") || !lL1.equals("f") || !lL1.equals("g") || !lL1.equals("h") || !lL1.equals("i"));
My skills in Java are limited but this should work, unless i'm missing something obvious. Any help would be amazing!
Instead of using an operator for each case of the input, you might want to create a list of the accepted answers and then your condition will look like:
while answer is not in accepted answers, ask another input
An example would be:
Scanner scanner = new Scanner(System.in);
List<String> acceptedAnswers = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h", "i");
String input;
do {
System.out.println(
"Please enter the location of your battleship, starting with the first letter value. Make sure it is from the letters a-i.");
input = scanner.nextLine();
} while (!acceptedAnswers.contains(input));
scanner.close();
System.out.println("Got correct input: " + input);
If you have a negation you need AND to join the conditions not OR.
That's because if you or some not-ed values, they form an and.
Let me explain better.
If you input a, then the first is false (because you not it), and the others are true, so the or condition make the result be true.
You should instead group all the ors and then not it.
e.g.
!(lL1.equals("a") || lL1.equals("b") || lL1.equals("c") || lL1.equals("d") || lL1.equals("e") || lL1.equals("f") || lL1.equals("g") || lL1.equals("h") || lL1.equals("i"))
Please try this:
char lL1;
Scanner scanner = new Scanner(System.in);
do {
System.out.println("Please enter the location of your battleship, starting with the first letter value. Make sure it is from the letters a-i.");
lL1=scanner.next().charAt(0);
}while(lL1!='a' && lL1!='b' && lL1!='c' && lL1!='d' && lL1!='e' && lL1!='f' && lL1!='g' && lL1!='h' && lL1!='i');
Since you are only getting a single character, you can check that it does not match either [a to i] characters as shown above. This is the shortest way to do so by making the check as the condition of the loop. If it fails then the loop will be called.
For some reason, when I have multiple correct strings, the statement keeps repeating
do {
System.out.println("Enter Service Code");
Scanner a = new Scanner(System.in);
serviceCode = a.nextLine();
} while (!serviceCode.equals("ORB1") || !serviceCode.equals("ORBH") ||
!serviceCode.equals("ISS5") || !serviceCode.equals("ILLOYDS") ||
!serviceCode.equals("DLAB") || !serviceCode.equals("LEOM7") ||
!serviceCode.equals("MOON2"));
However, when there's just one string that the code checks against. The do while statement works fine and will stop looping when the correct input is entered
do {
System.out.println("Enter Service Code");
Scanner a = new Scanner(System.in);
serviceCode = a.nextLine();
} while (!serviceCode.equals("ORB1"));
If you enter "ORB1", "!serviceCode.equals("ORB1")" will return false but the others will return true; and you are using the "OR" operator. So, this sentence :
!serviceCode.equals("ORB1") || !serviceCode.equals("ORBH") ||
!serviceCode.equals("ISS5") || !serviceCode.equals("ILLOYDS") ||
!serviceCode.equals("DLAB") || !serviceCode.equals("LEOM7") ||
!serviceCode.equals("MOON2")
will always be true. You need to use the "AND" operator
!serviceCode.equals("ORB1") && !serviceCode.equals("ORBH") &&
!serviceCode.equals("ISS5") && !serviceCode.equals("ILLOYDS") &&
!serviceCode.equals("DLAB") && !serviceCode.equals("LEOM7") &&
!serviceCode.equals("MOON2")
Your comparison can never return false. it's either A or B.
so, if you were to say:
if ( !A OR !B ){
--> Input = A => true (because !B returns true)
--> Input = B => true (because !A returns true)
--> Input = C => true (because !A returns true)
Change your OR (||) by AND (&&)
Also: declare and instantiate your Scanner before your loop.
A better approach would be create a Listof string which includes the valid codes and check if that list contains the provided user input.
List<String> validServiceCodes = Arrays.asList("ORB1", "ORBH", "ISS5", "ILLOYDS", "DLAB", "LEOM7", "MOON2" );
do {
System.out.println("Enter Service Code");
Scanner a = new Scanner(System.in);
serviceCode = a.nextLine();
} while (!validCodes.contains(validServiceCodes));
below my code was working fine until my last if-else. It appears I've done something wrong with my boolean variables canGraduate and onProbation. Perhaps I'm reassigning them incorrectly in the prior if-else statements. The deadbranch occurs at the else half of my last if-else.
package lab5;
import java.util.Scanner;
public class Lab5 {
public static void main(String[] args) {
//creates scanner object
Scanner scanner = new Scanner(System.in);
//PART II
//creating variables
double gpa;
int totalCreditsTaken;
int mathScienceCredits;
int liberalArtsCredits;
int electiveCredits;
boolean canGraduate = true;
boolean onProbation = false;
//prompts user for imput
System.out.println("What is your GPA?");
gpa = scanner.nextDouble();
System.out.println("What's the total amount of credits you've taken?");
totalCreditsTaken = scanner.nextInt();
System.out.println("How many math and science credits have you taken?");
mathScienceCredits = scanner.nextInt();
System.out.println("How many liberal arts credits have you taken?");
liberalArtsCredits = scanner.nextInt();
System.out.println("How many elective credits have you taken?");
electiveCredits = scanner.nextInt();
//creates first "if" statment to determine if GPA is high enough to be on track or on probation
if (gpa < 2.0){
System.out.println("You're on academic probation.");
onProbation = true;
}
//PART III
//creates a conditional to see if there's enough credits to graduate
if (totalCreditsTaken < 40 ){
System.out.println("You need more credit(s) to graduate.");
canGraduate = false;
}
else{
System.out.println("Examining credit breakdown...");
canGraduate = true;
}
//PART VI
//Nested if-else if-else to determine if the student qualifies for BA or BS
if ((mathScienceCredits >= 9) && (electiveCredits >= 10)){
System.out.println("You qualify for a BS degree.");
canGraduate = true;
}
else if ((liberalArtsCredits >= 9) && (electiveCredits >= 10)){
System.out.println("You qualify for a BA degree.");
canGraduate = true;
}
else{
System.out.println("You currently don't meet the degree requirments.");
canGraduate = false;
}
//PART V
//Uses an if statement to either congradulate the student or tell the student to take more classes
if ((onProbation = true) || (canGraduate = false)){
System.out.println("You don't qualify to graduate.");
}
else{
System.out.println("Congradualations you qualify to graduate.");
}
}
}
You are assigning the values here:
if ((onProbation = true) || (canGraduate = false)){
You need to compare them using == instead
UPDATE (after comments)
Better yet, don't compare boolean values. Instead, since onProbation and canGraduate are both boolean types, you can use:
if (onProbation || ! canGraduate ){
credit to #RealSkeptic and #FredK (in their comments)
A bit more explanation about what's happening here.
In Java, the = operator is assignment, not comparison (The comparison operator is ==). So if a is an int, a = 3 means "put the value 3 in the variable a".
But an assignment is also an expression. In addition to putting the value in that variable, the expression also evaluates to the value that was assigned.
So the value of the expression a = 3 is 3. You can do things like:
System.out.println( a = 3 );
This will both put 3 in a, and print 3 on the console.
Usually, Java doesn't allow you to confuse between = and ==. If the variable is an int or a float or a String, writing a statement like:
if ( a = 3 ) ... // Compilation error
will not work because the value of the expression is 3, an int value, and if expects an expression of type boolean. So it will tell you that the expression is wrong, and you'll notice: "Oh, I meant ==".
But if the type of a is boolean, then writing a = false or a = true is an assignment, that also returns the value that was assigned - which is a boolean. Because of that, you can write
if ( a = false ) ... // Compiles correctly
and the compiler won't complain, because the value of the expression is boolean and that's what the if expects. The compiler doesn't know you actually meant to compare. All it knows is that it got an expression of the appropriate type.
For this reason it is recommended never to compare boolean variables at all. Instead of
if ( a == true )
It is perfectly correct to write
if ( a )
Because the if will succeed when a is true and fail when a is false. No need to compare! It's important to give the variable a good name like you did - canGraduate is a good name, and a statement like
if ( canGraduate )
is nicely readable "If [the user] can graduate...".
For false, you can use
if ( ! canGraduate )
it's not as nice-sounding in English, but it's clear enough, and clearer than if ( canGraduate == false ), with the added bonus that you will not miss the = and write if ( canGraduate = false ) by mistake.
So I am writing a code that ask a user if they would like to be recommended a new pet. I give them a message dialog the ask them to enter Y for Yes and N for No. This is my code do far and there is something I am not getting. The big question is how do I test if the value they entered is Y or N. The answer they give can either be lower case or upper case. How do I code this?
public static void aPet()
{
char answer;
String newPet;
newPet = JOptionPane.showInputDialog(null,"Would you like to recommend another pet?(Y), or Stop (N)","Another Recommendation?", JOptionPane.QUESTION_MESSAGE);
answer = newPet.charAt(0);
if (answer == y || answer == Y)
{
//methods to recommend pet
}
if (answer == n || answer == N)
{
System.exit(-1);
}
}
You need to use actual character literals, not just the letter:
if (answer == 'y' || answer == 'Y')
Characters are denoted in code by surrounding the letter with single quotes (they can also be denoted in other ways, but this is the simplest).
You can read about this on The Java Tutorials > Primitive Data Types which says, among other things:
Always use 'single quotes' for char literals and "double quotes" for String literals.
You are missing single quotes around the values 'y' and 'n':
Try this:
char answer = newPet.charAt(0);
if('y' == answer || 'Y' == answer) {
// recommend pet
} else {
// exit
}
OR
Edited
if(newPet.matches("y|Y")) {
// recommend pet
} else {
// exit
}
OR
if("y".equalsIgnoreCase(newPet)) {
// recommend pet
} else {
// exit
}
You can use Character#toUpperCase() like that:
if (Character.toUpperCase(answer) == 'Y')
{
//methods to recommend pet
}
In my program, I have a String called yesOrNo that is a keyboard input. I created an if statement to test if yesOrNo is one of the following : "Y", "y", "Yes",
"yes" by using the || operator.
I got the error message: The operator || is undefined for the argument type(s) java.lang.String, java.lang.String. What is the right way to do something like this? Thanks.
Scanner keyboard = new Scanner(System.in);
String yesOrNo = keyboard.nextLine();
System.out.println(yesOrNo + "?" );
if (yesOrNo.equals("Y" || "y" || "Yes || "yes")){
The shortest I can think of is :
if (yesOrNo.equalsIgnoreCase("Y") || yesOrNo.equalsIgnoreCase("Yes"))
Your syntax is invalid. It needs to have separate clauses:
if(yesOrNo.equals("Y") || yesOrNo.equals("y")...)
or cleaner would be if you used regex:
if(yesOrNo.matches("Y|y|Yes|yes")) {
// Code.
}
Extra Reading
You should look at the String Docs. They detail all sorts of useful stuff.
Read up on Regex. It makes complex String comparison very simple.
Finally, look at the different Operators to see what kind of logical statements you can form, with the correct syntax.
Alternatively, you could create a list of acceptable answers and check whether the answer is in that list.
List<String> kindOfYes = Arrays.asList("yes", "y", "okay", "righto");
if (kindOfYes.contains(yesOrNo.toLowerCase())) { ...
Two ways:
Using equals:
if (yesOrNo.equals("Y") ||
yesOrNo.equals("y") ||
yesOrNo.equals("Yes") ||
yesOrNo.equals("yes")) {
//...
}
Using regexp (shorther than using || multiple times):
if (yesOrNo.toLowerCase().matches("y|yes")) {
//...
}
Try:
if(yesOrNo.equals("Y") || yesOrNo.equals("y")
|| yesOrNo.equals("Yes") || yesOrNo.equals("yes"))
if (yesOrNo.equals("Y") || yesOrNo.equals("y") || yesOrNo.equals("Yes") || yesOrNo.equals("yes"))
What about the next code?
String yesOrNo = keyboard.nextLine();
if (yesOrNo.toLowerCase().charAt(0) == 'y') {
//
}
NOTE: Do you think there's a quicker way? I think not.
Like this:
if (yesOrNo.equals("Y") || yesOrNo.equals("y") || yesOrNo.equals("Yes") || yesOrNo.equals("yes")){
//...
}
Your program syntax is wrong.
This is correct:
Scanner keyboard = new Scanner(System.in);
String yesOrNo = keyboard.nextLine();
System.out.println(yesOrNo + "?" );
if(yesOrNo.equals("Y") || yesOrNo.equals("y") || yesOrNo.equals("Yes") || yesOrNo.equals("yes")) {