Having trouble the .equals in JAVA - java

package thenewboston;
import java.util.Scanner;
public class apple {
public static void main(String args[]) {
Scanner myScan = new Scanner(System.in);
System.out.println("Enter your first num");
double fnum, snum, answer;
String oper;
fnum = myScan.nextDouble();
System.out.println("Enter your second num");
snum = myScan.nextDouble();
System.out.println("Enter your operation");
if (oper.equals("+")) {
answer = fnum + snum;
} else if (oper.equals("-")){
answer = fnum - snum;
} else if (oper.equals("*")) {
answer = fnum * snum;
} else if (oper.equals("/")){
answer = fnum / snum;
} else {
System.out.println("Please choose a valid operation");
}
System.out.println("Your answer is: " + answer);
}
}
Hi. Im trying to use .equals() in order to create a basic calculator but there is an error showing up on oper when I write oper.equals("...").

You should assign value to oper.
String oper = "*";

You are probably getting an error because you never actually set oper to anything before using it.
...
snum = myScan.nextDouble();
System.out.println("Enter your operation");
oper = myScan.nextLine(); //<-- You were missing this.
if (oper.equals("+")) {
answer = fnum + snum;
...

You didn't ask the user to input an operation, therefore, your oper can't match any of the things you say later.

Related

How to make this calculator to only accept numbers in first two input's and loop till they are correct

Somehow I got operator looping till I get correct input. When i try to put num1 or num2 in "if" statement, It says that I cannot convert "int" to "boolean". Please help
public class main {
public static void main(String[] args) {
int num1;
int num2;
String operator;
Scanner scan = new Scanner(System.in);
System.out.print("tell me first number: ");
num1 = scan.nextInt(); //<--input only numbers, loop if not
System.out.print("tell me second number: ");
num2 = scan.nextInt(); //<--input only numbers, loop if not
//////////////////operator////////////////////////
System.out.print("tell me operator: ");
operator = scan.next();
while(true) {
if(operator.equals("+")) {
System.out.println("answer is: " +(num1 + num2));
break;
}
else if(operator.equals("-")) {
System.out.println("answer is: " +(num1 - num2));
break;
}
else if(operator.equals("*")) {
System.out.println("answer is: " +(num1 * num2));
break;
}
else if(operator.equals("/")) {
System.out.println("answer is: " +(num1 / num2));
break;
}
else {
System.out.print("wrong input! try again!: ");
operator = scan.next();
}
}
}
}
Try this.
System.out.print("tell me first number: ");
while (!scan.hasNextInt()) scan.next();
num1 = scan.nextInt();
System.out.print("tell me second number: ");
while (!scan.hasNextInt()) scan.next();
num2 = scan.nextInt();
System.out.print("tell me first number: ");
while (!scan.hasNextInt()) scan.next();
num1 = scan.nextInt();
System.out.print("tell me second number: ");
while (!scan.hasNextInt()) scan.next();
num2 = scan.nextInt();
With this, wrong answer was looping till i got correct input, but I could not get it to print me "Wrong Input! Try again!: " with wrong input without starting to loop infinitely, so i tried to edit and came up with this.
//////////////////first number////////////////////
System.out.print("tell me first number: ");
while(!scan.hasNextInt()) {
System.out.print("Wrong Input! Try again!: "); scan.next();
if(scan.hasNextInt() == true) {
}
}
num1 = scan.nextInt();
//////////////////second number///////////////////
System.out.print("tell me second number: ");
while(!scan.hasNextInt()) {
System.out.print("Wrong input! Try again!: "); scan.next();
if(scan.hasNextInt() == true) {
}
}
num2 = scan.nextInt();
Somehow it helped lol.
Thanks #英語は苦手 for help.

How to print error message when user enters anything that is not a double?

I am trying to create a Java program that reads a double value from the user, Printing the difference between these two numbers so that the difference is always positive. I need to display an Error message if anything other than a number is entered. Please help, thank you !!
When I run the program and enter the second double value nothing happens. I have also tried adding try and catch but I get errors saying num1 cannot be resolved to a variable :(
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
//Reads input
Scanner sc = new Scanner(System.in);
System.out.println ("Please enter a double vaule: ");
double num1 = Math.abs(sc.nextDouble());
System.out.println("Please enter a second double vaule: " );
double num2 = Math.abs(sc.nextDouble());
double total = 0;
double total2 = 0;
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1>num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
}
if ((num1 < num2)); {
total2 = ((num2 - num1));
System.out.println("The difference is "+ total2);
}
}else {
System.out.println("Wrong vaule entered");
}
}
}
You have the right idea. You just need to remove the semicolon (;) after the last if and properly nest your conditions:
if (sc.hasNextDouble()) {
num1 = sc.nextDouble();
if (num1 > num2) {
total = (num1 - num2);
System.out.println("The difference is " + total);
}
else if (num1 < num2) {
total2 = (num2 - num1);
System.out.println("The difference is "+ total2);
}
} else {
System.out.println("Wrong vaule entered");
}
Try running your code and when you enter your first double, type in something random like "abc". What happens? In your console it should display an error named java.util.InputMismatchException. You can use a try catch block like so:
try {
//tries to get num1 and num2
double num1 = Math.abs(sc.nextDouble());
double num2 = Math.abs(sc.nextDouble());
} catch (java.util.InputMismatchException i){
//will only go here if either num1 or num2 isn't a double
System.out.println("error");
}
Basically, the code will try to get num1 and num2. However if you enter a non-double, it'll "catch" the java.util.InputMismatchException and go to the catchblock
I might've misinterpreted your question, but if you want to find the absolute value of the difference between num1 and num2, all you have to do is:
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.println("Please enter a double value: ");
double num1 = sc.nextDouble();
System.out.println("Please enter a double value: ");
double num2 = sc.nextDouble();
System.out.println("The difference is: " + Math.abs(num1 - num2));
} catch (java.util.InputMismatchException i) {
System.out.println("error");
}
}
}
To show error message until the user enters a double value I used a while loop for each value (num1 and num2).
If user enters a wrong value "Wrong vaule entered, Please enter again: " message will show and waits for the next input sc.next();
If user enters a double value check will be false and exits while loop
import java.util.Scanner;
public class Positive {
public static void main(String[] args) {
// Reads input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a double vaule: ");
double num1 = 0;
double num2 = 0;
double total = 0;
double total2 = 0;
boolean check = true;
while (check) {
if (sc.hasNextDouble()) {
num1 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
check = true; // that's for second control
System.out.println("Please enter a second double vaule: ");
while (check) {
if (sc.hasNextDouble()) {
num2 = Math.abs(sc.nextDouble());
check = false;
} else {
System.out.println("Wrong vaule entered, Please enter again: ");
sc.next();
}
}
if (num1 > num2) {
total = ((num1 - num2));
System.out.println("The difference is " + total);
} else if ((num1 < num2)) {
total2 = ((num2 - num1));
System.out.println("The difference is " + total2);
}
}
}

Saving results into csv

Here is a copy of my code,
i expected to save the results of the below code into a csv, and also ask the user do you want to review the results? if yes then display the contents of csv saved.
import java.io.*;
import java.util.Scanner;
public class TestMathOP {
public static void main(String [] args) {
float num1;
float num2;
Scanner input = new Scanner (System.in);
char choice;
do
{
System.out.print ("Enter the first number:");
num1 = input.nextFloat();
System.out.print ("Enter the second number:");
num2 = input.nextFloat();
System.out.println();
System.out.println("The sum of the numbers is " + (num1 + num2));
System.out.println("The subtract of the two numbers is " + + (num1 - num2));
System.out.print("Do you want to exit? Y/N ");
choice = input.next().charAt(0);
}
while ((choice == 'n') || (choice == 'n'));
System.out.print("Thanks for using our system");
if ((choice == 'y') || (choice == 'y'));
}
}
This should work. I think like #AlexZam said, try to go step by step.
public static void main(String[]args) throws IOException{
//creates file
File file = new File("file.csv");
//Change to strings
String num1;
String num2;
Scanner input = new Scanner (System.in);
//your choice
boolean isNo = false;
boolean isYes = false;
do
{
//enables writing to file
FileWriter fileWriter = new FileWriter("file.csv");
Scanner scanner = new Scanner(file);
System.out.print ("Enter the first number:");
float calc1;
calc1 = input.nextFloat();
String firstNumber = calc1 + "";
//WRITES TO FILE
fileWriter.write(firstNumber+"\n");
System.out.print ("Enter the second number:");
float calc2;
calc2 = input.nextFloat();
String secondNumber = calc2+"";
//WRITES TO FILE
fileWriter.write(secondNumber +"\n");
String message = "The sum of the numbers is " + (calc1 + calc2) + "\nThe subtract of the two numbers is " + (calc1 - calc2);
System.out.println(message);
fileWriter.write(message);
//close filewriting
fileWriter.close();
String question = ("Do you want to exit? Y/N ");
System.out.print(question);
String answer = input.next();
if(answer.equals("y")) {
isYes = true;
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
}else if(answer.equals("n")) {
isNo = true;
System.out.println("Thanks for using our systems!");
}
} while (!isNo&&!isYes);
}

I made a CLI calculator and I am wondering, how can I have the program accept numbers indefinetly until the user inputs a stop command?

You probably understand that I am a beginner, and I know that we aren't really liked by the community.
I made a multi purpose calculator a while back and now I want to expand it. In this question I will be focusing only on one class.
import java.util.Scanner;
public class Calculator {
public static void calcMenu(Scanner input){
Scanner oper = new Scanner(System.in);
System.out.println("Please input the First number:");
double anum = input.nextDouble();
System.out.println("Please input on of the following operations:");
System.out.println("+");
System.out.println("-");
System.out.println("*");
System.out.println("/");
String equ = oper.nextLine();
System.out.println("Please input the Second number:");
double bnum = input.nextDouble();
switch (equ){
case "+":
System.out.println(anum + bnum);
break;
case "-":
System.out.println(anum - bnum);
break;
case "*":
System.out.println(anum * bnum);
break;
case "/":
System.out.println(anum / bnum);
break;
}
}
}
In this Java class, the program can solve equations only with two numbers. I would like to make it like in a standard calculator, where you can input the numbers as much as you want. I would like to do it until the user types something like "done" and the application will return to the main menu.
This is probably a very nooby question but please help. And if you want to see the whole application: here's the link
This will help you out! :)
import java.util.InputMismatchException;
import java.util.Scanner;
public class Calculator {
private static double answer;
private static boolean done = false;
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
try {
new Calculator().calcExpression();
} catch (InputMismatchException e) {
System.out.println("An error occurred. ");
}
}
private void calcExpression() throws InputMismatchException {
System.out.println("Enter Your Expression Here:");
System.out.print("Num: ");
double firstNum = in.nextDouble();
in.nextLine();
while (!done) {
System.out.print("Operator: ");
String operand = in.nextLine();
if (operand.equals("=")) {
break;
}
System.out.print("Num: ");
double secondNum = in.nextDouble();
in.nextLine();
calculate(firstNum, operand, secondNum);
firstNum = answer;
}
System.out.printf("Answer is %.2f", answer);
}
private void calculate(double num1, String equ, double num2) {
switch (equ)
{
case "/":
answer = (num1 / num2);
break;
case "*":
answer = (num1 * num2);
break;
case "+":
answer = (num1 + num2);
break;
case "-":
answer = (num1 - num2);
break;
case "=":
done = true;
break;
}
}
}

java calculator loop not working properly

For some reason my calculator won't wait for user input to finish the do while loop. I'm very new to java coding (currently only been doing it for a few hours). I want the user to be able to do more math before the program closes instead of having to reopen it every time they want to use it (obviously I don't mean anything serious by this I just want to learn and I think this will help.
heres my code
import java.util.Scanner;
public class calculator {
public static void main(String[] args){
double Answer;
String op;
double num1;
double num2;
String again;
boolean yesorno = true;
Scanner input = new Scanner(System.in);
while (yesorno = true){
System.out.print("What opperation would you like to preform? +,-,*,/, :");
op = input.nextLine();
System.out.print("What is the first number? : ");
num1 = input.nextDouble();
System.out.print("And the seccond number? : ");
num2 = input.nextDouble();
if (op.equals("+")) {
Answer = (num1 + num2);
System.out.println(Answer);
} else if (op.equals("-")) {
Answer = num1 - num2;
System.out.println(Answer);
} else if (op.equals("*")) {
Answer = num1 * num2;
System.out.println(Answer);
} else if (op.equals("/")) {
Answer = num1 / num2;
System.out.println(Answer);
}
System.out.println("Would you like to do any more math?");
again = input.nextLine();
if (again.equals("yes")) {
yesorno = true;
} else if (again.equals("no")) {
yesorno = false;
System.out.print("have a good day!");
}
} while (yesorno = true);
}
}
please ignore the akward formatting at the beggining and end of this code.
1) while(yesorno = true ) you are doing assignation
change to
while(yesorno == true) to prevent this thing you can use yoda style while(true = yesorno) then a compile error would throw cause you can't assign something to a value.
Or even more simpler just use while(yesorno)
2) Follow Java Code Convention , variable names are in lower case.
3)if this block get executed while (yesorno = true); you will have an infinite loop.
4) If you are using java 7 , you can do switch over strings
switch(op){
case "+":answer = num1 + num2;break;
case "-":answer = num1 - num2;break;
case "*":answer = num1 * num2;break;
case "/":answer = num1 / num2;break;
default: throw new IllegalArgumentException("Invalid operation "+ op);
}
System.out.println(answer);
You are assigning, not testing for equality in while (yesorno = true){. You should use while (yesorno == true){, since the double equals (==) tests for equality.
There were many errors, I have fixed it and commented it for you. Hope it helps:
import java.util.Scanner;
// KK: by general convention class names should always start with an upper case letter
public class calculator {
public static void main(String[] args) {
double Answer; //KK: local variable should be lower case
String op;
double num1;
double num2;
String again;
boolean yesorno = true;
Scanner input = new Scanner(System.in);
//KK: for comparing you need the double-equals
//KK: the loop will be executed as long as the expression is true, so for a boolean you don't need it at all
//KK: you can use either of the following:
// while (yesorno == true)
// while (yesorno)
while (yesorno) {
System.out.print("What opperation would you like to preform? +,-,*,/, :");
op = input.nextLine();
System.out.print("What is the first number? : ");
num1 = input.nextDouble();
System.out.print("And the seccond number? : ");
num2 = input.nextDouble();
if (op.equals("+")) {
Answer = (num1 + num2);
System.out.println(Answer);
} else if (op.equals("-")) {
Answer = num1 - num2;
System.out.println(Answer);
} else if (op.equals("*")) {
Answer = num1 * num2;
System.out.println(Answer);
} else if (op.equals("/")) {
Answer = num1 / num2;
System.out.println(Answer);
}
System.out.println("Would you like to do any more math?");
//KK: you need to call nextLine twice because you printed 2 lines here
//KK: otherwise again will be empty, so yesorno will always be true and you have an endless loop
again = input.nextLine();
again = input.nextLine();
if (again.equals("yes")) {
yesorno = true;
} else if (again.equals("no")) {
yesorno = false;
System.out.print("have a good day!");
}
}
// KK: the following line was an empty loop, that didn't do anything, so I commented it
// while (yesorno = true);
}
} //KK: this one was missing at the end too ;)
(I started my comments with KK, so you see them and can remove them later.)
Try this....
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean status = true;
while(status){
String answer = "";
String choise = "";
System.out.println("\"WELCOME TO JAVA CALCULATOR\"");
Scanner scn = new Scanner(System.in);
Scanner cal = new Scanner(System.in);
Scanner cho = new Scanner(System.in);
System.out.println("Enter the numers one by one that you want to calculate..");
int numA = scn.nextInt();
int numB = scn.nextInt();
int result = 0;
System.out.println("What you want to calculate...?");
answer = cal.nextLine();
if(answer.equals("+")){
result = numA+numB;}
if(answer.equals("-")){
result = numA-numB;}
if(answer.equals("*")){
result = numA*numB;}
if(answer.equals("/")){
result = numA/numB;}
System.out.println( "The result of " + numA + " and " + numB + " is : " + result);
System.out.println("Do you want to continue.....(y) or (n)?");
choise = cho.nextLine();
if(choise.equalsIgnoreCase("y")){
System.out.println("Welcome back.....:)\n\"Make By Saikat Halder\"");
status = true;}
if(choise.equalsIgnoreCase("n")){
System.out.println("Good bye....Thanks for useing java Calculator......:)");
System.exit(0);
}
}
}
}

Categories

Resources