today i have an issue with this code i wrote. The problem comes when i try and run it with command prompt, it doesnt display the last line of code i wrote "Congratulations, the birth month is April"
If anyone understands why it would be helpful!
CODE:
import java.io.*;
import java.util.Scanner;
public class Lab3_5{
// Global variable to hold sales is defined
static double age, weight, birthMonth;
public static void main(String[] args){
// Method calls
getAge();
getWeight();
getMonth();
}
// This module takes in the required user input
public static void getAge(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your guess for age: ");
double age = keyboard.nextDouble();
if (age >= 25){
System.out.println("Congratulations, the age is 25 or less.");
}
}
// This module takes in the required user input
public static void getWeight(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your guess for weight: ");
double weight = keyboard.nextDouble();
if (weight <= 128){
System.out.println("Congratulations, the weight is 128 or less.");
}
}
// This module takes in the required user input
public static void getMonth(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your guess for birth month: ");
String birthMonth = keyboard.next();
if (birthMonth == "April"){
System.out.println("Congratulations, the birth month is April.");
}
}
}
It has no relation with the command prompt.
The problem is that :
if (birthMonth == "April"){
should be :
if ("April".equals(birthMonth)){
Strings have to be compared with equals().
birthMonth == "April" is true only if these are the same object.
This is not always the case wheras equals() compares the content of the Strings.
The command prompt is not the issue here.
You can't use "==" with strings, you need to use equals() or equalsignorecase()
public static void getMonth(){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter your guess for birth month: ");
String birthMonth = keyboard.next();
if (birthMonth.equalsIgnoreCase("April")){
System.out.println("Congratulations, the birth month is April.");
}
}
}
This is because String are objects. (note that String is uppercase what is good practice for classes!)
So you are looking at two different String classes and you are asking if they are the same, which they are not off course. So by using equals() or equalsIgnoreCase, you tell the class to compare itself with the other based on what kind of chars it holds.
In java String is a class and hence birthMonth is an object and so you cannot do
if (birthMonth == "April")
Since == tests for reference equality (whether they are the same object).
you have to string function .equals() or equalsIgnoreCase() (ignores cases) which tests for value equality (whether they are logically "equal").
Like So
if (birthMonth.equalsIgnoreCase("April"))
Related
My code looks like this; it get's an error on line 18
error: bad operand types for binary operator '==' if(answer=='y'||answer=='Y') {
import java.util.Scanner;
public class FullName {
public static void main(String[]args) {
String firstName = " ", middleName = " ", lastName = " ";
String in; // checks for input
String answer; // checks for condition, YES OR NO
boolean ask; // use as a loop switch
Scanner scan = new Scanner(System.in);
do {
System.out.println("Please indicate your full name: ");
in = scan.nextLine();
ask = scan.hasNext(in);
String str = String.format("My name is %s %s %s ", firstName, middleName, lastName);
System.out.println("Do you want to try again? (Y/N )");
answer = scan.Next();
if(answer=='y' || answer=='Y') {
ask = true;
} else {
ask = false;
}
} while(ask == true);
}
}
Let's just focus on these lines:
String answer;
...
answer = scan.next();
if (answer == 'y' || answer == 'Y') {
You will notice that I have tweaked the the style to make it more readable and consist with common Java style rules.
You will notice that I have fixed a compilation error by changing Next() to next().
But now for the interesting part:
answer == 'y' || answer == 'Y'
What you are trying to do here is test if the user is trying to reply in the affirmative or the negative; i.e. a response to your `"(Y/N)" question.
There are both technical and logical problems in the way you are doing it. The technical problem is that answer == 'y' tries to compare a String and a char using ==. Java doesn't allow that.
This is what the compilation error about "bad operand types for ==" is saying.
String and char are different types.
'Y' and "Y" are not the same value.
Expressions of the form "string == char" or "char == string" are not allowed.
You shouldn't compare strings using == anyway; see How do I compare strings in Java?.
So if you were just going to compare (one character) String with a char, there are a few ways to do it; e.g.
answer.charAt(0) == 'y'
or
Character.toString('y').equals(answer)
(In this context charAt(0) is safe. You are using the default Scanner delimiter, so next() is going to return a String with length of at least 1.)
But it would be simpler to do a String to String comparison:
answer.equals("y")
or
"y".equals(answer)
The latter has the advantage in some contexts that "y" can never be null so you will avoid possible NPEs.
Now for the logical problem. You have asked the user to respond to a (Y/N) question. But you are actually using Scanner to read a word (loosely speaking) so you may get one character, or more than one. Also, you are assuming that if the answer is not y or Y, then that means "no". But what if the user enters "yes" ... or "fish"? There are more possible answers to consider than the ones that you are expecting.
If I was marking this exercise, I would deduct a mark or two (out of ten) for not properly validating the user's input.
Since the answer variable is not stored as a string, change its variable type to char.
Also, use the following code to get the letter entered by the user.
answer = scan.next().charAt(0);
Use the following
import java.util.Scanner;
public class FullName {
public static void main(String[]args) {
String firstName = " ", middleName = " ", lastName = " ";
String in; // checks for input
char answer; // checks for condition, YES OR NO
boolean ask; // use as a loop switch
Scanner scan = new Scanner(System.in);
do {
System.out.print("Please indicate your full name: ");
in = scan.nextLine();
//ask = scan.hasNext(in);
String str = String.format("My name is %s %s %s ", firstName, middleName, lastName);
System.out.println("Do you want to try again? (Y/N )");
answer = scan.next().charAt(0);
if(answer=='y' || answer=='Y') {
ask = true;
} else {
ask = false;
}
scan.nextLine();
} while(ask == true);
}
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 12 months ago.
So i'm just doing some elementary testing while I learn java, and i'm curious why this doesn't work:
public static void main(String[] args) {
String[] names={"John","Mark","Suzy","Anthony"};
String[] passwords={"passw0rd","CandyC4ne","x5021","ADawg55"};
System.out.println("Please indicate which user you would like to log in as:\n(1)John\n(2)Mark\n(3)Suzy\n(4)Anthony");
Scanner x=new Scanner(System.in);
int y=x.nextInt()-1;
System.out.print("Please enter the password to log into "+names[y]+"'s account: ");
Scanner a=new Scanner(System.in);
String newpass=a.nextLine();
System.out.println(passwords[y]);
if(passwords[y]==newpass){
System.out.print("Hello "+names[y]+"!");
}else{
System.out.println("Incorrect Password. "+passwords[y]+" "+newpass);
}
}
Both passwords[y] and newpass are the exact same string, and when I try:
if(passwords[y]=="passw0rd");
(And obviously pick the 'John') it does work, so i'm hoping someone can explain the difference and how to get around it so as to better accept user input.
Also i'll take a for loop as an answer, but i'm hoping I can avoid it.
never use == to compare strings. Always use equals or equalsIgnoreCase methods. == will check both references pointing to the same object and equals will check the content of the strings.
Use equals or compareTo method to compare to two Strings instead of == which compares reference.
import java.util.*;
public class Password{
public static void main(String[] args) {
String[] names={"John","Mark","Suzy","Anthony"};
String[] passwords={"passw0rd","CandyC4ne","x5021","ADawg55"};
System.out.println("Please indicate which user you would like to log in as:\n(1)John\n(2)Mark\n(3)Suzy\n(4)Anthony");
Scanner x=new Scanner(System.in);
int y=x.nextInt()-1;
System.out.print("Please enter the password to log into "+names[y]+"'s account: ");
Scanner a=new Scanner(System.in);
String newpass=a.nextLine();
System.out.println(passwords[y]);
if(passwords[y].equals(newpass)){
System.out.print("Hello "+names[y]+"!");
}else{
System.out.println("Incorrect Password. "+passwords[y]+" "+newpass);
}
}
}
Output:
$ javac Password.java && java Password
Please indicate which user you would like to log in as:
(1)John
(2)Mark
(3)Suzy
(4)Anthony
1
Please enter the password to log into John's account: passw0rd
passw0rd
Hello John!
I am creating a simple lift programme in java. I want to to have four users that are allowed to use the lift i have already got it working for 1 but i cant figure out how to check multiple strings using the one if statement.
import java.util.Scanner;
public class Username
{
public static void main (String[]args)
{
Scanner kb = new Scanner (System.in);
String name;
System.out.println("Enter your name");
name = kb.nextLine();
if (name.equals("barry "))
System.out.println("you are verified you may use the lift");
Scanner f = new Scanner(System.in);
int floor;
System.out.println("What floor do you want to go to ");
floor = f.nextInt();
if (floor >7)
System.out.println("Invalid entry");
else if (floor <= 7)
System.out.println("Entry valid");
}
}
Check out this related question:
Test if a string contains any of the strings from an array
Basically, put the names into an Array of strings, and compare the name entered with each name in the Array.
Use the OR symbol "||" or "|".
Such as if (name.equals("barry ") || name.equals("sara"))
For future reference the difference between the two is "||" short circuits. In this situtation, if barry is the name then the second statement for checking against sara will never be executed.
basically, you need an "Or" gate, this would work:
if(name.equals("name1")||name.equals("name2")||name.equals("name3"))
etc...
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
import java.util.Scanner;
public class Poop {
public static void main (String args[]){
Scanner input = new Scanner(System.in);
String Gender;
System.out.println("Are you a boy or a girl?");
Gender = input.nextLine();
if(Gender == "boy"){
System.out.println("You are a boy.");
}
if(Gender == "girl"){
System.out.println("You are a girl.");
}
}
}
I'd like to know why this program isn't working. In Eclipse it says there is no errors but when i run it and type in boy or girl nothing happens and I don't see why.
Also please no making fun of the program I am testing myself on string variables.
If you are comparing Strings, don't use ==, but use equals():
if(Gender.equals( "boy" ) ){
System.out.println("You are cool.");
}
if(Gender.equals( "girl" ) ){
System.out.println("You are cute.");
}
In Java == compares object identities and not contents! So in your case your compare the object, you read in, with two others objects. This will always fail.
On the other hand equals() compares the contents of both objects and thus will succeed here.
This is probably a duplicate of this answer:
What is the difference between == vs equals() in Java?
Use equals instead of == in java for stirng comparison
import java.util.Scanner;
public class Poop {
public static void main (String args[]){
Scanner input = new Scanner(System.in);
String Gender;
System.out.println("Are you a boy or a girl?");
Gender = input.nextLine();
if(Gender.equals("boy")){
System.out.println("You are cool.");
}
if(Gender.equals("girl")){
System.out.println("You are cute.");
}
}
}
Use .equals() for string comparision not ==
I have just answered an answer: exactly same problem
Use equals method for string comparision.
== will not compare string object's string value it just checks for reference equality.
In this respect if you compare two string objects with same value they are not equal by == operator
import java.util.Scanner;
public class Poop {
public static void main (String args[]){
Scanner input = new Scanner(System.in);
String Gender;
System.out.println("Are you a boy or a girl?");
Gender = input.nextLine();
if(Gender.equals("boy")){
System.out.println("You are cool.");
}
if(Gender.equals("girl")){
System.out.println("You are cute.");
}
}
}
Just realized multiple same answers. Reason is same, use .equals instead of ==
import java.util.Scanner;
public class Poop {
public static void main (String args[]){
Scanner input = new Scanner(System.in);
String Gender;
System.out.println("Are you a boy or a girl?");
Gender = input.nextLine();
if(Gender.equals("boy")){
System.out.println("You are cool.");
}
if(Gender.equals("girl")){
System.out.println("You are cute.");
}
}}
Use the .equals for string comparison.
if(Gender.equals("boy"))
Or you could intern the input like so, and then use ==
Gender = input.nextLine().intern();
if(Gender=="boy")
Interesting program though :D
I'm getting in on this...
== tests if the two String objects are the same object.
.equals() tests if the two Strings have the same "value"
Change your tests to if(Gender.equals("boy")) etc.
Java ain't javasript.
public static String getSubMenu(String submenu){
Scanner keyboard = new Scanner(System.in);
String chosen="", A="A",B="B", a="a", b="b";
do{
chosen = keyboard.next();
keyboard.nextLine();
System.out.print("\n\n");
}while(chosen.compareTo(A));
return chosen;
}
//This function below is fine.
public static void Menu(){
String unem="";
do{
System.out.println("Sub Menu");
System.out.println("Select an Option\n\n");
System.out.println("a.Sort by name\n" +
"b.Sort by time\n" +
"c.Exit sub-menu\n\n");
System.out.print("Input the number for the selected option: ");
unem= getSubMenu(unem);
if("a".equals(unem)|| "A".equals(unem)){
}
if("b".equals(unem)|| "B".equals(unem)){
}
}while ("a".equals(unem) ||"b".equals(unem) || "A".equals(unem) || "B".equals(unem));
}
}
Hi, I'm trying to make a sub menu. As you can see in the function Menu, when getSubMenu is called the user has to input a selected option in the function getSubMenu. I looked through my textbook and online and it doesn't seem you can use char within arguments such as
char a="a";
if(a != b);
If you can use characters instead of strings in the functions above please tell.
But moving on. What I am trying to do now is to get getSubMenu to return a String containing either 'A' || 'a' || 'b' || 'B' || 'c' || 'C' and then loop when the user does not put any of these as an input. I've tried attempting to use compareTo but I receive a Type mismatch: cannot convert from int to boolean error how can I improve on this. What syntax can I use so that this can work.
Thanks for everyone who will help and contribute to this.
EDITED: NEW WORKING FUNCTION
public static String getSubMenu(String submenu){
Scanner keyboard = new Scanner(System.in);
boolean looped = true;
String chosen="";
do{
chosen = keyboard.next();
keyboard.nextLine();
System.out.print("\n\n");
if("a".equals(option)|| "A".equals(option) || "b".equals(option)|| "B".equals(option) || "c".equals(option)|| "C".equals(option)){
looped = false;
}
else
System.out.println("Wrong input");
}while(looped);
return option;
It may of not been what I was aiming for but it still did it job.
while(chosen.compareTo(A)) is where you should get an error . The method compareTo(String) returns an int which you cannot use in while(boolean expression) , it requires a boolean expression which shall evaluate to true or false. I am pasting a code for reference , improvise on it :
public static String getSubMenu(String submenu) {
Scanner keyboard = new Scanner(System.in);
List<String> list = Arrays.asList(new String[]{"A","B","C"});
do {
chosen = keyboard.next();
keyboard.nextLine();
System.out.print("\n\n");
} while (chosen!=null && list.contains(chosen.toUpperCase()));
return chosen;
}
compareTo() compares 2 objects and returns an int that represents which object was greater. Since it is not a boolean your do while loop fails to compile. If you're looking for a specific input from the user, use this snippet.
do
{
chosen = keyboard.next();
keyboard.nextLine();
System.out.print("\n\n");
}
while (!chosen.trim().equalsIgnoreCase("a"));
You'll need to trim() the string to remove characters like whitespaces and you can use equalsIgnoreCase() to match 'A' and 'a'.