Calculator console app not working - java

I'm trying to make a simple calculator console app. The answer stays 0 no matter what I do. Can anyone tell me what is wrong if anything is wrong without giving me a direct answer.
import java.util.Scanner;
public class Calculator
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int firstNum;
int secondNum;
int division = 0, addition = 0, subtraction = 0, multiplication = 0;
String userChoice = "";
String choices[] = {"add","multiply","divide","subtract"};
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?");
System.out.println("add, multiply, subtract or divide.");
input.nextLine();
userChoice = input.nextLine();
if (userChoice.equals("add"))
System.out.print("The answer is " + addition);
else if (userChoice.equals("multiply"))
System.out.print("The answer is " + multiplication);
else if (userChoice.equals("subtract"))
System.out.print("The answer is " + subtraction);
else if (userChoice.equals("divide"))
System.out.print("The answer is " + division);
division = firstNum / secondNum;
addition = firstNum + secondNum;
subtraction = firstNum - secondNum;
multiplication = firstNum * secondNum;
}
}

As others have already said, the calculation needs to be done before the output.
I suggest some more improvements:
Use proper variable naming. For example, addition is an operation but the variable holds the result of this operation which is usually called sum. So use these names for your variables. Actually, you don't need four different variables, see below.
Declare your variables where you need them, not at the beginning of the function.
In your code, the four possible calculations are always performed, not only the one selected by the user.
The second part of your code (after the input) could look like this:
int result = 0;
if (userChoice.equals("add")) {
result = firstNum + secondNum;
}
else if (userChoice.equals("subtract")) {
result = firstNum - secondNum;
}
else if (userChoice.equals("multiply")) {
result = firstNum * secondNum;
}
else if (userChoice.equals("divide")) {
// maybe check if secondNum is not zero
result = firstNum / secondNum;
}
else {
System.out.print("Invalid input " + userChoice);
return;
}
System.out.print("The answer is " + result);

Related

How to get rid of zero after decimal point?

import java.util.Scanner;
import java.lang.Math;
public class Calculator {
public static void main(String[] args) {
int firstNum;
int secondNum;
int sum;
int product;
int difference;
float division;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter First Number : ");
firstNum = scanner.nextInt();
System.out.print("Enter Second Number : ");
secondNum = scanner.nextInt();
scanner.close();
sum = firstNum + secondNum;
difference = firstNum - secondNum;
product = firstNum * secondNum;
division = (float) firstNum / secondNum;
double firstSquare = Math.pow(firstNum, 2);
double secondSquare = Math.pow(secondNum, 2);
System.out.println("Sum = " + sum);
System.out.println("Division = " + division);
System.out.println("Product = " + product);
System.out.println("Difference = " + difference);
System.out
.println("Square of " + firstNum + " is " + firstSquare + " Square of " + secondNum + " is " + secondSquare);
}
}
This is a program that takes in two inputs then performs few calculations. I have an issue that I don't want zero after decimal point when I am squaring two inputs. So, how do I get rid of it? Can someone help me with that. Thank you
If you don't want decimals either use an int or cast a double to an int. E.g (int) doubleValue. But if you just want to eliminate the .0 from floating point numbers then perhaps this is what you want.
for (double d : new double[]{2.3, 2.0,1.222, 4445.2, 442.0}) {
System.out.println(new DecimalFormat("#.######").format(d));
}
prints
2.3
2
1.222
4445.2
442
For more information on the format syntax, check out DecimalFormat
You can do it with formatting as follows:
System.out.format("Square of %d is %.0f Square of %d is %.0f",
firstNum, firstSquare, secondNum, secondSquare);
%d means an integer without decimal places and %.0f means a floating-point number with 0 decimal places as you wanted.
Convert to string and check for ending
public String removePrefix(double number) {
if(String.valueOf(number).endsWith(".0")) {
return String.valueOf(number).split(".0")[0];
}
return String.valueOf(number);
}
Not tested, but I hope it helps. =)
Change the double values firstSquare and secondSquare to ints and cast them to int to change from double that Math.pow() returns to int, no need to round since squares of ints will always be int
int firstSquare = (int) Math.pow(firstNum, 2);
int secondSquare = (int) Math.pow(secondNum, 2);

Storing multiple values inside a while loop - Java

I'm trying to store the sum of 2 numbers inside a while loop so that once the loop ends multiple sums can be added up and given as a total sum, however I am rather new to Java and am not sure how to go about doing this.
I'm trying to use an array but I'm not sure if it is the correct thing to use. Any help would be greatly appreciated.
import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
Int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[0]=AddedNum;
TotalNum[1]=;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
System.out.println("The total sum of all the numbers you entered is " + TotalNum);
}
}
There is a data container called ArrayList<>. It is dynamic and you can add as many sums as you need.
Your example could be implemented like this:
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> listOfSums = new ArrayList<>();
int Num1, Num2, AddedNum;
String answer;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
listOfSums.add(AddedNum);
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
// Then you have to calculate the total sum at the end
int totalSum = 0;
for (int i = 0; i < listOfSums.size(); i++)
{
totalSum = totalSum + listOfSums.get(0);
}
System.out.println("The total sum of all the numbers you entered is " + totalSum);
}
}
From what I see, you come from a background of C# (Since I see capital letter naming on all variables). Try to follow the java standards with naming and all, it will help you integrate into the community and make your code more comprehensible for Java devs.
There are several ways to implement what you want, I tried to explain the easiest.
To learn more about ArrayList check this small tutorial.
Good luck!
Solution with array:
import java.util.Scanner;
public class StoredWhile{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int TotalNum[]=new int[10];
int Num1, Num2, AddedNum;
String answer;
int count = 0;
do{
System.out.println("Please enter a number");
Num1 = input.nextInt();
System.out.println("Please enter a second number");
Num2 = input.nextInt();
AddedNum = Num1 + Num2;
System.out.println("The sum of the two entered numbers is " + AddedNum);
TotalNum[count]=AddedNum;
count++;
System.out.println("Would you like to calculate the sum of two more numbers (y/n)?");
answer = input.next();
}
while (answer.equals("y"));
int TotalSum = 0;
for(int i = 0; i <count; i++ ) {
TotalSum += TotalNum[i];
}
System.out.println("The total sum of all the numbers you entered is " + TotalSum);
}
}
This solution is not dynamic. There is risk that length of array defined on beginning will not be enough large.

How do you find the average of three numbers with input and output dialog boxes with JAVA?

I've been playing around with this code for a little bit now and can't seem to find the correct way to sort it out. I used a program without JOptionPane and it worked and tried to use the same sequence but it didn't work. Do I need to add something else? The assignment is to have the user enter 3 integers and print the average with input and output dialog boxes. I've done the average and input/output dialog boxes before but putting it all together is harder than I thought.
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.*;
import java.text.DecimalFormat;
public class Number3
{
public static void main(String[] args)
{
System.out.println("Enter 3 numbers: ");
Scanner input = new Scanner (System.in);
DecimalFormat decimalFormat = new DecimalFormat("0.00##");
int num1;
int num2;
int num3;
double avg;
num1=input.nextInt();
num2=input.nextInt();
num3=input.nextInt();
avg=(double)(num1+num2+num3)/3.0;
System.out.println("The average is: " + decimalFormat.format(avg));
}
}
I don't know what you find hard here. I think you are looking for this:
DecimalFormat decimalFormat = new DecimalFormat("0.00##");
int num1;
int num2;
int num3;
double avg;
num1= Integer.valueOf(JOptionPane.showInputDialog("Enter #1"));
num2= Integer.valueOf(JOptionPane.showInputDialog("Enter #2"));
num3= Integer.valueOf(JOptionPane.showInputDialog("Enter #3"));
avg=(double)(num1+num2+num3)/3.0;
JOptionPane.showMessageDialog(null, "The average is: " + decimalFormat.format(avg));
Please note that this code could be written better but for the sake of answering I just replaced the JOptionPane in your code where you need them.
It's really not that much harder. On the input side, using one of the showInputDialog(...) methods of JOptionPane is almost an exact replacement for input.nextInt();. The only difference it that showInputDialog(...) returns the user's input as String, not an int, so you'll have to use Integer.parseInt to convert the returned String into an int. As for the output, showMessageDialog(...) is an almost exact replacement for System.out.println(...); just use the --- as the message text argument.
public static void main(String[] args) {
int num, count=0;
double total =0, avg;
for(int i = 1; i <= 3; i++){
num = Integer.valueOf(JOptionPane.showInputDialog("Enter number "+ count++));
total += num;
}
avg = total / count;
JOptionPane.showMessageDialog(null, "The average is: " + (double)Math.round(avg * 100) / 100);
}
/*
*AverageOfThreeNumnber.java
*calculating the Average Of Four Numnberand diaply the output
*using JOptionpane method in java
*/
import javax.swing.JOptionpane;
public class AverageOfThreeNumbers {
public static void main(String[] args) {
int fristNumber; // FRIST INTEGER NUMBER
int SecondNumber; // SECOND INTEGER NUMBER
int ThridNumber; // THRID INTEGER NUMBER
int sum; // SUM OF THE FOUR INTEGER NUMBERS
double avarage; // AVERAGE OF THE FOUR NUMBERS
String input; // INPUT VALUE
String result; // OUTPUT GENERATING STRING
// ACCEPT INTEGER NUMBERS FROM THE USER
input = JOptionpane.showInputDialog(null, "Enter frist nmuber: ");
FristNumber=Integer.parse.Int(Input);
input = JOptionpane.showInputDialog(null, "Enter Second nmuber: ");
SecondNumberr=Integer.parse.Int(Input);
input = JOptionpane.showInputDialog(null, "Enter Thrid nmuber: ");
ThridNumber=Integer.parse.Int(Input);
//CALCULATE SUM
sum = fristNumber + SecondNumber + ThridNumber;
//CALCULATE AVERAGE
average = sum/4.0
//BUILD OUTPUT STRING AND DISPLAY OUTPUT
result = "Average of" + fristNumber + ", " + SecondNumber + " And " + ThridNumber +" is = " + average;
JOptionpane.showMessageDialog(null, result, "Average of 3 Numbers", JOptionpane.INFORMATION_MESSAGE);
}
}

Prompting user to continue not working, java

I need help. I want to ask the user if he wants to try again, but something seems to be wrong with my code, because it's not working.
public class TotoAzul
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int n1, n2, sum;
String answer;
do {
System.out.println("Enter number 1: ");
n1 = keyboard.nextInt();
System.out.println("Enter number 2: ");
n2 = keyboard.nextInt();
sum = n1 + n2;
System.out.println("Number 1\t" + "Number 2\t" + "Sum");
System.out.println("__________________________________");
System.out.println(n1 + "\t\t" + n2 + "\t\t" + sum);
System.out.println("Enter yes to continue or any other key to end");
answer = keyboard.nextLine();
keyboard.nextLine();
}
while(answer.equalsIgnoreCase("YES"));
}
}
When I run it, it stores the user's answer, yet the program doesn't repeat. How can I fix this?
Move the keyboard.nextLine(); after n2 = keyboard.nextInt(); to accept and ignore the dangling newline character in the inputstream left behind by call to nextInt().
When I run it, it stores the user's answer - Try printing what it has stored in the answer field then you will see the problem.
Scanner keyboard = new Scanner(System.in);
int n1, n2, sum;
String answer = "Yes";
while (answer.equals("Yes"))
{
System.out.println("Enter number 1: ");
n1 = keyboard.nextInt();
System.out.println("Enter number 2: ");
n2 = keyboard.nextInt();
sum = n1 + n2;
System.out.println("Number 1\t" + "Number 2\t" + "Sum");
System.out.println("__________________________________");
System.out.println(n1 + "\t\t" + n2 + "\t\t" + sum);
System.out.println("Enter yes to continue or any other key to end");
answer = keyboard.nextLine();
keyboard.nextLine();
}
Change the position of keyboard.nextLine();.
keyboard.nextLine();
answer = keyboard.nextLine();
In your code answer is getting next line(i.e. enter), which comes into picture when you take value of n2 and press enter.
You can test your code by executing below code
System.out.println("Enter yes to continue or any other key to end");
answer = keyboard.nextLine();
System.out.println("Answer : " + answer);
System.out.println(keyboard.nextLine());

sum the second to the last on java

How can I print the sum of the 2nd to the last digit of each integer on java?
(so, 8 would be printed since 1 + 3 + 4 is 8 , and 35 would be printed since 3453 + 65324 + 354) in the following Program: * without using if statements *
import java.util.*;
public class Pr6{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int num1;
int num2;
int num3;
int sumSecToLast;
System.out.print("Please write an integer: ");
num1 = scan.nextInt();
System.out.print("Please write an integer: ");
num2 = scan.nextInt();
System.out.print("Please write an integer: ");
num3 = scan.nextInt();
sumSecToLast = (num1/10) % 10 + (num2/10) % 10 + (num3/10) % 10;
System.out.print((num1/10) % 10 + " + " + (num2/10) % 10 + " + " + (num3/10) % 10 + " = " + sumSecToLast);
}//main
}//Pr6
Once you've scanned all the integers:
//In main method:
int secLast1 = Pr6.getSecLastDigit(num1);
int secLast2 = Pr6.getSecLastDigit(num2);
int secLast3 = Pr6.getSecLastDigit(num3);
int sum = secLast1 + secLast2 + secLast3;
System.out.println(secLast1 + " + " + secLast2 + " + " + secLast3 + " = " + sum);
You also want to create the additional method:
private static int getSecLastDigit(int num) {
return (num / 10) % 10;
}
Here is how I would do it. Depending on your definition of an if statement this might not work for you (spoiler).
import java.util.*;
public class Pr6{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int total = 0;
String num1, num2, num3;
System.out.print("Please write an integer: ");
num1 = scan.nextLine(); // rather than taking an integer this takes a String because it is easier to extract a single element.
... // get the other numbers
for (int i = 1; i < num1.length(); i++){
total += Character.getNumericValue(num1.charAt(i)); // adds each number to the total
}
... // do this for the other Strings (or use another loop for with a String[])
System.out.println(total);
}//main
}//Pr6
To make this more concise I would highly recommend using a String[] rather than 3 different variables. Also I am assuming a for loop doesn't count as an if statement. However I realize that because of the boolean check they may be considered too similar for your current situation. I hope this helps! :)
Sorry for inconvenience. My question was misunderstood. I meant that I want to write a code to find the sum of the 2nd to the last digit of a three different integers. For ex: if the user entered 15, 34, and 941, which in this case the 2nd to the last digit will be 1, 3, and 4. Therefore, the subtotal of them will be 1+3+4 = 8.
I found out the answer and I wanted to share it with everyone, and also I would like to thank all of those who tried to help.
thank you..
import java.util.*;
public class Pr6{
public static void main(String[] args){
Scanner scan = new Scanner (System.in);
int num1;
int num2;
int num3;
int sumSecToLast;
System.out.print("Please write an integer: ");
num1 = scan.nextInt();
System.out.print("Please write an integer: ");
num2 = scan.nextInt();
System.out.print("Please write an integer: ");
num3 = scan.nextInt();
sumSecToLast = ((num1/10) % 10) + ((num2/10) % 10) + ((num3/10) % 10);
System.out.println("The subtotal of the 2nd to the last digit = " + sumSecToLast);
System.out.println();
}//main
}//Pr6

Categories