java calculator loop not working properly - java

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);
}
}
}
}

Related

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);
}
}
}

Scanner skipping nextLine(); after do while loop

as you can probably see I am a newbie in java. Below is a simple calculator program which asks for the user to input a symbol such as + or -. The user then inputs 2 numbers and depending on the operator symbol chosen a method will be called. A do while loop allows the user to repeat the process. The problem is that after the program loops, the following line: "String symb = inp.nextLine();" is skipped. I have already tried searching for a solution however I only found a fix if the nextLine is called after nextInt. Thank you in advance for your patience.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inp = new Scanner(System.in);
Methods operation = new Methods();
boolean loop = false;
do {
System.out.println("Enter an operator symbol - +, -, * or /");
String symb = inp.nextLine(); //this is the line which is skipped
System.out.println("Enter a number");
int num1 = inp.nextInt();
inp.nextLine();
System.out.println("Enter a second number");
int num2 = inp.nextInt();
inp.nextLine();
switch(symb) {
case "+" :
operation.setA(num1);
operation.setB(num2);
int totalAddition = operation.addNums(num1,num2);
System.out.println("The result is - " + totalAddition);
break;
case "-" :
operation.setA(num1);
operation.setB(num2);
int totalSubtract = operation.subtractNums(num1,num2);
System.out.println("The result is - " + totalSubtract);
break;
case "*" :
operation.setA(num1);
operation.setB(num2);
int totalMult = operation.multNums(num1,num2);
System.out.println("The result is - " + totalMult);
break;
case "/" :
operation.setA(num1);
operation.setB(num2);
int totalDiv = operation.divNums(num1,num2);
System.out.println("The result is - " + totalDiv);
break;
}
System.out.println("Would you like to exit? Y/N");
char ans = inp.next().charAt(0);
if(ans == 'Y' || ans == 'y') {
loop = true;
inp.close();
System.exit(0);
}
else {
loop = false;
}
}
while(loop == false);
}
}

Java Beginner, Why does my Program keep terminating?

Trying To create a calculator, Done a lot of this before about 4 years ago and just getting back into java. It just keeps terminating, it doesn't print out anything, runs for approx 5 seconds then terminates. Any help would be much appreciated.
EDIT: The problem was with the main function. The problem is fixed, thank you!
Adding the OOJCalculation code for those wanting to laugh at my stupidity more
public class OOJCalculation {
int Calculation (int Num1, int Num2, String Function,int Num3){
if(Function == "+"){
Num1 += Num2 = Num3;
return Num3;
}
else if(Function == "-"){
Num1 -= Num2 = Num3;
return Num3;
}
else if(Function == "*"){
Num1 *= Num2 = Num3;
return Num3;
}
if(Function == "/"){
Num1 /= Num2 = Num3;
return Num3;
}
return Num3;
}
}
public class Main {
public static void main(){
int State = 0;
int Num1 = 0;
int Num2 = 0;
String Function = "";
Scanner reader = new Scanner(System.in);
OOJCalculation calc = new OOJCalculation();
while(State < 5){
if(State == 0){
System.out.println("Enter first number.");
Num1 = reader.nextInt();
State++;
}
if(State == 1){
System.out.println("Enter the function.");
Function = reader.next();
State++;
}
if(State == 3){
System.out.println("Enter the second number.");
Num2 = reader.nextInt();
State++;
}
if(State == 4){
calc.Calculation(Num1, Num2, Function);
System.out.println(calc);
}
}
}
}
As the jls state :
The method main must be declared public, static, and void. It must specify a formal parameter (ยง8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:
public static void main(String[] args)
So your program is not running because it can't find the main.
EDIT :
Just saying about your code, the loops and conditon are not necessay.
public static void main(String[] args ) {
int State = 0;
int Num1 = 0;
int Num2 = 0;
String Function = "";
Scanner reader = new Scanner(System.in);
System.out.println("Enter first number.");
Num1 = reader.nextInt();
reader.nextLine(); //Read the <enter> key
System.out.println("Enter the function.");
Function = reader.nextLine();
System.out.println("Enter the second number.");
Num2 = reader.nextInt();
System.out.println(Num1 + Function + Num2);
}
Your main method is missing mandatory argument:
public class Main {
public static void main(String[] args){
....
}
}
Secondly it will be terminating, because it will reach the end of the block, and then have no more instruction to run.
Your OOJCalculation method is invalid:
int calculation(int num1, int num2, String function) {
if ( "+".equals(function)) {
return num1 + num2;
} else if ( "-".equals(function)) {
return num1 - num2;
} else if ( "*".equals(function)) {
return num1 * num2;
}else if ( "/".equals(function)) {
return num1 / num2;
}
throw new IllegalArgumentException("Unknown operator");
}
it should start with lowerCase. Use also lov\wwer case for variables. CamelCase are reserved for class names and constructors. You have also wrongly declared returned type. Above implementation is covorrected.

reference to println is ambiguous error

i have code a very basic program than when i do type System.out.println, i get thes error: "reference to println is ambiguous" and the occured randomly it use to work and did not have a erroe but now it does and i cant figure this error occurs, so how do i fix this ,than you.
package blue.light;
//name is: slash
import java.util.*;
public class BlueLight {
public static void main(String[] args) throws InterruptedException {
Scanner scan = new Scanner(System.in);
String name;
int age;
String a;
String yes;
String no;
double num1;
double num2;
double ans;
System.out.println("hello, my name is Slash");
System.out.println("What is your name?");
name = scan.nextLine();
System.out.println("Hello " + name);
Thread.sleep(1000);
System.out.println("How old are you?");
age = scan.nextInt();
if(age < 18)
{
System.out.println("ur young af");
}
else if (age == 21)
{
System.out.println("Shots, shots, shots");
}
else if (age == 69)
{
System.out.println("ohhh yea");
}
System.out.println("you to calculate any thing?");
a = scan.nextLine();
if(a==("yes")){
System.out.println("What would u like to do?(multiply,or add)");
a = scan.nextLine();
if(a == "add"){
System.out.println("Enter number 1");
num1 = scan.nextDouble();
System.out.println("Enter number 2");
num2 = scan.nextDouble();
ans = num1+num2;
}
}
}
}
First, nextInt() doesn't consume the new line after the age (so your nextLine is then empty). You compare Object values with a call to .equals() because == tests reference identity (and with a String I'd use String.equalsIgnoreCase(String)). Finally, I'd declare the variables with minimum visibility in Java; as close to their first use as possible. Something like,
public static void main(String[] args) throws InterruptedException {
Scanner scan = new Scanner(System.in);
System.out.println("hello, my name is Slash");
System.out.println("What is your name?");
String name = scan.nextLine();
System.out.println("Hello " + name);
Thread.sleep(1000);
System.out.println("How old are you?");
int age = scan.nextInt();
if (age < 18) {
System.out.println("ur young af");
} else if (age == 21) {
System.out.println("Shots, shots, shots");
} else if (age == 69) {
System.out.println("ohhh yea");
}
System.out.println("you to calculate any thing?");
scan.nextLine(); // <-- nextInt leaves a trailing new line.
String a = scan.nextLine();
if (a.equalsIgnoreCase("yes")) { // <-- compare string for equality in
// Java
System.out.println("What would u like to do?(multiply,or add)");
a = scan.nextLine();
if (a.equalsIgnoreCase("add")) {// <-- compare string for equality
// in Java
System.out.println("Enter number 1");
double num1 = scan.nextDouble();
System.out.println("Enter number 2");
double num2 = scan.nextDouble();
double ans = num1 + num2;
System.out.println(ans); // <-- display answer
}
}
}

Having trouble the .equals in 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.

Categories

Resources