Add two numbers instead of combining - java

I am trying to create a program in which a user can enter 2 numbers and the program will take the 2 numbers and multiply them to get an answer. However, for this specific example, I am simply trying to take 2 numbers from a user and I want Java to add them. eg 1+1=2, instead of 1+1=11.
My code:
import javax.swing.JOptionPane;
public class MultiplicationTables {
public static void main(String args[]) {
//declare variables
String num1;
String num2;
int ans=0;
num1=JOptionPane.showInputDialog(null,"Enter a number");
num2=JOptionPane.showInputDialog(null,"Enter another number");
ans=Integer.parseInt(num1);
ans=Integer.parseInt(num2);
JOptionPane.showMessageDialog(null,"Your answer is " + (num1+num2));
}
}

num1 and num2 are String.
So as you write num1+num2 you get the result of their concatenation.
In fact, you don't use the Integer.parseInt(); results.
Instead, do it to addition two int values:
int result = Integer.parseInt(num1) + Integer.parseInt(num2);
And display result :
JOptionPane.showMessageDialog(null,"Your answer is " + result);

You are using num1 and num2 which are Strings instead of ans which should be your sum as an int.
Also you don't add correctly the 2 values into ans.
public static void main(String args[]){
String num1 = JOptionPane.showInputDialog(null,"Enter a number");
String num2 = JOptionPane.showInputDialog(null,"Enter another number");
int ans = Integer.parseInt(num1);
ans += Integer.parseInt(num2);
JOptionPane.showMessageDialog(null,"Your answer is " + ans);
}

Here:
num1=JOptionPane.showInputDialog(null,"Enter a number");
num2=JOptionPane.showInputDialog(null,"Enter another number");
The option pane returns strings, what you seem to understand, as you then go:
ans=Integer.parseInt(num1);
ans=Integer.parseInt(num2);
But then you use the + operator on your string results:
... +(num1+num2));
But + for strings concatenates them.
So instead of "adding" strings, you want to add the numbers, as in:
int1FromUser = Integer.parseInt(num1);
int2FromUser = Integer.parseInt(num2);
int sum = int1FromUser + int2FromUser;
That is all there is to this.
( and I took the freedom to use slightly better naming - keep in mind to use variable names that say something about the meaning of the thing they point to )

You are doing it wrong. You are adding Strings in the end and ignoring the parsed Integers.
And also you using the same integer variable for both inputs.
So that should be
int ans1=0;
int ans2=0;
...
ans1=Integer.parseInt(num1);
ans2=Integer.parseInt(num2);
And in the end
JOptionPane.showMessageDialog(null,"Your answer is " +(ans1+ans2));

+ is used in addition when using Integer or int, and it also used to concatenate two Strings. In your case num1 and num2 are Strings, and hence it is concatenating the result. So you will have to change your code to reflect following changes:
ans = Integer.parseInt(num1);
ans += Integer.parseInt(num2); // add the result of parseInt to ans
//--^---------------------------
JOptionPane.showMessageDialog(null,"Your answer is " + ans ); // another one
Or alternatively:
JOptionPane.showMessageDialog(null,"Your answer is " + (Integer.parseInt(num1) + Integer.parseInt(num2)));

I'd suggest you change the last line of your method to:
JOptionPane.showMessageDialog(null,"Your answer is " + (Integer.parseInt(num1) + Integer.parseInt(num2)));
This way, you don't need the "ans" variable (which in your code doesn't really do anything) at all. Instead, you can simply parse the int values and add them on the same line as you're writing the message.
If you want to use ans, try this:
ans = Integer.parseInt(num1) + Integer.parseInt(num2);
Then:
JOptionPane.showMessageDialog(null,"Your answer is " + ans);

Related

How would I check If two user inputs only contains numbers(calculator program), I keep getting a runtime error

Hi I'm still new to java and I would like to know how to check if the user only input numbers and not letters my problem comes in when I had to parse the input from string to double to be able to add decimals together in the console. But when I googled to see how to check if my input is only numbers I had to take in a string input that gives me *2 inputs(hope I'm making sense).Is there maybe a easier version to do this or am I missing something.
public class javaCalculator {
public static void main(String[] args){
//initializing two scanners for numbers and operations and creating 3 variables
Scanner numbers = new Scanner(System.in);
Scanner operation = new Scanner(System.in);
double number1;
double number2;
String operator;
//getting user input for the type of operations and numbers they want to enter
System.out.print("Enter the operator you would like to choose(+, -, *, /): ");
operator = operation.next();
//My program didn't want to take decimals, so I had to parseDouble which takes the input as a string and then
//converts(parse) it to a double which then makes my program run with decimal numbers
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
number1 = Double.parseDouble(numbers.nextLine());
System.out.print("Enter your second number: ");
String num2 = numbers.nextLine();
number2 = Double.parseDouble(numbers.nextLine());
boolean check1 = num1.matches("[0-9]+");
boolean check2 = num2.matches("[0-9]+");
if (check1 == true && check2 == true){
System.out.println("...");
}else {
System.out.println("Only enter numbers not letters.");
}
//Using if else statements to check what operation was chosen above and then depending on
//that choice(+, -, *, /) printing a suitable answer to console
//Creating a calculation variable to use in the writing to a file
String calculation;
if (operator.equals("+")){
calculation = (number1 + " + " + number2 + " = " + (number1 + number2));
System.out.println(calculation);
}else if (operator.equals("-")){
calculation = (number1 + " - " + number2 + " = " + (number1 - number2));
System.out.println(calculation);
}else if (operator.equals("*")){
calculation = (number1 + " * " + number2 + " = " + (number1 * number2));
System.out.println(calculation);
}else if (operator.equals("/")){
calculation = (number1 + " / " + number2 + " = " + (number1 / number2));
System.out.println(calculation);
}else{
calculation = operator + ":" + " Is not a valid operator!";
System.out.println(calculation);
}
Your code is trying to read the same number twice:
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
number1 = Double.parseDouble(numbers.nextLine());
What you should do is read the number as a string, confirm that it is a number and then parse it only if it matches.
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
boolean check1 = num1.matches("[0-9]+");
if(check1){
number1 = Double.parseDouble(num1);
}
else{
//Error handling
}
Alternatively you can simply try to parse the string directly and catch the exception i.e.
System.out.print("Enter the first number: ");
String num1 = numbers.nextLine();
try{
number1 = Double.parseDouble(num1);
} catch(NumberFormatException e){
//Error handling
}
Your approach is OK. Although Scanner lib provides the nextDouble() method I recommend using the regular expression control you are using. Even though there are some little things to fix:
You are parsing (convert from String to double) first, and then checking format. If for example, the user enters a letter your program will fail when parseDouble tries to convert the String to double. So, read the String from the input, apply the match control, and if there is no Error then parse.
Your regular expression is matching any String that has 1 or more numbers. For example, the input Hello1 will match because there is at least one number. Then the parse will fail because Hello1 is not a valid number. You have to use a regular expression that matches only numbers. This expression will look like this: "^[0-9]+$"
The ^ character means that the expression must match at the beginning of the line, and the $ character force that the expression match at the end of the line. In other words, this expression should have numbers from the beginning to the end of the string. It would be a good thing to add a .trim() (num1.trim().matches("[0-9]+");) to delete any extra white space at the beginning or at the end.
The third recommendation is that if you don't want to use decimals may be Double type is not the proper data type to use. Double can represent decimals. The proper type should be Integers.
number1 = Integer.parseInt(num1);
#christopher When you raise error you are printing a message but the program keeps running. That's why you get the Error commented on #Turamarth solution comment

Java: can't get .equals() to work

I want to make a basic game where two random numbers are generated and the user has to enter the correct product.
What am I doing wrong? thanks
import java.util.Scanner;
import java.awt.*;
public class Userinput {
public static void main (String[] args) {
String firstName;
//Create scanner to obtain user input
Scanner scanner1 = new Scanner( System.in );
int a, b, correctAnswer;
a=(int) (Math.random()*10);
b=(int) (Math.random()*10);
//obtain user input
System.out.println("Enter your first name: ");
firstName = scanner1.nextLine();
//output information
System.out.print("Hello " + firstName + " ");
System.out.println("what is " + a +" times " + b);
String answer1 = scanner1.nextLine();
correctAnswer = a * b;
if ((answer1).equals(correctAnswer))
System.out.println("Correct!");
else if (!(answer1).equals ("correctAnswer"));
System.out.println("Incorrect!");
}
}
You are comparing a String (answer1) to an Integer (correctAnswer). That's comparing apples and oranges, they are never the same.
You need to either convert the String to an int:
Integer.parseInt(answer1)
which might fail if answer1 can't be parsed as an integer; or convert the int to a String:
Integer.toString(correctAnswer)
and then compare them:
Integer.parseInt(answer1) == correctAnswer // You can use == because int is primitive.
or
answer1.equals(Integer.toString(correctAnswer))
Try this:
int answer1 = scanner1.nextInt();
int correctAnswer = a*b;
if (answer1==correctAnswer) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
There were a few issues with your code, mostly related to mixing up Strings and ints. Here is a good explanation of how to compare different data types. I would recommend that you use Scanner.nextInt() to save you having to cast Strings to integers.
I would also recommend that you do not omit the braces in your if statements. It makes your code easier to read and can avoid some confusion, especially when you are just starting out with Java.
This is where the problem is:
if ((answer1).equals(correctAnswer))
System.out.println("Correct!");
else if (!(answer1).equals ("correctAnswer"));
System.out.println("Incorrect!");
}
Do this instead:
Integer answer = Integer.parseInt( answer1 );
if (answer1.equals(correctAnswer)) {
System.out.println("Correct!");
} else {
System.out.println("Incorrect!");
}
The way that it is currently written, "Incorrect!" would always be printed, because of the semi-colon on the else if. Also, it was comparing answer1 with the literal String "correctAnswer" because of the quotes. Since they're not even the same type (int and String), equals(...) returns false. I would also suggest using curly braces. It helps to alleviate some of these issues.

Calculator int choice = Integer.parseInt(char_a); java

Trying to create a simple calculator on java. No errors show up in the code. But it still doesn't work at all. am I missing anything?
import java.util.Scanner;
public class JavaApplication15 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("This is a calculator. Enter a letter followed by a number to calculate it.");
System.out.println(" S = sine \n C = Cosine \n T = Tangent \n R = Square Root \n N = natural Log \n X = exit the program");
String num = in.nextLine();
String sValue = num.substring(2);
String char_a = num.substring(0);
int choice = Integer.parseInt(char_a);
double dValue = Double.parseDouble(sValue);
while (choice != 'x'){
switch(choice){
case 's':
Math.sin(dValue);
System.out.println("The sine of your number is " + dValue);
break;
case'c':
Math.cos(dValue);
System.out.println("The Cosine of your number is " + dValue);
break;
case't':
Math.tan(dValue);
System.out.println("The Tangent of your number is " + dValue);
break;
case'r':
Math.sqrt(dValue);
System.out.println("The square root of your number is " + dValue);
break;
case'n':
Math.log(dValue);
System.out.println("The Log of your number is " + dValue);
break;
case'x':
break;
}
}
}
}
I think I see your error.
You're performing operations using the Math class but aren't assigning the result of the operation back to your variable.
For example, Math.cos(dValue); should probably be dValue = Math.cos(dValue);
There are a few problems with your code.
Firstly, you are not using .substring method correctly. It returns everything from the index you specify to the end of your String. So for a user input of "S 4"
sValue equals to "4", but char_a equals to "S 4".
The way you use substring method is:
value = input.substring(2);
operation = input.substring(0,1);
I would actually suggest that you use something like:
params = input.split(" ");
Then you have:
params[0] // as your command
and
params[1] // as your value
This way you don't have to worry about how many symbols each bit actually takes up.
Next, don't convert your command to char like this. My previous suggestion means you should really be using something like
if (params[0].equals("sin")) {
} else if (params[0].equals("cos")) {
} else {
// catch unknown command
}
However, you can convert to char simply by:
sValue.toCharArray()[0]
Also, there is no reason why your switch statement should be in a while loop. There is nothing to be done continuously, it will just keep printing the same answers. And lastly, ajb said, you calculate the values and throw them away, whilst printing the old value. You have to use:
System.out.println("The Tangent of your number is " + Math.tan(dValue));

Simple java console calculator

Without directly giving me the answer can someone help me with this simple calculator that I am trying to write?
Everything seem to work well except for the very end when I ask the user to make a choice for add,subtract, multiply, or divide. It does not allow me to enter my choices in the console.
I think it has something to do with the array of String that I created and the if statement. Not sure. Any tips would be much appreciated.
import java.util.Scanner;
public class simpleCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//declare my variables
int firstNum;
int secondNum;
int division = 0, addition = 0, subtraction = 0, multiplication = 0;
String userChoice = "";
String choices[] = {"add","multiply","divide","subtract"};
//ask for user input
System.out.print("Please enter first number: ");
firstNum = input.nextInt();
System.out.print("Please enter second number: ");
secondNum = input.nextInt();
System.out.println("What type of operation would you like to perform on these numbers?");
System.out.println("add " +"multiply " +"subtract " + "divide ");
userChoice = input.nextLine();
if (userChoice == "add"){
System.out.print("Answer = " + addition);
}
//calculator formulas
addition = firstNum + secondNum;
multiplication = firstNum * secondNum;
subtraction = firstNum - secondNum;
division = firstNum / secondNum;
}
}
nextInt() reads just the number and not the end of the line after the number. You will need a nextLine() after each nextInt() to consume the rest of the line.
Also, before you beat your head against the wall the following statement won't work for you:
if (userChoice == "add")
== tests for reference equality.
.equals() tests for value equality. So you need something like this instead:
if (userChoice.equals("add"))
I wanted to give you that freebie because I love your attitude that you don't want anyone to give you the answer. That is great that you wan to learn it. Keep up the good work.
Saying that String a == String b means that you're comparing two strings to see if they have reference equality, while saying a.equals(b) will compare the values stored in the string.
Reference equality is used to compare whether two object references point to the same object, which in this case you shouldn't be using as you're trying to compare whether the value of two variables are equal. So definitely go with
if(userChoice.equals("add"))

In java, in this program it suddenly stops running properly at a certain point of code? but it compiles? any ideas what could be the issue?

import java.io.IOException;
import java.util.*;
public class task2 {
public static void main (String [] args) throws IOException {
int a;
int b;
String y;
String x;
Scanner input = new Scanner(System.in);
System.out.println("Please enter number A:");
a = input.nextInt();
System.out.println("\nPlease enter number B:");
b = input.nextInt();
System.out.println("\nLastly, enter A if you wish it to be the dividor and/or subtractor, or if you wish it to be B, please enter B :"); //stops running properly here...
y=input.nextLine();
System.out.println("\nWhat would you like to do? Multiply (*), Divide (/), Subtract (-) or Add (+)? Please enter the symbol of which process you would like to have completed:");
x=input.nextLine();
if (y=="b"+"B") {
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + a*b);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + a/b);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + a+b);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (a-b));}}
else
if (y=="a"+"A"){
if (x=="*") {
System.out.println("\nThe product of these numbers is:" + b*a);}
else
if (x=="/") {
System.out.println("\nThe quotient of these numbers is:" + b/a);}
else
if (x=="+") {
System.out.println("\nThe sum of these numbers is:" + b+a);}
else
if (x=="-") {
System.out.println("\nThe difference of these numbers is:" + (b-a));}}
}
}
I dont know why it stops but where indicated by "//" the program suddenly stops letting me input information and does not continue the processes i want it to do. I wont bother explaining the program in detial because i believe it is fairly obvious from the code itself what i want to do.
Thanks in adavance for all the help!
Use
input.next();
not
input.nextLine();
Since nextLine() skips over the input and sets the scanner to the NEXT line and returns a string representation of what was skipped. Your program throws the errow because the NEXT line does not exist
Your string comparisons are incorrect--you need to compare strings using the equals() method, like x.equals("*") in order for any of them to work. (This is a pretty common mistake, so even though it's homework, freebie :)
There's no loop, so it'll stop after the first time "through"; this may or may not be what you want.

Categories