Simple Calculator: Addition wrong output [duplicate] - java

This question already has answers here:
Java printing a String containing an integer
(9 answers)
Closed 4 years ago.
I'm a beginner and I am trying to make a simple calculator in java. Everything works fine except for Addition has wrong output (e.g. 1+1 = 1.01.0). Here is a sample of my code
package Package;
import java.util.Scanner;
public class SimpleCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Equation:");
double num1 = input.nextDouble();
String oper = input.next();
String plus, minus, divide, modulus, multiply;
plus = "+";
minus = "-";
divide = "/";
multiply = "*";
modulus = "%";
//Everything is the same but addition seems to have wrong output
if (oper.equals(plus))
{
double num2 = input.nextDouble();
System.out.println("= " + num1 + num2);
}
else if (oper.equals(minus))
{
double num2 = input.nextDouble();
System.out.println(num1 - num2);

You are printing the Strings num1 and num2, not the result of the calculation.
When you print out a string ("=" in your case), Java will treat any number added to it as Strings as well).
To solve this, just add your calculation into parentheses to allow Java to calculate them separately:
System.out.println("=" + (num1 + num2));

Related

Printing The Result of a Division Between Two Doubles only if the second value is different from zero

I'm trying to make a Java program that takes two doubles in input, divides them and then prints out the result of the division. However, if the second double that it takes as input is zero, I want the program to keep asking the user to insert another number, for as long as the user gives as input to the program a number that is different from zero.
I tried to translate into Java code this idea, but I've never really gotten the result I wanted. So far, the code I've written is the following:
import java.util.Scanner;
public class DoubleDivision {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first number that you want to divide: ");
double numerator = scan.nextDouble();
System.out.println("Enter the second number that you want to divide: ");
double denominator = scan.nextDouble();
do {
System.out.println("Enter the second number that you want to divide: ");
double denominator1 = scan.nextDouble();
} while (denominator == 0);
double fraction = numerator/denominator;
System.out.println("The result of the division is: " + fraction);
scan.close();
}
}
I tried to use a do-while loop, but I'm afraid I somehow failed at implementing it properly.
Is there anyone who might be able to give me some piece of advice? I'm kinda a beginner in the coding world.
Thank you very much!
You used another variable to compare the scanner result, denominator1 is set but then the other variable is used for the do while loop
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first number that you want to divide: ");
double numerator = scan.nextDouble();
double denominator;
do {
System.out.println("Enter the second number that you want to divide: ");
denominator = scan.nextDouble();
} while (denominator == 0);
double fraction = numerator/denominator;
System.out.println("The result of the division is: " + fraction);
scan.close();
You were close. Here are my test results.
Enter the first number that you want to divide:
1
Enter the second number that you want to divide:
0
Enter the second number that you want to divide:
3
The result of the division is: 0.3333333333333333
Here's the code with the changes made. A while loop would have been more natural, but I kept your do-while loop.
import java.util.Scanner;
public class DoubleDivision {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first number that you want to divide: ");
double numerator = scan.nextDouble();
double denominator;
do {
System.out.println("Enter the second number that you want to divide: ");
denominator = scan.nextDouble();
} while (denominator == 0);
double fraction = numerator / denominator;
System.out.println("The result of the division is: " + fraction);
scan.close();
}
}
The mistake in your do-while is that you are reading the value into a different variable (i.e. denominator1) than the one you are testing (denominator). In fact, you are using a variable whose scope is limited to the body of that do-while. Simple solution is to use the variable you had already defined for the denominator.
double denominator = 0.0;
do {
System.out.println("Enter the second number that you want to divide: ");
denominator = scan.nextDouble();
} while (denominator == 0.0);
I would suggest that you modify the prompts to inform the user that they are entering the numerator and denominator respectively. IF they enter a 0.0 for denominator then tell them what's wrong before repeating the prompt. In this example, I put it in a separate method.
private void readDenominator() {
System.out.println("Enter the denominator: ");
denominator = scan.nextDouble();
while (denominator == 0.0) {
System.out.println("Cannot divide by zero. Enter the denominator: ");
denominator = scan.nextDouble();
}
}

Adding numbers in GUI giving unexpected result?

The following is a simple code that takes in two numbers and adds them in a gui. For some reason the output is not the sum of the two numbers, but is instead a random number. Please tell me what is going on. Here is my code:
import javax.swing.JOptionPane;
public class GUI {
public static void main(String[] args) {
String fn = JOptionPane.showInputDialog("Enter first number");
String sn = JOptionPane.showInputDialog("Enter second number");
int num1 = Integer.parseInt(fn); //Converts a string into an integer, since showInputDialog can only take in a string
int num2 = Integer.parseInt(fn);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null, "The answer is "+sum, "This is the title", JOptionPane.PLAIN_MESSAGE);
}
}
For example, if I enter the first and second numbers as 5 and 6 respectively, instead of an outcome of 11 I get an outcome of 10. Any help would be appreciated.
It shouldn't be a random number, it should be double the first number because num2 is also fn
int num2 = Integer.parseInt(fn);
This is likely a typo and should be:
int num2 = Integer.parseInt(sn);
Things like this are why you should name variables properly. ie. firstNumber and secondNumber it improves readability vastly and will likely result in it being easier to spot typos like this.

( Java) When I enter a non-number (NaN) my program loops infinitely where is supposed to exit. [duplicate]

This question already has answers here:
How do you test to see if a double is equal to NaN?
(7 answers)
Closed 8 years ago.
The code is supposed to keep accepting numbers >-10 for as long as you enter them. Then when you are ready to exit you just enter anything other than a number and it is supposed to take the mean value of the sum of the numbers recorded and print the value, then exit.
When I enter a non-number (NaN) my program loops infinitely and I can't figure out how I can keep this from happening.
Program so far:
package project1;
import java.util.Scanner;
public class mean
{
public static void main(String[] args)
{
System.out.println("Enter the Temperature: ");
Scanner input = new Scanner(System.in);
double value=0.0;
double sum=0;
int i=0;
//This infinitely loops when a non Double value is entered. WHY!?!?!?
while(value != Double.NaN) {
value = averageTemperature(input, -10);
sum += value;
i++;
System.out.println("I've been here " + i + " time(s)");
if (value == Double.NaN){
break;
}
}
double mean = sum / i;
System.out.println("The average temperature is: " + mean);
}
public static double averageTemperature(Scanner input, double lowestTemp)
{
double temp = 0.0;
if (input.hasNextDouble()) {
temp = input.nextDouble();
if(temp >= lowestTemp){
return temp;
}
else if (temp < lowestTemp)
{
System.out.println("Invalid temperature. Please Re-enter: ");
return averageTemperature(input,lowestTemp);
}
}
return Double.NaN;
}
}
By definition, NaN is not equal to anything, including itself. Thus
while(value != Double.NaN) {
doesn't work as you'd expect. Use Double.isNaN() instead.
When I enter a non-number (NaN)...
Just to be clear with the terminology, "a non-number" and not-a-number are not the same thing:
a non-number can be pretty much anything, e.g. an alphanumeric string;
a not-a-number (NaN) is a specific IEEE 754 floating-point value.

How to recognize what math operation I am inputing? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 8 years ago.
I am trying to make a simple calculator which can add, substract, divide and multiply any two numbers.
The way it works is that I ask for a number, then I ask for a sign (+,-,*,/) , and then I ask for the second number. The math should be done accordingly afterwards.
However I can't get the 'math sign' to be recognized properly by the program.
Here is my code:
package practice1;
import java.util.Scanner;
public class maiin {
public static void main(String[] args){
System.out.println("it works.");
double num1;
double num2;
String sign;
double total;
System.out.println("Please enter a number: ");
Scanner input = new Scanner(System.in);
num1 = input.nextDouble();
System.out.println("Enter a +,-,/,* sign: ");
sign = input.nextLine();
input.nextLine();
System.out.println("Enter another number: ");
num2 = input.nextDouble();
if (sign.equals("+")){
total = num1 + num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("-")) {
total = num1 - num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("/")) {
total = num1 / num2;
System.out.println("Your total is: " + total);
} else if (sign.equals ("*")) {
total = num1 * num2;
System.out.println("Your total is: " + total);
} else {
System.out.println("Please enter the a proper sign");
}
When I run the program, I always get "Please enter the a proper sign".
Thank you in advanced.
I think you need to change
sign = input.nextLine();
input.nextLine();
to
sign = input.nextLine();
sign.nextLine();

Reading a char from Scanner [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
Sorry for the noob question. This is my first day trying out Java programming. I need help retrieving the users input of which operator the user wants to use with integers.
import java.util.Scanner;
public class calculator {
public static void main (String args[]) {
Scanner number = new Scanner(System.in);
double num1,num2,answer;
char operator;
System.out.println("Enter first number: ");
num1 = number.nextDouble();
operator = number.nextChar(); /* the "nextChar" is not correct */
System.out.println("Enter second number: ");
num2 = number.nextDouble();
if (operator = '+'){
answer = num1 + num2; /* If statements do not work like this */
} /* I would use "else if", unsure if it allows */
if (operator = '-'){
answer = num1 - num2;
}
if (operator = '*'){
answer = num1 - num2;
}
if (operator = '/'){
answer = num1 / num2;
}
System.out.println(num1 + num2 + operator + answer);
}
}
Edited Version:
import java.util.Scanner;
public class calculator{
public static void main (String args[]) {
Scanner userInput = new Scanner(System.in);
String operator;
double num1,num2,answer = 0;
System.out.println("Enter first number: ");
num1 = userInput.nextDouble();
System.out.println("Enter operator: ");
operator = userInput.next();
System.out.println("Enter second number: ");
num2 = userInput.nextDouble();
if (operator.equals ("+")){
answer = num1 + num2;
}
else if (operator.equals ("-")){
answer = num1 - num2;
}
else if (operator.equals ("*")){
answer = num1 * num2;
}
else if (operator.equals ("/")){
answer = num1 / num2;
}
System.out.println("First number:" + num1);
System.out.println("Operator:" + operator);
System.out.println("Second number:" + num2);
System.out.println("Answer: " + answer);
}
}
First number:10.0
Operator:*
Second number:3.14
Answer: 31.400000000000002
Thanks a lot guys! Helped a lot!
Ok. This works and can help you on your road to java
public class Tester4 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
double num1, num2, answer = 0;
String operator;
System.out.println("Enter first number: ");
num1 = input.nextDouble();
System.out.println("Enter operator: ");
operator = input.next();
System.out.println("Enter second number: ");
num2 = input.nextDouble();
if(operator.equals("+")) {
answer = num1 + num2;
} else if(operator.equals("-")) {
answer = num1 - num2;
} else if(operator.equals("*")) {
answer = num1 - num2;
} else if(operator.equals("/")) {
answer = num1 / num2;
}
System.out.println("First number:" + num1);
System.out.println("Operator:" + operator);
System.out.println("Second number:" + num2);
System.out.println("Answer: " + answer);
}
}
Use == in comparisons, not = (that means assignation).
As other have already pointed out, use the == operator to check for equality. The = operator will assign values instead.
In order to read a single character from the Scanner, take a look at the following question: Scanner method to get a char. There you'll find the suggestion to use Scanner.findInLine() method, which receives a regular expression as an argument. Providing the . wildcard character as pattern, you'll be able to get a String with the one next character, and using charAt(0) on it, you'll get it as a char.
Scanner sc = new Scanner("abc");
char ch = sc.findInLine(".").charAt(0);
System.out.println(ch); // prints "a"
Of course, you could also just use Scanner.next() to get the next word as a String, and just get its first character. But take into account that doing so would discard from the input buffer the rest of the word.
You need to use
if (operator == '+')
Notice the 'double equal to'.

Categories

Resources