My program's not working. What do you think is wrong?
Scanner in = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = in.nextDouble();
System.out.print("Enter second number: ");
double num2 = in.nextDouble();
System.out.println("Enter operation to perform: ");
String oper = in.next();
if(oper == "add" || oper == "addition" || oper == "+") {
double sum = num1 + num2;
System.out.printf("The sum of the two numbers is %d", sum);
}
When I type the operation(which is a String), program terminates. Output:
Enter first number: 12
Enter second number: 8
Enter operation to perform:
"add"
Process completed.
I can't seem to find the error, please help?
Never compare strings with operator == - it is rough mistake. Use equals instead:
if(oper.equals("add") || oper.equals("addition") || oper.equals("+")) {
Do not use == use the equals method :
if(oper.equals("add") || oper.equals("addition") || oper.equals("+"))
== operator is used to compare address in memory space rather than the content of the strings being compared
Don't compare Strings using ==. Always use equals():
if("add".equals( oper ) || "addition".equals( oper ) || "+".equals( oper ) ) {
// ...
}
With == you compare object references (or primitive types). Strings are objects in Java, so when you compare oper and add, both point to different objects. Thus even if they contain the same value, the comparison with == fails, because they are still different objects.
if(oper == "add" || oper == "addition" || oper == "+") {
should be
if(oper.equals("add") || oper .equals("addition") || oper.equals("+")) {
use .equals method to check if two strings are meaningfully equal, == operator just checks if two reference variables refer to the same instance.
Don't compare Strings using ==. Use equals instead.
Compare strings by using equals(..) not ==
replace
if(oper == "add" || oper == "addition" || oper == "+") {
by
if(oper.equals("add") || oper.equals("addition") || oper.equals("+")) {
== compares for same reference not same content.
Do what all the others say: use equals or even equalsIgnoreCase. (There are good explanations for this so in the other answers. Would be silly to repeat it here.)
AND type "add" without the " in the console.
Only doing both will work.
use this
if("add".equals(oper) || "addition".equals(oper) || "+".equals(oper)) {
double sum = num1 + num2;
System.out.printf("The sum of the two numbers is %d", sum);
}
In addition to using equals() or still better equalsIgnore() instead of == for strings, you also need to enter add in the command-line instead of "add".
Or else, you have to compare it as:
oper.equals("\"add\"")
Also, you seem to be from a C background. Normally in Java, one would use:
System.out.println("The sum of the two numbers is " + sum);
instead of
System.out.printf("The sum of the two numbers is %d", sum);
since %d prints integer value and not double value.
Related
This is my first try on Java. The project is a calculator that takes a number, an operator signal (+,-,*,/), and another number to create an equation and give the final value of it, asking after that if the user wants to restart the program for another equation or not. I would like to know if there is anything that I can do to improve my code.
Thanks!
/*
Name: Felipe de Araujo
Project #: 1
*/
import java.util.Scanner; //Importing API.
public class Calculator {
public static void main(String[] args){
int a = 1; //Creating variable for the first while loop.
System.out.println("Welcome to the calculator!"); //Program introduction.
while (a == 1){
Scanner input = new Scanner(System.in); //Creating the input.
double firstNumber, secondNumber, result; char operator; //Creating all variables.
//Program asking for the first number.
System.out.print("First Number: ");
firstNumber = input.nextDouble();
//Program asking for the operator
System.out.print(firstNumber + " (+,-,*,/): ");
operator = input.next(".").charAt(0);
int repeat = 1; //Creating variable for the next while loop.
//Evaluating the operator to determine if it is inside the criteria (+,-,*,/).
if (operator == '+' || operator == '-' || operator == '*' || operator == '/'){
System.out.print(firstNumber + " " + operator + " Second Number: "); //If the operator is inside the criteria than start
//asking for the second number.
}
else { //If the operator is not inside the criteria run the loop until the user type something that is.
while (repeat == 1){
System.out.print(operator + " not recognized, please select between (+,-,*,/): ");
operator = input.next(".").charAt(0);
if (operator == '+' || operator == '-' || operator == '*' || operator == '/') {
System.out.print(firstNumber + " " + operator + " Second Number: ");
repeat++;
}
}
}
secondNumber = input.nextDouble(); //Initialize the secondNumber variable to the number typed.
//Equalling the variable result to the return given by the method calculatorMethod, with the variables given.
result = calculatorMethod(firstNumber, secondNumber, operator);
System.out.println(firstNumber + " " + operator + " " + secondNumber + " = " + result);//Printing the equation.
System.out.println(" ");
// Asking the user to continue the program for another operation.
char out;//Creating the variable out.
System.out.print("[y/Y] - continue | [n/N] or any other to end program: ");
out = input.next(".").charAt(0);//Initializing the variable out to what was typed.
//Verifying if the user wants to continue the program.
if (out == 'y' || out == 'Y'){
System.out.println(" ");
}
else {//If the users type anything besides y/Y the program will exit the main loop, ending the program.
System.out.println("Bye!");
a++;
}
}
}
//Declaring the calculatorMethod and all its behaviors.
private static double calculatorMethod(double a, double b, char c){
if (c == '+'){
return a + b;
}
else if (c == '-'){
return a - b;
}
else if (c == '*'){
return a * b;
}
else {
return a / b;
}
}
}
hello and welcome to the Java world :) . Some tips :
Try to give clear name to your variables. 'a', 'b', 'c' could be complicated to understand.
Favor short methods to improve the readability of your code. For example you can create an other method which return an object of : separator + the two numbers and an other one which print the result.
You can use switch(variable) in your calculatorMethod method. For example :
switch (c) { // you have to change the name of all the variables 'c', 'a' and 'b'
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
default:
return a / b;
}
}
You can create an enum or a list with the different operators.
When you check the input operator, you can use a while() loop and delete the if...else loop. The condition of the while loop could be "while the operator is not the correct one (and so, not contained in the list of correct operators), loop again and again".
The scanner initialization Scanner input = new Scanner(System.in); should be out the while() loop because you need to initialize only one time the scanner and in this case, you initialize X times (X refers to the numbers of loops).
Good luck :)
I'm trying to make this Sentinel program more robust by continuing it even when incorrect user inputs are received. I've gotten it to work if the user input is a different int, but if it is a string, or anything else really, the program crashes.
My current code attempt is this:
} else if (userInt != 1 && userInt != 2 && userInt != 3 && userInt != 4 && userInt != 5 && userInt !=6
|| userInt instanceof String) {
The first part of this code works fine at checking if the user input is a different in. The instanceof statement gives the error of "incompatible operand types int and String"
Should I even be using an instanceof statement? Is there a better way to check for this?
This is the whole method:
public static void printMenu() {
Scanner userInput2 = new Scanner(System.in);
String menu = new String(" Please choose from the following menu: \n 1. Rock paper Scissors\n 2. "
+ "Tip Calculator\n 3. "
+ "Number Adding\n 4. Guessing Game\n 5. Random\n 6. Exit");
System.out.println(menu);
int userInt = userInput2.nextInt();
if (userInt == 1) {
System.out.println(" You asked to play Rock Paper Scissors");
System.out.println(" Launching Rock Paper Scissors... \n");
RockPaperScissors gameRun1 = new RockPaperScissors();
gameRun1.main(null);
} else if (userInt == 2) {
System.out.println(" You asked to run the Tip Calculator");
System.out.println(" Launching the Tip Calculator... \n");
TipCalculator gameRun2 = new TipCalculator();
gameRun2.main(null);
} else if (userInt == 3) {
System.out.println(" You asked to run the Number Adding game");
System.out.println(" Launching the Number Adding game... \n");
NumberAddingGame gameRun3 = new NumberAddingGame();
gameRun3.main(null);
} else if (userInt == 4) {
System.out.println(" You asked to play GuessingGame");
System.out.println(" Launching GuessingGame... \n");
GuessingGame gameRun4 = new GuessingGame();
gameRun4.main(null);
} else if (userInt == 5) {
System.out.println(" You asked for a random game");
option5();
} else if (userInt == 6) {
System.out.println( "Thank you for using Conner's Sentinel");
// figure out how to terminate the program from here
} else if (userInt != 1 && userInt != 2 && userInt != 3 && userInt != 4 && userInt != 5 && userInt !=6
|| userInt instanceof String {
System.out.println("Not a valid input, type 1-6");
printMenu();
}
printMenu();
}
There is no way to check if the next input was an int like you are doing (userInput2.nextInt() can only return an int), instead you have to check before you assign the result. Something like,
if (userInput2.hasNextInt()) {
int userInt = userInput2.nextInt();
if (userInt == 1) {
System.out.println(" You asked to play Rock Paper Scissors");
System.out.println(" Launching Rock Paper Scissors... \n");
RockPaperScissors gameRun1 = new RockPaperScissors();
gameRun1.main(null);
} else if (userInt == 2) {
System.out.println(" You asked to run the Tip Calculator");
System.out.println(" Launching the Tip Calculator... \n");
TipCalculator gameRun2 = new TipCalculator();
gameRun2.main(null);
} else if (userInt == 3) {
System.out.println(" You asked to run the Number Adding game");
System.out.println(" Launching the Number Adding game... \n");
NumberAddingGame gameRun3 = new NumberAddingGame();
gameRun3.main(null);
} else if (userInt == 4) {
System.out.println(" You asked to play GuessingGame");
System.out.println(" Launching GuessingGame... \n");
GuessingGame gameRun4 = new GuessingGame();
gameRun4.main(null);
} else if (userInt == 5) {
System.out.println(" You asked for a random game");
option5();
} else if (userInt == 6) {
System.out.println("Thank you for using Conner's Sentinel");
// figure out how to terminate the program from here
} else {
System.out.println("Not a valid input, type 1-6");
printMenu();
}
} else {
userInput2.nextLine(); // <-- consume the non-number
System.out.println("Not a valid number, type 1-6");
printMenu();
}
Instead of "expecting" an int...
int userInt = userInput2.nextInt();
You should "expect" a String...
int actualInput = userInput2.nextLine();
From this you could then use Integer.parseInt(String) in an attempt to parse the String to an int, this will give you your first chance to validate the value.
The problem with this is Integer.parseInt(String) can throw a NumberFormatException, and you really should avoid making logic decisions based on exceptions.
Another approach might be to use a regular expression instead, something like...
if (actualInput.matches("^\\d*")) {
// This is a number, safe to parse to int
} else {
// This is not a number and is not safe to be parsed
}
Once you're satisfied that the actualInput is a number, you could use another Scanner to get the next int...
Scanner safeScanner = new Scanner(actualInput);
int userInt = safeScanner.nextInt();
as an example
userInt instanceof String will always be false, since userInt is an int. If it is an int, you don't need to check for instanceof string.
What you meant is to proof check the string from user input with StringUtils.isNumeric and reduce your other expressions to:
if 1<= userInt && userInt <=6
Should I even be using an instanceof statement? Is there a better way
to check for this?
Even if some other string, non numeric, could be converted to int and result into a value between 1 and 6, this way it would be rejected. Keep the numeric check, yes, just the correct one, StringUtils.isNumeric .
If you opt to have userInt as String, instead, then turn the other expression into if 1<= Integer.parseInt(userInt) && Integer.parseInt(userInt) <=6
First of all, after you write something like this:
int userInt = userInput2.nextInt();
your userInt is declared as an int, and can be nothing but a int. So writing something like this makes no sense:
userInt instanceof String
Because here, you already know that userInt is an int, because you declared it so.
The problem (where the exception, or crash as you called it, occurred) is elsewhere. It will happen at the call to nextInt().
Read the documentation for Scanner.nextInt(), under the exceptions, it states:
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
So that is exactly what happens.
You have several choices, two of which:
catch the exception, and handle it the way you want it to be handled
Use of Scanner.hasNextInt().
I already see a growing number of alternative approaches.
Also most people would translate that chain of if/else if statements into a switch/case/default construct.
Then an other problem in your printMenu() method, it is endlessly recursive. Even though it is just user input, and it might have a limited timespan, with limited user entries before it exits, in theory you could reach a situation where you get a StackOverflowException. This implementation begs to be converted from recursive to iterative to avoid overallocation of objects (memory leak) and having a stack that grows forever.
I'm writing a simple program with a do while loop and switch, which cna accept a mathematical operation and execute it for given 2 numbers.
The problem I have is, why should I initialize the result produced by the operation to zero at the beginning.
If I don't make ans=0, it gives me errors. If the given conditions are not met, some code parts are not executed and I don't need "ans".
package q3;
import java.util.Scanner;
public class Q3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char operator;
float no1, no2, ans=0; // <-------------- Why should I initialize ans
do {
System.out.println(" Mathematical Operations to be performed :");
System.out.println("\t * Multiplication\n\t / Division\n\t + Addition\n\t - Subtraction");
System.out.println("Press any other character to exit");
System.out.print("Mathematical Operator : ");
operator = input.next().charAt(0);
if (operator == '*' || operator == '/' || operator == '+' || operator == '-') {
System.out.print("Number 1: ");
no1 = input.nextFloat();
System.out.print("Number 2: ");
no2 = input.nextFloat();
switch (operator) {
case '*':
ans = no1 * no2;
break;
case '/':
ans = no1 / no2;
break;
case '+':
ans = no1 + no2;
break;
case '-':
ans = no1 - no2;
break;
}
System.out.println("The answer of " + no1 + operator + no2 + " = " + ans);
}
} while (operator == '*' || operator == '/' || operator == '+' || operator == '-');
}
}
Java requires that all local variables are initialised before they are used.
In your print line, you read the value of abs, but not all control paths set a value to it. (Even though you think you've covered all possibilities of your switch given the outer if, the compiler will not see things that way: some other thread could modify operator).
So your IDE / compiler is suggesting that you initialise it at the point of declaration.
This is because if no case evaluates to true, the value of ans will not be set. So you cannot use it.
You can overcome this by adding a default case, and setting the value of ans as 0 in that.
You should initialize ans=0; because you didn't have a default value for ans, for this you need to initialized it.
But if you add the defualt value you don't need to initialize it like this:
...
case '-':
ans = no1 - no2;
break;
default :
ans = someValue;
break;
Well, it could be that none of the case statements apply and as a result ans would still be un-initialized. And since local variables have to be initialised before they are being used, you get this error.
If you didnt initialize it, you ans will have a garbage value at first.
It is not compulsory to initialize it.
But your program will be a better program if you initialize it.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I am working on a VERY simple calculator with Java and it does not seem to output an answer after selecting the operation. The code is as follows:
import java.util.Scanner;
public class Calc {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
Double fnum;
Double snum;
Double answer;
String operation;
System.out.println("Enter a number.");
fnum = keyboard.nextDouble();
System.out.println("Enter another number.");
snum = keyboard.nextDouble();
System.out.println("What operation do you wish for? [Multiplication, Addition, Subtraction, Division]");
operation = keyboard.next();
if (operation == "Multiplication" || operation == "multiplication" || operation == "*") {
answer = fnum * snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Division" || operation == "division" || operation == "/") {
answer = fnum / snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Addition" || operation == "addition" || operation == "+" || operation == "add") {
answer = fnum + snum;
System.out.print("Your answer is: " + answer);
}
else if (operation == "Subtraction" || operation == "subraction" || operation == "-" || operation == "subtract"){
answer = fnum - snum;
System.out.print("Your answer is: " + answer);
}
else {
System.out.println("This is not valid.");
}
}
}
and this is the output:
Enter a number.
6
Enter another number.
6
What operation do you wish for? [Multiplication, Addition, Subtraction, Division]
Multiplication
This is not valid.
Any help would be very appreciated.
P.S. there are no errors.
Thanks!
There are 2 problems. A problem with Scanner and with the condition
keyboard.nextDouble(), keyboard.next() etc... (all except .nextLine() ) leave the newline ( \n or Enter ) in the buffer. This can cause problems etc..
I suggest adding a delimiter using keyboard.useDelimiter("\n");. This only needs to be done once and can be done right after initialization of keyboard.
That way, it will only see the Enter as a signal to end that current input.
Also, the conditions must all be using the .equals() method or .equalsIgnoreCase() which is written as:
operation.equals("Multiplication");
or
operation.equalsIgnoreCase("multiplication");
Strings should be compared via .eqauals() method. So put in the if clause operation.equals("Multiplication")...and so on...
You are comparing strings by reference, not by their values. Use .equals() instead!
As #Sebastian said you should use equals instead of ==
You can improve it a little bit to avoid the spaces mistakes or case (upper case or lower case) issues by doing it the following way:
if (operation.trim().toUpperCase().equals("MULTIPLICATION") || operation.trim().equals("*"))
That way it will work for Multiplication multiplication but also MulTIpliCation, etc.
You can get the same result using equalsIgnoreCase also
I'm trying to do this:
System.out.println("Do you want to solve an equation (y/n)?");
char first = In.getChar();
boolean y = true;
boolean n = false;
if(first == y)
System.out.println("Enter a:");
if(first == n)
System.out.println("Thanks");
Basically, what I'm trying to do is that if I ask the user to solve the equation and the user presses y (meaning yes), then it will go through the if statement for which y is true; but if the user enters n (meaning no), then it will say something like "thanks for using the system".
I'm getting the error "The operator == is undefined for the argument type(s) char, boolean".
What am I doing wrong, and how can I fix this?
y is a boolean. 'y' is a char
if (first == 'y') {
...
}
You're comparing the different data types char and boolean and Java doesn't know how to do that. For example, what should be the result of this?
'a' == false
If you want to compare the content of a char variable with a specific char then do the following:
char charVar = 'n';
if (charVar == 'y') { // this would return "false", because 'n' is not equal 'y'
//...
}
So you can change your code as follows:
if(first == 'y')
System.out.println("Enter a:");
else if(first == 'n') // use "else if" instead of "if" :)
System.out.println("Thanks");