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.
Related
This question already has answers here:
String.equals versus == [duplicate]
(20 answers)
How do I compare strings in Java?
(23 answers)
Closed 11 months ago.
I wrote a function to receive user input. Can't get the correct answer back. Always Failure. I am losing my mind right now.
public String getChoice() {
Scanner SC = new Scanner(System.in);
System.out.print("Ready to play? (Y/N) ");
String playChoice = SC.next(); // Input Y or N
playChoice = playChoice.replace("\n", "");
System.out.println("Input length is: " + playChoice.length());
System.out.println(playChoice);
if (playChoice == "N") {
SC.close();
return "Success N";
}
else if (playChoice == "Y") {
SC.close();
return "Success Y";
}
SC.close();
return "Failure"; // Always this one works
}
Try this:
public String getChoice() {
Scanner SC = new Scanner(System.in);
System.out.print("Ready to play? (Y/N) ");
String playChoice = SC.next(); // Input Y or N
playChoice = playChoice.replace("\n", "");
if (playChoice.equals("N")) { // Replace operator '==' with 'equals()' method.
SC.close();
return "Success N";
} else if (playChoice.equals("Y")) { // Same here.
SC.close();
return "Success Y";
}
SC.close();
return "Failure"; // Always this one works
}
The reason why your code is not working as intended, is that the == operator compares whether the 2 compared object references are pointing to the same object. This obviously is not the case in your if-statements, and therefore those expressions will always evaluate to false.
the equals() method on the other hand actually compares the content of the given objects , thus delivering the desired result.
#Bialomazur gave an explanation already and here is a bit cleaner code and tips.
Actually, closing Scanner is not a good practice, but if you decided to, you can close it before your ifs just in one place, since you are not using scanner anymore.
Also, switch looks better here
public String getChoice() {
Scanner SC = new Scanner(System.in);
System.out.print("Ready to play? (Y/N) ");
String playChoice = SC.next(); // Input Y or N
playChoice = playChoice.replace("\n", "");
System.out.println("Input length is: " + playChoice.length());
System.out.println(playChoice);
SC.close();
switch (playChoice) {
case "Y":
return "Success Y";
case "N":
return "Success N";
default:
return "Failure";
}
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have this program set up and i need help with 2 errors that i am getting
import java.util.Scanner;
public class EvenOdd {
public static void main(String[]args) {
Scanner keyboard = new Scanner (System.in);
System.out.print("---EvenOdd--- /n");
System.out.printf("Enter a whole number: ");
c = in.nextInt();
}
public static EvenOdd (int num) {
int c = num;
if (int.class)
(c/2)*2 = c;
System.out.println("is even.");
else (c)
System.out.println("is odd");
return EvenOdd;
}
}
C:\Users\Desktop\EvenOdd.java:28: error: not a statement
else (c)
C:\Users\Desktop\EvenOdd.java:28: error: 'else' without 'if'
else (c)
2 errors
Your else doesn't make sense. First of all, you are not using braces, but also your boolean logic does not make sense. Just adding braces will not make your code compile.
I think this rewrite is the closest to what you have
public static boolean EvenOdd (int num) {
// Here your calculation is done
boolean isEven = (c/2)*2 == c;
if (isEven) {
System.out.println("is even.");
} else if (!isEven) {
// Using 'else if' for a boolean parameter does not make much sense
// but i'll leave it here to explain the syntax
System.out.println("is odd");
}
return isEven;
}
However, the most common way to check for odd or even is using the modulus operator. And if i make the entire code a bit more java-ish, you'd end up with (for example method-naming)
/**
* Check if the given number is even.
* #param num the number to check
* #return whether num is an even number
*/
public static boolean isEven (int num) {
if ((x % 2) == 0) {
System.out.println("is even.");
return true;
} else {
System.out.println("is odd");
return false;
}
}
Here is a solution
public static void main(String[]args)
{
Scanner keyboard = new Scanner(System.in);
try{
System.out.println("---EvenOdd---");
System.out.print("Enter a whole number: ");
int c = keyboard.nextInt();
evenOdd(c);
}finally{
keyboard.close();
}
}
public static void evenOdd(int num)
{
int c = num;
if ((c/2)*2 == c){
System.out.println("is even.");
}else {
System.out.println("is odd");
}
}
Output:
for the input value 5
---EvenOdd---
Enter a whole number: 5
is odd
for the input value 4
---EvenOdd---
Enter a whole number: 4
is even.
Continued Reading
There are several problems with the original code and I will attempt to explain them in line order.
Original code for reference:
public class EvenOdd {
public static void main(String[]args) {
Scanner keyboard = new Scanner (System.in);
System.out.print("---EvenOdd--- /n");
System.out.printf("Enter a whole number: ");
c = in.nextInt();
}
public static EvenOdd (int num) {
int c = num;
if (int.class)
(c/2)*2 = c;
System.out.println("is even.");
else (c)
System.out.println("is odd");
return EvenOdd;
}
}
First we have this line
System.out.print("---EvenOdd--- /n");
use of the .print() method here, while not illegal is unnecessary because java provides us with .println() which automatically creates a new line so we don't have to. (i.e. with "/n")
System.out.printf("Enter a whole number: ");
Next you use the .printf() method, this prints a formatted output and accepts arguments as a parameter. You aren't using any of the exclusive features of this method so we can achieve the same functionality with .print().
c = in.nextInt();
the variable in is not defined in this scope, I presume that you meant to use keyboard.nextInt().
public static EvenOdd (int num) {
when a method has no return type and the same name as the class it resides in (case sensitive) it is a constructor. Constructors do not require a return statement and are invoked with the syntax new ObjectConstructor() usually to assign a value to a variable of the same type as the constructor.
if (int.class)
(c/2)*2 = c;
System.out.println("is even.");
else (c)
System.out.println("is odd");
This if-else block is clearly not even java syntax.
first there is no need to cast your result to an int and the semicolon at the end of your conditional doesn't belong.
removing these errors brings us to:
if (c/2)*2 = c
System.out.println("is even.");
else (c)
System.out.println("is odd");
now we need to wrap our conditional in parentheses '( and )' and rather than use the assignment operator '=' we should use the comparison operator '==' which returns a boolean. Also, the else clause does not require a condition, if you would like to use a condition look into elseif.
these changes get us to this step.
if ((c/2)*2 == c)
System.out.println("is even.");
else
System.out.println("is odd");
Now we add proper brackets and we are good to go.
if ((c/2)*2 == c){
System.out.println("is even.");
}else{
System.out.println("is odd");
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
This a simple program that asks the user for two questions. Based on the user's input, we will display a guess of what the object is. Similar to the game "20 Questions". No matter what input I give the program, it always returns the value of myGuess as "paper clip"
I have tried commenting out the inside of each if/else statement and having the output set to 1,2,3 but it still gets to 3 ( the block of the paper clip). This leaves me to think that my comparison of strings has a bug either in the assignment of the user input or conditional logic... Here is the code:
import java.util.Scanner;
public class JavaTraining {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String input1,input2;
String myGuess;
System.out.println("TWO QUESTIONS!");
System.out.println("Think of an object, and I'll try to guess it.\r\n");
System.out.println("Question 1) Is it an animal, vegetable, or mineral?");
input1 = keyboard.nextLine();
System.out.println("\r\nQuestion 2) Is it bigger than a breadbox?");
input2 = keyboard.nextLine();
if (input1 == "animal"){
if (input2 == "yes"){
myGuess = "moose";
}
else{
myGuess = "squirrel";
}
}
else if (input1 == "vegetable"){
if (input2 == "yes"){
myGuess = "watermelon";
}
else{
myGuess = "carrot";
}
}
else{
if (input2 == "yes"){
myGuess = "Camaro";
}
else{
myGuess = "paper clip";
}
}
System.out.println("\r\nMy guess is that you are think of a "+myGuess+".\r\nI would"
+" ask you if I'm right, but I don't actually care."+input1+input2);
}
}
Use .equals() for strings instead of == . Java strings are objects not primitive data types.
change this
if (input1 == "animal")
to
if(input1.equals("animal"))
Take a look at this link
It compiles, just that it doesn't initialize the while (choice = false) so whatever ans was entered, it wouldn't show "Invalid input, enter a, b, c: " and reiterate.
import java.util.Scanner;
public class Test
{
public static void main(String[] args)
{
Scanner kb = new Scanner(System.in);
String ans;
boolean choice;
System.out.print("Enter a, b, c: ");
ans = kb.nextLine();
choice = isValidChoice(ans);
while (choice = false)
{
System.out.print("Invalid input, enter a, b, c: ");
ans = kb.nextLine();
choice = isValidChoice(ans);
}
if (choice = true)
{
System.out.println("Your input was " + ans);
}
}
public static boolean isValidChoice(String choice)
{
if (choice.equalsIgnoreCase("a") || choice.equalsIgnoreCase("a")
|| choice.equalsIgnoreCase("a"))
{
return true;
}
else
{
return false;
}
}
}
Always use == when you need to compare , which means equality in Java, while = means assignment. This is different from some language like PL/SQL.
So when you call while(choice =false), Java only assigns false to variable choice , it does not compare the choice with false.
You should use while(choice==false) instead, the same in if (choice == true)
Check operators for more details
You are using an assignment where you want to use the equals operator. while(!choice) or while(choice==false). Same in if. In your case you need to differentiate between valid and the actual choice. Maybe it is easier to have the function return more values than a boolean.
And a helpful tip: never ignore warnings of the compiler or the IDE. It will tell you if you do something stupid like assigning in an expression.
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");
}
}