How to use && (AND) and || (OR) for textView - java

I am developing an personal assistant and it can answer to questions like "How are you?" but I don't want to define the same answers to similar questions such as "How do you feel?" and etc.I tried to use || after contains but it just didn't work.How can I use || in this kind of situation??Can someone help me out please?
Code:
else if (Text.getText().toString().contains("see you later")){
saySomething("Good bye sir"); }
The code I tried:
else if (Text.getText().toString().contains("see you later"||"goodbye")){
saySomething("Good bye sir"); }

String s = text.getText().toString();
// disjunction of 2 contains
boolean orResult = s.contains("see you later") || s.contains("goodbye");
// alternative using regex
boolean regexResult = s.matches(".*(see you later|goodbye).*");

My idea would be to reduce the condition in if clauses like:
boolean isSeeLaterTxt = Text.getText().toString().contains("see you later");
boolean isGoodByeTxt = Text.getText().toString().contains("goodbye");
else if ( isSeeLaterTxt || isGoodByeTxt )) {
saySomething("Good bye sir");
}
That's my short suggestion. The code will be better readable. And you can later change flexible the condition.

else if (Text.getText().toString().contains("see you later"||"goodbye")){
saySomething("Good bye sir"); }
instead of this try below code
else if (Text.getText().toString().contains("see you later") || Text.getText().toString().contains("goodbye")){
saySomething("Good bye sir"); }

Related

How to loop java with incorrect input

I'm currently learning how to code and I'm facing a bit of a problem, and I was hoping someone could help me out. Currently, Im creating a program that prompts for military status and shows appropriate discounts, but I would like it to loop if the answer isn't one of the given options.
This is my code:
public static void main(String[] args)
{
char milID = ' ';
char status = ' ';
String validMilitaryID = JOptionPane.showInputDialog("Do you have a valid military ID?");
milID = validMilitaryID.charAt(0);
Scanner valid = new Scanner(System.in);
if (milID == 'Y') {
System.out.printf("%n Are you Active Duty, Retired, or a Dependant?");
status = valid.nextLine().charAt(0);
} else if (milID == 'y'){
System.out.printf("%n Are you Active Duty, Retired, or a Dependant?");
status = valid.nextLine().charAt(0);
}else{
JOptionPane.showMessageDialog(null, "Sorry, you are currently ineligible for a Military Discount");
System.exit(0);
}
if (status == 'A'){
JOptionPane.showMessageDialog(null, "Congratulations! You are eligible to recieve a 15% discount!");
} else if (status == 'R'){
JOptionPane.showMessageDialog(null, "Congratulations! You are eligible to recieve a 13% discount!");
}else if ( status == 'D'){
JOptionPane.showMessageDialog(null, "Congratulations! You are eligible to recieve a 10% discount!");
} else {
JOptionPane.showMessageDialog(null, "Sorry! That was not a valid answer.");
}
System.exit(0);
}//END MAIN
If anyone is able to help, can you explain the process as well. Since I am new to Java I would like to learn rather than just have a fix.
Thank you!!
1) you may call your input as well as your if code into a while loop
2) maybe use a switch instead of if..else if
something from the logic such as:
boolean checkInput = true;
while (checkInput) {
// now get your input... not coded
switch (milId) {
case "y","Y": bla bla, break;
case "x","X": bla bla, break;
otherwise: bla bla, break;
}}
3) use a variable for your account value; you could code this with a lookup
An integral part of Java (or programming in general) is missing from your code, and that is the "while loop". I do not know how much knowledge of Java you have so far, but a while loop repeats what's in its block of code until a requirement is met. If you are adding a feature that repeats the survey if the wrong input is given, a while loop at the beginning of your conditionals is what you need.
Pseudocode
create variable called correctAnswer
Do you have a military id? Enter y or Y if yes, any other key for no
if yes, correctAnswer = 1
if no, correctAnswer = 0 and while loop is skipped
while correctAnswer = 1
{
Are you active, retired, etc?
If yes, what is your status?
if A, R, or D is given, display congrats message. correctAnswer = 0 //end
if anything other than A, R or D is given, then correctAnswer = 1 //repeat
}
The while loop in the second block of conditionals keeps repeating the loop until a correct answer is given.

How do I get Java to only look at the first letter like y or n?

I am trying to get java to react to the answer regardless of the following letters I just want it to see "y/Y" or "n/N" and act accordingly. I want it to be able to recognize "yep" or "yeah" as opposed to "Yes" because they both begin with 'y'. How do I do that?
public static void reMatch(Scanner scan, Random rand, int gameCount, int
totalCount) {
System.out.println("Would you like to play again?");
String answer = scan.next();
if (answer.equalsIgnoreCase("y")) {
gameCount++;
game(scan, rand, gameCount, totalCount);
}
else if (answer.equalsIgnoreCase("n")) {
results(gameCount, totalCount);
}
}
You need to test the value of first char in the string and act accordingly.
if (answer.charAt(0)=='y' || answer.charAt(0)=='Y') {
gameCount++;
game(scan, rand, gameCount, totalCount);
}
else if (answer.charAt(0)=='n' || answer.charAt(0)=='N') {
results(gameCount, totalCount);
}
else {
//do something else
}
Edit: I highly recommend you use if (answer.substring(0, 1).equalsIgnoreCase("y")) instead as suggested by #Coldspeed
try:
String firstChar = "" + answer.charAt(0);
if(firstChar.equalsIgnoreCase("y")){
....
}
else if(firstChar.equalsIgnoreCase("n")){
....
}
As #ElliotFrisch said in his comment, you can make use of startsWith. Most answers that mean yes start with "ye," such as "yeah," "yep," or just plain "yes," so I would suggest something like this:
if (answer.toLowerCase().startsWith("ye")) {
System.out.println("your answer stared with \"ye\"");
} else {
System.out.println("your answer did not start with \"ye\"");
}
However you can also just use:
if (answer.toLowerCase().startsWith("y")) {
if you only want to test the first letter.
P.S. Thanks Elliot Frisch!

How to check if one out of four strings have been entered?

I am looking for a statement that checks if the input is either: yes, y, no, n.
It should also ignore whether or not there are big or small letters. I have been searching here for a while but couldn't find an answer I understood. Is there a way to add more then just "yes" to the if statement?
String result;
do {
System.out.print("Bigger the better");
result = scanner.nextLine();
if (!("yes".equals(result))) {
System.out.println("Invalid answer, try again");
}
} while(!result.matches("[A-ZÅÄÖa-zåäö]+"));
You could use
if (result.matches("(?i)Y(es)?|N(o)?")) {
...
You can OR your conditions using double pipes ||, like so:
if (result.equals("yes") || result.equals("no") || result.equals("y") || result.equals("n"))
Make your result a lower case by:
result.toLowerCase()
And then you can compare to any of the strings ("yes","no","y","n") by using equals() as you did, and using 'or' (||).
result.toLowerCase();
if(result.length()>1 && !result.equals("yes") &&!result.equals("no")){
System.out.println("wrong input");
} else if(result.charAt(0)=='y') {
System.out.println("good answer");
}else if(result.charAt(0)=='n') {
System.out.println("Invalid answer, try again");
}
it will check ether the user will type "yes" or plain "y", or "no" or plain "n"

How to try a true or false syntax in java

I have the fallowing code
while (b == true){
System.out.print("input the account balance without tax: ");
int inner = input.nextInt();
List[x]=inner;
x=x+1;
}
and I want to check if my user inputs a word it would do:
b =false
So I would exit this loop. In python we had try() and except.
I don't really know what to do in java.
I think you want to change
while (b == true){
to use Scanner.hasNextInt() like
while (input.hasNextInt()){
If you must do a while(true) statement, which isn't good programming practice, the final code snippet would look something like this,
boolean someCondition = true;
while(true){
if(someCondition == false){
break;
}
//and here you would put something that would make that check condition eventual
//false to break the loop
}
This is prone too error but would work for your purposes.
That being said, the answer Elliot gave is the correct one and worth considering.

How to make a x = y or z statement in Java

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")) {

Categories