Java: can't get .equals() to work - java

I want to make a basic game where two random numbers are generated and the user has to enter the correct product.
What am I doing wrong? thanks
import java.util.Scanner;
import java.awt.*;
public class Userinput {
public static void main (String[] args) {
String firstName;
//Create scanner to obtain user input
Scanner scanner1 = new Scanner( System.in );
int a, b, correctAnswer;
a=(int) (Math.random()*10);
b=(int) (Math.random()*10);
//obtain user input
System.out.println("Enter your first name: ");
firstName = scanner1.nextLine();
//output information
System.out.print("Hello " + firstName + " ");
System.out.println("what is " + a +" times " + b);
String answer1 = scanner1.nextLine();
correctAnswer = a * b;
if ((answer1).equals(correctAnswer))
System.out.println("Correct!");
else if (!(answer1).equals ("correctAnswer"));
System.out.println("Incorrect!");
}
}

You are comparing a String (answer1) to an Integer (correctAnswer). That's comparing apples and oranges, they are never the same.
You need to either convert the String to an int:
Integer.parseInt(answer1)
which might fail if answer1 can't be parsed as an integer; or convert the int to a String:
Integer.toString(correctAnswer)
and then compare them:
Integer.parseInt(answer1) == correctAnswer // You can use == because int is primitive.
or
answer1.equals(Integer.toString(correctAnswer))

Try this:
int answer1 = scanner1.nextInt();
int correctAnswer = a*b;
if (answer1==correctAnswer) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
There were a few issues with your code, mostly related to mixing up Strings and ints. Here is a good explanation of how to compare different data types. I would recommend that you use Scanner.nextInt() to save you having to cast Strings to integers.
I would also recommend that you do not omit the braces in your if statements. It makes your code easier to read and can avoid some confusion, especially when you are just starting out with Java.

This is where the problem is:
if ((answer1).equals(correctAnswer))
System.out.println("Correct!");
else if (!(answer1).equals ("correctAnswer"));
System.out.println("Incorrect!");
}
Do this instead:
Integer answer = Integer.parseInt( answer1 );
if (answer1.equals(correctAnswer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
The way that it is currently written, "Incorrect!" would always be printed, because of the semi-colon on the else if. Also, it was comparing answer1 with the literal String "correctAnswer" because of the quotes. Since they're not even the same type (int and String), equals(...) returns false. I would also suggest using curly braces. It helps to alleviate some of these issues.

Related

Java: if / else not responding even with no compile errors

I wrote a simple if / else that is supposed to print the answer to the if else. but does not respond even with the correct input. I can't see what I'm missing.
import java.util.Scanner;
public class MarriageQuiz{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
String marStat;
System.out.print("Please enter your Marital Status (M or S) >> ");
marStat = input.nextLine();
marStat = marStat.toUppercase();
if(marStat.equals('M')){
System.out.print("You are married");
}
else if(marStat.equals('S')){
System.out.print("You are single");
}
}
}
Your code is comparing a String object against a character literal, which I believe the JVM will box into a Character object. Well, these two objects don't belong to the same class, so "M".equals('M') will return false. To remedy this, use "M".equals("M").
change toUppercase() to toUpperCase() and marStat.equals('M') to marStat.equals("M") also marStat.equals('S') to marStat.equals("S")
import java.util.Scanner;
public class MarriageQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String marStat = "";
System.out.print("Please enter your Marital Status (M or S) >> ");
marStat = input.nextLine();
marStat = marStat.toUpperCase();
if (marStat.equals("M")) {
System.out.print("You are married");
} else if (marStat.equals("S")) {
System.out.print("You are single");
}
}
}
On the other hand, you can use Character type instead of 'String'. Rather using Character would be more accurate as you are dealing with only one character.
Scanner input = new Scanner(System.in);
Character marStat;
System.out.print("Please enter your Marital Status (M or S) >> ");
marStat = input.next().charAt(0);
marStat = Character.toUpperCase(marStat);
if (marStat.equals('M')) {
System.out.println("You are married");
} else if (marStat.equals('S')) {
System.out.println("You are single");
}
use ""
if(marStat.equals("M")){
System.out.print("You are married");
}
else if(marStat.equals("S")){
System.out.print("You are single");
}
As mentioned in a comment above, you are comparing a String object to an autoboxed Character object. One fix is obviously using double quotes, which Java will autobox to a String object your code will work.
A few tips to save a few lines of code: use String.equalsIgnoreCase() to save a line converting the incoming string to uppercase.
Next, consider using a constant for marital status:
public class MarriageQuiz{
private static final String STATUS_MARRIED = "M";
...
if (marStat.equalsIgnoreCase(STATUS_MARRIED)) {
...
That way you can use STATUS_MARRIED all over your code but can change it from, say, "M" to "Married" easily.

Simple java console calculator

Without directly giving me the answer can someone help me with this simple calculator that I am trying to write?
Everything seem to work well except for the very end when I ask the user to make a choice for add,subtract, multiply, or divide. It does not allow me to enter my choices in the console.
I think it has something to do with the array of String that I created and the if statement. Not sure. Any tips would be much appreciated.
import java.util.Scanner;
public class simpleCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//declare my variables
int firstNum;
int secondNum;
int division = 0, addition = 0, subtraction = 0, multiplication = 0;
String userChoice = "";
String choices[] = {"add","multiply","divide","subtract"};
//ask for user input
System.out.print("Please enter first number: ");
firstNum = input.nextInt();
System.out.print("Please enter second number: ");
secondNum = input.nextInt();
System.out.println("What type of operation would you like to perform on these numbers?");
System.out.println("add " +"multiply " +"subtract " + "divide ");
userChoice = input.nextLine();
if (userChoice == "add"){
System.out.print("Answer = " + addition);
}
//calculator formulas
addition = firstNum + secondNum;
multiplication = firstNum * secondNum;
subtraction = firstNum - secondNum;
division = firstNum / secondNum;
}
}
nextInt() reads just the number and not the end of the line after the number. You will need a nextLine() after each nextInt() to consume the rest of the line.
Also, before you beat your head against the wall the following statement won't work for you:
if (userChoice == "add")
== tests for reference equality.
.equals() tests for value equality. So you need something like this instead:
if (userChoice.equals("add"))
I wanted to give you that freebie because I love your attitude that you don't want anyone to give you the answer. That is great that you wan to learn it. Keep up the good work.
Saying that String a == String b means that you're comparing two strings to see if they have reference equality, while saying a.equals(b) will compare the values stored in the string.
Reference equality is used to compare whether two object references point to the same object, which in this case you shouldn't be using as you're trying to compare whether the value of two variables are equal. So definitely go with
if(userChoice.equals("add"))

Changing single chars to upper or lower case depending on user input in Java

I have tried to find guidance on this, but I keep getting solutions on an entire string, or a single character. I am in my 4th week of Java, and have hit a roadblock.
I have to ask a user to input three letters ("Enter three letters: abc"). Depending on which case they type, I have to write a program that swaps upper with lower and visa versa. For example, if the user types "aBc", my output will be "AbC".
This is what I have so far. If my code is horrible, I'm sorry. I'm learning as I go.
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
}
When I typed "abc" for the input, the output was:
A
B
C
A
B
C
A
B
C
The format of the output is supposed to be "Result: ABC". I can work on that later. I'm just trying to figure out how to get this to execute correctly. My hunch is that I'm definitely going wrong on my if/else statements. I do not know how to print the changed chars all in a row (abc, AbC, ABC, etc). I thought I did it correctly at the beginning with the indexing of the string (0,1,2).
By the way, it's not showing my output correctly this forum. It is supposed to be one letter per line, not "ABCABCABC", if I made sense with that.
The reasoning for this is because it's inside of a for loop, which is essentially worthless, because you are never using the integer 'i'. If you remove the for loop, it should only execute once, thus for outputting "ABC", instead of "A B C A B C A B C". To print the chars in a row, you can simply append each character to a string, and then output that.
The biggest issue I see is that you've got a loop going over the length of the string but you're not using the loop index i to reference the individual characters. In short, you're trying too hard and overlooking the obvious.
Wouldn't this do the trick?
for (int i = 0; i < letters.length(); i++) {
char letter1 = letters.charAt(0);
if (Character.isUpperCase(letter1)) {
System.out.println(Character.toLowerCase(letter1));
} else {
System.out.println(Character.toUpperCase(letter1));
}
}
The reason why you get a redundant printing 'coz you loop the three variables which already contain all characters.
To solve your problem. just remove the for loop. 'coz you already
store each character to the three variables.
You code will look like this now:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.println(Character.toLowerCase(letter1));
else {
System.out.println(Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.println(Character.toLowerCase(letter2));
else {
System.out.println(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.println(Character.toLowerCase(letter3));
else {
System.out.println(Character.toUpperCase(letter3));
}
}
}
Ok, here is my new code. It compiled with no errors and the output was just as it was supposed to be:
import java.util.Scanner;
public class LowerUpper {
public static void main(String[]args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter three letters: ");
String letters = input.nextLine();
char letter1 = letters.charAt(0);
char letter2 = letters.charAt(1);
char letter3 = letters.charAt(2);
if (Character.isUpperCase(letters.charAt(0)) == true)
System.out.print("Result: " + Character.toLowerCase(letter1));
else {
System.out.print("Result: " + Character.toUpperCase(letter1));
}
if (Character.isUpperCase(letters.charAt(1)) == true)
System.out.print(Character.toLowerCase(letter2));
else {
System.out.print(Character.toUpperCase(letter2));
}
if (Character.isUpperCase(letters.charAt(2)) == true)
System.out.print(Character.toLowerCase(letter3));
else {
System.out.print(Character.toUpperCase(letter3));
}
}
}
The problem is that you have a loop then do each letter individually. So get rid of the loop. It would look better if you re-wrote it with a loop but only had one if/else statement inside the loop based on i not 0,1&2.
Replace your for loop with:
System.out.println(letters.toUpperCase());

How do you prompt a user for an input in java

So I just started learning Java, its literally like my 1st day and I wanted to try to make a coinflip game. I already know a decent amount of Javascript and so i was trying to apply that knowledge to java. So everything has been working so far except one thing: Prompting a user for a choice. So read online that i have to import a scanner so i did that as you can see from my code. I also tried some code where you can have the user import a string but you can see a bit later in my program i change the variable userChoice into a number. So basically i just need help with this. If there is some way to have a variable type that can store both numbers or strings that would be best. But im tottaly open to other ways of doing this! Thanks in advanced! Here is the code:
package test;
import java.util.Scanner;
public class testclass {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("hi");
int bob;
bob = (int) Math.floor(Math.random()*2);
System.out.println(bob);
System.out.println("Enter heads or tails?");
System.out.println("You entered "+ userChoice);
if (bob == 0) {
System.out.println("Computer flipped heads");
}
else {
System.out.println("Computer flipped tails");
}
if(userChoice == "Heads") {
userChoice = 0;
}
else {
userChoice = 1;
}
if (userChoice == bob) {
System.out.println("You win!");
}
else {
System.out.println("Sorry you lost!")
}
}
}
Use a scanner, as you said:
Scanner in = new Scanner(System.in);
Then, prompt the user to enter something in:
String userChoice = in.nextLine();
Also, when you compared strings:
if(userChoice == "Heads") {...
that's bad to do for none-primitive objects. It's best to only use the == to compare values that are ints or enums. If you compare a String like this, it won't work, because it's checking if the objects are the same. Instead, compare like this:
if(userChoice.equals("Heads")) {...
Also, to convert to an int (NOTE: You can't convert one type of object to another that aren't related in any way! You'll have to create a new object if you're wanting to do that), do this:
int myInt = Integer.parseInt(myString); // NOTE: Can throw NumberFormatException if non-number character is found.
So your program should look somewhat like:
package test;
import java.util.Scanner;
public class testclass {
public static void main(String[] args) {
//System.out.println("hi");
Scanner in = new Scanner(System.in);
int bob;
int userChoice;
String input;
bob = (int) Math.floor(Math.random()*2);
System.out.println(bob);
System.out.println("Enter heads or tails?");
input = in.nextLine(); // waits for user to press enter.
System.out.println("You entered "+ input);
if (bob == 0) {
System.out.println("Computer flipped heads");
}
else {
System.out.println("Computer flipped tails");
}
if(input.equals("Heads")) {
userChoice = 0;
}
else {
userChoice = 1;
}
if (userChoice == bob) {
System.out.println("You win!");
}
else {
System.out.println("Sorry you lost!");
}
in.close(); // IMPORTANT to prevent memory leaks
}
}
You've already imported the Scanner class so you can now create a variable of the type Scanner for taking inputs.
Scanner in = new Scanner();
userChoice = in.nextLine();
nextLine() can be used to input a character or a string from the user.
To convert the string into a integer, You can assign the integer value to the string in the following way.
if(userChoice == "Heads") {
userChoice = "" + 0;
}
else {
userChoice = "" + 1;
}
"String" datatype in Java can hold both numbers and strings (as you asked). You can get user input using Scanner utility as below:
Scanner input = new Scanner();
userChoice = input.nextLine(); // if it is a string
//userChoice = input.nextInt(); // if it's integer choice
If your string is an integer then you can also parse it to get its integer value. For parsing:
int value = Integer.parseInt(userChoice);
Also for comparing String values you should use "equals" function rather than "==".
if(userChoice.equals("Heads")){...} //rather than if(userChoice == "Heads"){...}
Having imported java.util.Scanner, to get input from the user as a String, create a Scanner object that parameterizes System.in and assign userChoice the value of nextLine() invoked by the Scanner object:
Scanner input = new Scanner(System.in);
String userChoice = input.nextLine();
A few things about your code. The relational operator, ==, is used for comparing primitive data - not objects. Use string1.equals(string2) to see if two strings are equal.
Also, bob = (int) Math.floor(Math.random()*2); is really bob = (int)(Math.random() * 2);
because casting a double as an integer truncates the double to the highest integer less than or equal to it.
It might help you to get the ideas.
public static void main(String[] args) {
Random rd = new Random();
//Enter 1 0R 0
int bob = rd.nextInt(2);
String userChoice;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a number");
userChoice = sc.nextLine();
System.out.println("You entered " + userChoice + " and bob is " + bob);
int uc = Integer.parseInt(userChoice);
if (uc == bob) {
System.out.println("Hehe");
} else {
System.out.println("Sorry");
}
}

Why does my java program skip a if statement? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
im only 15 and new to java so i am trying to build a simple calculator, but i cant seem to figure out why this if statement is being ignored. I have check to be sure that all values are being stored and yes they are so i can not see any other problems which would explain this. Any help would be great! Look for the comment in the second class //This if statement
The first class
public class CalculatorOperations {
double fnum, snum,answer;
String operation;
void plus(){
operation="+";
answer = fnum + snum;
}
void subtract(){
operation="-";
answer = fnum - snum;
}
void multiple(){
operation="*";
answer = fnum * snum;
}
void divide(){
operation="/";
answer = fnum / snum;
}
void invalidOperation(){
System.out.println("Invalid operation.");
}
void showAttributes(){
System.out.println(fnum);
System.out.println(snum);
System.out.println(operation);
}
}
The second class
import java.util.Scanner;
public class calculatorApplication {
public static void main(String [] args){
CalculatorOperations Operators = new CalculatorOperations();
Scanner userInput = new Scanner(System.in);
String loop2 = null;
boolean loop;
while (loop = true){
// Getting input and storing it
System.out.print("Please enter first number: ");
Operators.fnum = userInput.nextDouble();
System.out.println("TEST:"+Operators.fnum);
System.out.print("Please enter second number: ");
Operators.snum = userInput.nextDouble();
System.out.println("TEST:"+Operators.snum);
System.out.print("Please enter operation (+, -, * or /): ");
Operators.operation = userInput.next();
System.out.println("TEST:"+Operators.operation);
// this if statement
if (Operators.operation == "+") {
Operators.plus();
} else if (Operators.operation == "-") {
Operators.subtract();
} else if (Operators.operation == "*") {
Operators.multiple();
} else if (Operators.operation == "/") {
Operators.divide();
} else {
Operators.invalidOperation();
}
System.out.println("Answer: " +Operators.answer);
System.out.print("Would you like to do another sum? (yes or no): ");
loop2 = userInput.next();
}
if (loop2.equals("yes") || loop2.equals("Yes")){
loop = true;
System.out.println();
System.out.println();
}else{
loop = false;
// Closes scanner to prevent resource leaks
userInput.close();
System.exit(0);
}
}
}
Comparing Strings with == generally doesn't work the way you'd like it to. It's because Strings are Objects and == compares object references against each other, instead of checking if the Strings contain identical text.
Try String.equals instead:
if (Operators.operation.equals("+")) {
... //and of course the same for the rest of the statements
Good luck with your program!
Use the .equals(String) method, instead of ==. Your if-structure would change to this:
if (Operators.operation.equals("+")) {
Operators.plus();
} else if (Operators.operation.equals("-")) {
Operators.subtract();
} else if (Operators.operation.equals("*")) {
Operators.multiple();
} else if (Operators.operation.equals("/")) {
Operators.divide();
} else {
Operators.invalidOperation();
}
.equals(String) is used for comparing strings, whereas == is used for comparing everything else pretty much. == is comparing the reference to an object and .equals(String) is used to compare String values.
Also, change while (loop = true) to while(loop) or while (loop == true); otherwise you are indicating that you are actually changing the value of loop.
You don't want to compare strings with == because by doing that you're comparing the reference of the string, and not the value of the string. You need to use the .equals method.
if (Operators.operation.equals("+"))
From the javadoc:
boolean equals(Object anObject)
Returns true if and only if the argument is a String object that represents the same sequence of characters as this object.
Also, you need to change
while (loop = true)
to
while (loop)
= is the assignment operator, == is the comparison operator.

Categories