This question already has an answer here:
- How do I compare strings in Java? 23 answers
I am new to Java. I am working on this bit of code which is being used to create a menu. This is just an example for school, not a real project. I looked for resources online and found some discussion about using string1.equals(string2) when comparing string items. I also have used the method shown below for our other projects to date without any issue.
I did remove the scanner line of code and hardcoded the variable age of 21 and a "S" or a "T" for the variable choice to see if the proper output would print, and it did! I am thinking that there is an issue with my scanner input. Can anyone assist me in figuring it out?
package chapter3.pkg5a;
/** * * @author */
import java.util.Scanner;
public class Chapter35a {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String choice;
int age = 21;
choice = stdin.nextLine();
if (choice == "S" || choice == "T" || choice == "B" && age <= 21) {
if (choice == "S")
System.out.println("vegetable juice");
else if (choice == "T")
System.out.println("cranberry juice");
else
System.out.println("soda");
}
else if (choice == "S" || choice == "T" || choice == "B" && age > 21) {
if (choice == "S")
System.out.println("cabernet");
else if (choice == "T")
System.out.println("chardonnay");
else
System.out.println("IPA");
}
else
System.out.println("invalid menu selection");
}
}
Aucun commentaire:
Enregistrer un commentaire