Boolean Method does not return false - java

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.

Related

Incompatible operand types Scanner and String?

I keep getting the following errors:
Incompatible operand types Scanner
and String
Incompatible operand types int and
String
before I added the int op = Integer.valueOf(operator) line it kept giving me errors when I would name my cases. I'm still very new it's the second code I've written for my class so please keep the explanation simple if at all possible (there is also a calculator class not shown here if there's any confusion about that) :
//change the package name to calculatorClass///////////////
import java.util.Scanner;
public class assignmentB {
public static String String(int y,int x, String name, String str) throws Exception {
if (y < 1)
throw new Exception("Value must be larger than 0.");
if (x < 1)
throw new Exception("Value must be larger than 0");
return name;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Calculator c1 = new Calculator();
Scanner input = new Scanner(System.in);
c1.name = "The total is $";
try {
} catch (Exception e1){
System.out.println(e1);
}
{
int x, y, s, a, m;
String name1;
System.out.println("Red River College");
System.out.println("Custom Calculator");
System.out.println("Enter first value: ");
x = input.nextInt();
System.out.println("Enter second value: ");
y = input.nextInt();
System.out.println("Enter operation(a=Add, s=Subtract, m=multiply): ");
String operator = input.nextLine();
int op =Integer.valueOf(operator);
switch (op) {
case 1:
if (input == "s") {
System.out.println(c1.name + c1.subtract(x,y));
}
case 2:
if (input == "a") {
System.out.println(c1.name + c1.add(x,y));
}
case 3:
if (input == "m") {
System.out.println(c1.name + c1.multiply(x,y));
}
}
}
}
}
```
You have defined input to be a Scanner, with this line:
Scanner input = new Scanner(System.in);
You can then use input to do scanner things, as you're doing here:
x = input.nextInt();
So far so good.
But later in the code, you do this (and a few variations that are similar):
if (input == "s") {
...
}
This isn't valid. The Java compiler is telling you that it will not allow you to use == to compare a Scanner (that is, input) against a String (which in this example is "s"). The compiler is giving you an error to say: input == "s" isn't allowed.
It isn't clear what your intent is (that is, how you want the code to actually behave), but the issue is definitely with those three if statements. Each is attempting to compare a java.util.Scanner with a java.lang.String (one is "s", one is "a", the last is "m"). So you'll need to fix those to do whatever it is you're trying to do.
As a guess, maybe you want to read a new String input from the scanner, and then compare that to "s", etc.? If so, that could look something like below. Note that to compare strings you should use equals() (don't use == to compare strings, or any other objects).
String newString = input.next();
switch (op) {
case 1:
if (newString.equals("s")) {
System.out.println(c1.name + c1.subtract(x, y));
}
...
}

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.

Using result of a scan.nextLine with an if-else statement -- Java

I'm trying to make a BAC (blood alcohol content) calculator that takes inputs from the user and lets them know if they qualify to win... a grand DUI prize! I'm trying to use the Scanner to determine if the person is a male or female and then use an if-then statement down the line based on what the user input...but I don't really know how. It should be a very simple fix, but here's what I have and kinda what I want to do with the if-then statement commented out.
import java.util.*;
public class Proj2_Mazzone
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
String gender;
int D, W, H, age;
...
System.out.print("Enter M if you're a male, or F if you're a female: ");
gender = scan.nextLine();
/*if(gender = M)
{
System.out.println("You're a man!");
}
else if(gender = F)
{
System.out.println("You're a woman!");
}
*/
When comparing String you use .equals() or .equalsIgnoreCase(). Like,
gender = scan.nextLine();
if (gender.equalsIgnoreCase("m")) {
System.out.println("You're a man!");
} else if (gender.equalsIgnoreCase("f")) {
System.out.println("You're a woman!");
}
But, you could also compare the first character with something like
if (Character.toUpperCase(gender.charAt(0)) == 'M') {
System.out.println("You're a man!");
} else if (Character.toUpperCase(gender.charAt(0)) == 'F') {
System.out.println("You're a woman!");
}
note, that's == (not = which is for assignment).
Use like this:
if(gender.equals("M"))
{
System.out.println("You're a man!");
}
else if(gender.equals("F"))
{
System.out.println("You're a woman!");
}
Note: = is assign operator not conditional operator.
You can see how equal condition is work in java at below link.
http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/
What's the difference between ".equals" and "=="?

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