This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am new to programming and would appreciate some help. The slightest bit of insight would be highly appreciated.
I have an issue with the following code. The program emulates a calculator but currently my main focus is on if and else if statements. The issue is that no matter what the user selects, the program will always add the two numbers i.e. 'number1' and 'number2' in the code
import java.util.*;
public class Input
{
private Scanner input;
public Input()
{
input = new Scanner(System.in);
}
public void calculation()
{
double number1, number2, answer;
String A, B, C, D, E;
String option;
A = "A"; B = "B"; C = "C"; D = "D"; E = "E"; //initialising the strings
System.out.println("add - option A \t (if your option is A, insert 'A')");
System.out.println("multiply - option B");
System.out.println("subtract - option C");
System.out.println("divide - option D");
System.out.println("power - option E (1st number - 'X' & 2nd number - 'n' following X^n)");
System.out.println("Remember Java is case sensitive, therefore, inserting 'a' as 'A' won't work");
System.out.println();
System.out.println("Insert your first number: ");
number1 = input.nextDouble();
System.out.println("Insert your second number: ");
number2 = input.nextDouble();
System.out.println("Choosing option: ");
option = input.next();
if(A == A)
{
answer = number1 + number2;
System.out.println("Your answer is: " + answer);
}
else if(B == B)
{
answer = number1 * number2;
System.out.println("Your answer is: " + answer);
}else if(C == C)
{
answer = number1 - number2;
System.out.println("Your answer is: " + answer);
}else if(D == D)
{
answer = number1 / number2;
System.out.println("Your answer is: " + answer);
}else if(E == E)
{
answer = Math.pow(number1, number2);
System.out.println("Your answer is: " + answer);
}else
{
System.out.println("Choose a suitable option");
}
}
}
Youre getting the selected option from user input in option = input.next(); line and than your not using it in your if statements.
Instead of if(A == A) use if(option.equals(A)) and so on for other cases.
Related
This question already has answers here:
In Java, how do I check if input is a number?
(4 answers)
Closed 5 years ago.
Is there a basic solution I am missing here?
Side note, I don't particularly want a super advanced solution as I am in the first 8 weeks of a computer science course in college and I feel it is either something simple I am missing or something I haven't learned yet.
Please focus on what I am asking, I know the code can be cleaner for now I don't want tips on how to make it more efficient I know there is too much repetition.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
/*Initializing a string which will be
*used in the future to determine the
*operator the user wants to use*/
String operator = "z"; //Cant be A,S,M or D or the program would skip my while loop
//Creating number variables which will initilised later by user input//
int numOne;
int numTwo;
//Creating a boolean variable asking the user if they would like
//to run another calculation and a String to store Yes or No
boolean anotherCalc = true;
String runAgain = "p";
Scanner userOperator = new Scanner(System.in);
Scanner userNumbers = new Scanner(System.in);
Scanner userAgain = new Scanner(System.in);
while (anotherCalc == true) { //Containing the whole calculator in this while loop
//so it only stops when the user says they don't want another calc
while (!operator.equalsIgnoreCase("A") && !operator.equalsIgnoreCase("S")
&& !operator.equalsIgnoreCase("M") && !operator.equalsIgnoreCase("D")
&& operator.equalsIgnoreCase("z")){
System.out.println("What kind of calculation would you like to make?");
System.out.println("Press A for Addition\nPress S for Substraction");
System.out.println("Press M for Multiplication\nPress D for Division");
operator = userOperator.next();
}
System.out.println("\nThank you, now what numbers would you like to use?");
System.out.println("Enter number 1:");
String numError;
numError = userNumbers.next();
numOne = Integer.parseInt(numError);
System.out.println("Enter number 2:");
String numError2;
numError2 = userNumbers.next();
numTwo = Integer.parseInt(numError2);
int answer;
//Starting outer if statement containing nested if statements for
//all 4 operators
//Addition if statement with nested if statement that won't
//break the code if someone trys to add outside the int value range
if (operator.equalsIgnoreCase("A")){
if (numOne > 1073741824 || numTwo > 1073741824){
long answerlong = (long) numOne + (long) numTwo;
System.out.print("\nYour answer is " + answerlong);
} else {answer = numOne + numTwo;
System.out.println("\nYour answer is " + answer);}
//Subtraction if statement with nested if statement that won't
//break the code if someone trys to subtract from a number above the int value range
} else if (operator.equalsIgnoreCase("S")){
if (numOne > 2147483647 || numTwo > 2147483647){
long answerlong = (long) numOne - (long) numTwo;
System.out.print("\nYour answer is " + answerlong);
} else {
answer = numOne - numTwo;
System.out.println("\nYour answer is " + answer);
}
} else if (operator.equalsIgnoreCase("M")){
if (numOne > 20000 || numTwo > 20000){
long answerlong = (long) numOne * (long) numTwo;
System.out.print("\nYour answer is " + answerlong);
} else {
answer = numOne * numTwo;
System.out.println("\nYour answer is " + answer);
}
} else if (operator.equalsIgnoreCase("D")){
if (numOne % numTwo == 0){ //Nested if else statement so
answer = numOne / numTwo; //an answer with no decimal
System.out.println("\nYour answer is " + answer); //point is shown as a whole
//number and otherwise return decimals
} else {
float answerdec = (float) numOne / (float) numTwo;
System.out.printf("\nYour answer is " + "%.2f",answerdec);}
} else {
System.out.println("\nError");
}
System.out.println("\nWould you like to run another calculation?");
System.out.println("Press Y for Yes or N for No");
runAgain = userAgain.next();
if (runAgain.equalsIgnoreCase("Y")){
anotherCalc = true;
operator = "z"; //This needs to be added so it returns to ask the user what type of calculation
System.out.println("\n\n"); //This is just for aesthetics, creating 2 lines before the program runs again. Not included on the first run of the program on purpose.
} else if (runAgain.equalsIgnoreCase("N")){
anotherCalc = false;
} else {
anotherCalc = false;
System.out.println("\n\nInput Error (Y or N not entered)\nPlease reload the program");
}
}
System.out.println("\n\nThank you for using the calculator");
System.out.println("I hope you enjoyed it");
parseInt() will throw NumberFormatException, so it should be caught... so for example:
try{
numOne = Integer.parseInt(numError);
}catch(NumberFormatException nfe){
System.out.println("Error: value entered is not a number");
System.out.println("Please try again");
continue;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I am new to Java and I am creating a simple calculator. I used while loop to run it continuously but I couldn't stop it, Please help me with the code.
My calculator class code is:
package calculator;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Boolean keepRunning = true;
while (keepRunning) {
double a, b, out;
int n;
String ans = null;
Scanner in = new Scanner(System.in);
System.out.println("Enter two Numbers ");
a = in.nextDouble();
b = in.nextDouble();
System.out.println("Enter the mode of operation:" + "\n"
+ "1. Addition" + "\n"
+ "2. Subtraction" + "\n"
+ "3. Multiplication" + "\n"
+ "4. Division");
n = in.nextInt();
switch(n){
case 1:
out = add(a,b);
System.out.println("The output is: "+ out );
break;
case 2:
out = sub(a,b);
System.out.println("The output is: "+ out );
break;
case 3:
out = mul(a,b);
System.out.println("The output is: "+ out );
break;
case 4:
out = div(a,b);
System.out.println("The output is: "+ out );
break;
default:
System.out.println("Enter Valid option");
break;
}
System.out.println("Do you want to continue? (Y/N)");
Scanner in1 = new Scanner(System.in);
ans = in1.next();
if(ans == "Y" || ans == "y"){
}else if(ans == "N" || ans == "n"){
keepRunning = false;
System.exit(0);
}
}
}
public static double add(double a, double b){
return a+b;
}
public static double sub(double a, double b){
return a-b;
}
public static double mul(double a, double b){
return a*b;
}
public static double div(double a, double b){
return a/b;
}
}
The if loop is not at all running what's the problem in it.
Note: This question is already exist in Stackoverflow but I can't find my answer.
Don't compare strings with == in Java, use "N".equals(ans), for example. Look out to the duplicate that #EJP post for you
Somewhere around line 15 it gives me issues.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //scanner object created
System.out.println("Enter your first number");
int nr1 = sc.nextInt();
System.out.println("Enter your second number");
int nr2 = sc.nextInt();
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
int ans = 0;
//somewhere around this line is where it is having the problems. it gives me the answer before i can put in my sign;
if(anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
}
else if(anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
}
else if(anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
}
else if(anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
}
System.out.println(ans);
System.out.println("To continue type yes");
String yes= sc.nextLine();
if(yes.equalsIgnoreCase("yes")) {
return;
}
}
}
it answers "0" whatever I enter before I can put in my sign
Enter your first number
9
Enter your second number
9
Enter your sign (+ , - , /, *)
0
To continue type yes
please tell me what I did wrong and possibly correct it so I can understand further
Try changing your sc.nextInt() lines to Integer.parseInt(sc.nextLine()). This should make your code work correctly.
EDIT: updated the code to include a while loop to make it so you can do multiple runs per your comment. This would also require you changing your last if statement to break; instead of return;
Scanner sc = new Scanner(System. in ); //scanner object created
while (true) {
System.out.println("Enter your first number");
int nr1 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your second number");
int nr2 = Integer.parseInt(sc.nextLine());
System.out.println("Enter your sign (+ , - , /, *)");
String anvin = sc.nextLine();
int ans = 0;
//somewhere around this line is where it is having the problems. it gives me the answer before i can put in my sign;
if (anvin.equalsIgnoreCase("+")) {
ans = nr1 + nr2;
} else if (anvin.equalsIgnoreCase("-")) {
ans = nr1 - nr2;
} else if (anvin.equalsIgnoreCase("*")) {
ans = nr1 * nr2;
} else if (anvin.equalsIgnoreCase("/")) {
ans = nr1 / nr2;
}
System.out.println(ans);
System.out.println("To continue type yes");
String yes = sc.nextLine();
if (!yes.equalsIgnoreCase("yes")) {
break;
}
}
Change
String anvin = sc.nextLine();
to
String anvin = sc.next();
Also keep in mind that you might divide through zero ;-)
Edit:
also change
String yes= sc.nextLine();
to
String yes= sc.next();
Instead of sc.nextLine(); use sc.next();
I would suggest you this, you can not only learn using objects but learn a better way of writing managed codes too,
Calculator.java -> a class
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
//Instantiate
Scanner input = new Scanner(System.in);
Calculations calc = new Calculations();
// Variable declarations
double answer = 0, entry1 , entry2 ;
char operator;
// Start
System.out.println("***** Welcome to the Command line calculator program *****");
System.out.print("Please enter the first number :");
entry1 = input.nextDouble();
System.out.print("Please enter the second number:");
entry2 = input.nextDouble();
System.out.println("Please enter the operation : ");
System.out.println("***** Operations :- + -> Add ; - ->Substract ; / -> Divide ; * -> Multiply ; ^ : Power *****");
operator = input.next().charAt(0);
// Switch case
switch (operator){
case '+' : answer = calc.add(entry1, entry2);
break;
case '-' : answer = calc.substract(entry1, entry2);
break;
case '/' : answer = calc.divide(entry1, entry2);
break;
case '*' : answer = calc.multiply(entry1, entry2);
break;
case '^' : answer = calc.power(entry1, entry2);
break;
}
System.out.println(entry1 + " " + operator + " " + entry2 + " = " + answer);
}
}`
Calculations.java -->another class holding calculations
import java.math.*;
public class Calculations {
// Addition Method
double add (double first, double second){
double answer = first + second;
return answer;
}
// Substraction Method
double substract (double first, double second){
double answer = first - second;
return answer;
}
// Multiplication Method
double multiply (double first, double second){
double answer = first * second;
return answer;
}
// Division Method
double divide (double first, double second){
double answer = first / second;
return answer;
}
// Power Method
double power(double a, double b){
double answer =Math.pow(a, b);
return answer;
}
}
I've run a debugger and everything, but I can't find out whats wrong! I run the code, and it accepts a as an asnwer, but if i put b, it runs the code saying "This is not an A or a B"
import java.util.Scanner;
public class messingAround {
public static void main(String[] args){
Scanner ques = new Scanner(System.in);
String question;
System.out.println("Would you like to:");
System.out.println("A: Solve a math problem");
System.out.println("B: Display Pi");
System.out.println("Type A or B (no caps)");
question = ques.next();
if(!(question.equals("a")) || question.equals("b")){
System.out.println("Sorry that isn't an A or a B");
System.out.println("Try running the code again");
}else if(question.equals("a")) {
double fnum, snum, answer;
String type;
Scanner intString = new Scanner(System.in);
System.out.println("Enter your first number: ");
fnum = intString.nextDouble();
System.out.println("Enter your second number: ");
snum = intString.nextDouble();
System.out.println("What would you like to do? (+ - * /)");
type = intString.next();
if(type.equals("*")){
answer = fnum * snum;
System.out.println("The product is: " + answer);
}else if(type.equals("+")) {
answer = fnum + snum;
System.out.println("The sum is: " + answer);
}else if(type.equals("-")) {
answer = fnum - snum;
System.out.println("The difference is: " + answer);
}else if(type.equals("/")) {
answer = fnum / snum;
System.out.println("The dividend is: " + answer);
}
}else if(question.equals("b")) {
System.out.println("3.14159265359");
}
}
}
if(!(question.equals("a")) || question.equals("b")){
parens are a bit off. Try this:
if(!(question.equals("a") || question.equals("b"))){
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I have been coding Java for a short period of time so I do not know why my System.exit(0) command is not working.
This program tests a user on 1st or 2nd grade math. It takes in two "random" numbers and the user answers arithmetic questions. When the program asks the user whether they want to play again, entering N for No does not seem to register with the if statement that contains System.exit(0). The program just restarts as if the user entered Y.
import java.util.*;
class Tester {
public static void main (String[] args) {
SuperRandom randomNumberGenerator = new SuperRandom();
Scanner scan = new Scanner (System.in);
int selection, q1_1, q1_2, q1_3, q1_4, q1_5, questans;
int score = 0;
int a;
int b, i;
String scanchoice;
String choice = "Y";
final int numberOfQuestions = 5;
int getNextRandom;
int answer;
while (choice == "Y"){
System.out.println ("Welcome to Math Tester 2.0.");
System.out.println ("");
System.out.println ("Please enter your grade level:");
System.out.println ("1. 1st Grade Test");
System.out.println ("2. 2nd Grade Test");
System.out.println ("3. Quit Math Tester 2.0");
selection = scan.nextInt();
if (selection == 1) {
System.out.println ("Enter: " +selection);
System.out.println ("");
for (i=1; i<=5; i++){
a = randomNumberGenerator.getNextRandom(numberOfQuestions);
b = randomNumberGenerator.getNextRandom(numberOfQuestions);
System.out.println ("What is " +a + " + " +b + "?");
answer = a+b;
questans = scan.nextInt();
System.out.println("" +questans);
if (questans == answer){
score++;
}
}
System.out.println ("");
System.out.println ("Max points possible: 5.");
System.out.println ("Your score: " +score);
System.out.println ("Do you wish to play again (Enter Y for Yes or N for No)?");
choice = scan.next();
if (choice = "N") {
System.out.println ("Goodbye!");
System.exit(0); //Exits program if user entered N.
}
if (choice = "Y");
choice = "Y";
}
if (selection == 2){
System.out.println ("Enter: " +selection);
System.out.println ("");
}
if (selection == 3){
System.out.println ("Goodbye!");
System.exit(0);
}
}
}
}
System.exit() is not executed in your code because your if/else conditions are not right.
Use equals for string comparion instead of ==.
As per the comments in Juned Ahsan'anwer you should change = to == or .equals() for example in this line if (choice = "N") { it should be if (choice.equals("N")) {
Though == will not work in your case you should use .equals()
= is an assignment operator where as == is a relational operator