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);
Related
I am a complete beginner with java and coding altogether and am trying to make a program that solves two equations based on what a user has inputted into the program. I've tried changing the variable types to long, int, double, but nothing changes. The result is always 0 or 0.0 Any help would be much appreciated.
package pa2;
import java.util.Scanner;
public class GravitationalForce
{
public static void main(String[] args)
{
System.out.println("Please enter the name of the planet and its weight in quintillion kilograms");
Scanner myScanner = new Scanner (System.in);
String planetName = myScanner.next();
int planetWeight = myScanner.nextInt();
System.out.println("Enter the weight of the person in kilograms");
double personWeight = myScanner.nextDouble();
System.out.println("Please enter the radius of the planet Alderaan in million meters");
double planetRadius = myScanner.nextDouble();
Long gravitationalConstant = (long) (6.673*Math.pow(10,-11));
Double force = gravitationalConstant*(planetWeight*Math.pow(10, 18)*personWeight)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6);
Double gravity = gravitationalConstant*(planetWeight*Math.pow(10, 18)/planetRadius*Math.pow(10, 6)*planetRadius*Math.pow(10, 6));
System.out.println("The gravitational force of planet " + planetName + " on the person is " + force + " Newtons");
System.out.println("The gravity of the planet " + planetName + " is " + gravity + " meters per second squared");
}
}
6.673*Math.pow(10,-11) is < 1, so if you cast it to long, it becomes 0.
change
Long gravitationalConstant = (long) (6.673*Math.pow(10,-11));
to
double gravitationalConstant = 6.673*Math.pow(10,-11);
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);
}
}
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);
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
I need to be able to input two numbers, divide the first by the second and output how many times it goes into it and what the remainder is.
I can print out the remainder but how do I work out how many times the number divides by?
My code is as follows
import java.util.Scanner;
public class TotalAndRemainder
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your first number");
int firstvalue = keyboard.nextInt();
System.out.println("Enter your second number");
int secondvalue = keyboard.nextInt();
int total = firstvalue / secondvalue;
int remainder = firstvalue % secondvalue;
System.out.println("The remainder is " + remainder);
}
}
If I understand correctly what you are trying to do you already have how many times secondvalue goes into firstvalue, when you find total. You just need to print it out with a statement like so:
System.out.println(secondvalue + " goes into " + firstvalue + ", " + total + "times.");
System.out.println(firstNumber + " goes into " + secondNumber + " " + total + " times. The remainder is " + remainder + ".");
In java int\int=int, i.e. your total field already gives you the number of whole times.
import java.util.Scanner;
public class TotalAndRemainder
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your first number");
int firstvalue = keyboard.nextInt();
System.out.println("Enter your second number");
int secondvalue = keyboard.nextInt();
if(firstvalue >= secondvalue)
{
int total = firstvalue / secondvalue;
int remainder = firstvalue % secondvalue;
}
else
{
int total = secondvalue / firstvalue;
int remainder = secondvalue % firstvalue;
}
System.out.println("The total is " + total + "remainder is " + remainder);
}
}
I hope this will work for u...