Input/Output - Arithmetic Equation - java

I am brand new to Java, started two weeks ago and am having issues wrapping my mind around this issue. I have a problem in a class I am taking that has been brought up before. Converting kilograms to pounds and rounding to the second decimal place.
I can create the input side of things and bring up a dialog box to prompt the user to enter in a weight. I can also create an output that uses an equation I made to output the answer in a dialog box.
My question is how do I take the information that is input and use it to convert from kilograms to pounds?
I have been reading my book and scouring the internet trying to find an answer and I think I may be over thinking it. Thanks for the help.
Input.java:
//This program asks a user to input a weight in kilograms.
package module2;
import javax.swing.*;
public class Input {
public static void main(String[] args) {
String weight;
weight = JOptionPane.showInputDialog("Enter weight in kilograms");
}
}
Output.java:
//This program outputs a converted weight from kilograms to pounds.
package module2;
import javax.swing.JOptionPane;
public class Output {
public static void main(String[] args) {
double kg = 75.5;
double lb = 2.2;
double sum;
sum = (kg * lb);
JOptionPane.showMessageDialog(null,sum, "Weight Conversion", JOptionPane.INFORMATION_MESSAGE);
}
}

Right now you have 2 main methods. Both of these are entry points for the program. Since they have to share information, it doesn't make sense you have both.
What I'd recommend is to change the Output's main method to a instance method, taking one parameter: the weight from the Input.
Like so:
public void printOutput(final double weight){
//...
}
You can then call that from the Input's main method like so:
public static void main(String[] args) {
String weight;
weight = JOptionPane.showInputDialog("Enter weight in kilograms");
double kg = Double.parseDouble(weight); // Be sure to parse the weight to a number
Output output = new Output(); // Create a new instance of the Output class
output.printOutput(kg); // Call our method to display the output of the conversion
}
One other thing, is that since Output is currently only used for that one method, you could consider just moving that method into Input.

// addition of two integers using JOptionPane
import javax.swing.JOptionPane;
public class Addition
{
public static void main(String[] args)
{
String firstNumber = JOptionPane.showInputDialog("Input <First Integer>");
String secondNumber = JOptionPane.showInputDialog("Input <Second Integer>");
int num1 = Integer.parseInt(firstNumber);
int num2 = Integer.parseInt(secondNumber);
int sum = num1 + num2;
JOptionPane.showMessageDialog(null, "Sum is" + sum, "Sumof two Integers", JOptionPane.PLAIN_MESSAGE);
}
}

Related

How can I change this linear Java Code for a program that adds and subtracts to Object-Oriented Code

I am trying to make a simple android app that can add and subtract numbers, but my challenge is to make sure that the program is Object-Oriented. Currently I have been told that it is linear, but I am confused as to how it has remained linear after trying many times to make it object-oriented. How can I make this object oriented programming. Here is my code.
import java.util.Scanner;
public class addNumbers {
public static void main(String[] args)
{ // Begin main
Scanner input = new Scanner( System.in ); // Instantiate object input
System.out.println("Enter number 1"); // Ask the user to enter number 1
double number1 = input.nextDouble(); // Read the first number
System.out.println("Enter number 2"); // Ask the user to enter number 2
double number2 = input.nextDouble(); // Read the second number
double sum=number1 + number2; // Add the numbers
double difference = number1 - number2; // Subtract number 2 from number1
System.out.printf("\nSum = %f\n", sum); // Print the sum
System.out.printf("Difference = %f", difference); // Print the difference.
}
} // end main
My applications use this boilerplate to execute inside an object. If you start like this, you can add methods as you need them.
public class Demo
{
public static void main (String[] args)
{
final Demo app = new Demo ();
app.execute ();
}
private void execute ()
{
// Do stuff here.
}
}
Whoever gave you this assignment is using wrong and confusing terms, because linear programming is something else. But that's a different topic.
Even though this program is not complex, we can introduce some classes by modelling the flow of the program and/or the math operations.
Here is one idea... we could have a class called Operands, that has a method to read the numbers from the input while it prints instructions to the output. Then it stores these two numbers.
So something like this (I am using static class here instead of just class in case you will put this inside your public class addNumbers)
static class Operands {
public final double first;
public final double second;
public Operands(double first, double second) {
this.first = first;
this.second = second;
}
public static Operands readFromIO(InputStream in, PrintStream out) {
Scanner input = new Scanner(in); // Instantiate object input
out.println("Enter number 1"); // Ask the user to enter number 1
double number1 = input.nextDouble(); // Read the first number
out.println("Enter number 2"); // Ask the user to enter number 2
double number2 = input.nextDouble(); // Read the second number
return new Operands(number1, number2);
}
}
Then we could have another class called Calculator, that has a method to set the operands setOperands(Operands operands) and two methods to get the results for the sum and the difference. The methods could be called getSum and getDifference.
static class Calculator {
private double sum = 0;
private double difference = 0;
public void setOperands(Operands operands) {
sum = operands.first + operands.second;
difference = operands.first - operands.second;
}
public double getSum() {
return sum;
}
public double getDifference() {
return difference;
}
}
Then in the main method of the program, we just need to make an instance of the Calculator class and set the Operands on the instance. We read these operators by calling Operands.readFromIO(...). Then we retrieve the sum and the difference from the calculator instance.
So the code in main looks like this
public static void main(String[] args) {
Calculator c = new Calculator();
Operands operands = Operands.readFromIO(System.in, System.out);
c.setOperands(operands);
System.out.printf("Sum = %f\n", c.getSum()); // Print the sum
System.out.printf("Difference = %f\n", c.getDifference()); // Print the difference.
}
This is just one way to do it with some objects.
Another way could be to use an interface called Operation that contains a calculate(Operands operands) method and have 2 more classes Addition and Subtraction implement the interface. Then you would use those two classes to calculate the results.

Banking interest Q

Im trying to make a program that calculates the compound interest of an account with the principle,interest rate, and years. Im trying to do it with dialogs/ The program has the output the return on the invesment if the principle is left to accumulate.
Im stuck on the calculation part, please help
package firstAssignment;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class thinkingQuestion {
public static void main(String[] args) {
//Banking program that asks user for the amount of money they wish to invest in a
//compound interest account (principle), the interest rate (percent value) and the time frame (years).
Scanner in= new Scanner(System.in);
String principle, interestVal, years;
int newPrinciple,newYears;
double total;
principle=JOptionPane.showInputDialog("How much money would you like to invest?");
interestVal=JOptionPane.showInputDialog("What's the interest rate?");
years=JOptionPane.showInputDialog("How many years?");
//convert from String to integer
newPrinciple=Integer.parseInt(principle);
newYears=Integer.parseInt(years);
double newInterestVal=Integer.parseInt(interestVal);
total=JOptionPane.PLAIN_MESSAGE(newPrinciple*Math.pow(1+ newInterestVal, newYears), newYears);
I deleted somo variables you don't need, I think the main problem is on java syntax for show messages. Here you could see a tutorial:
https://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
import javax.swing.JOptionPane;
public class InterestBanking {
public static void main(String[] args) {
// Banking program that asks user for the amount of money they wish to
// invest in a
// compound interest account (principle), the interest rate (percent
// value) and the time frame (years).
String principle, interestVal, years;
float newPrinciple, newYears;
principle = JOptionPane.showInputDialog("How much money would you like to invest?");
interestVal = JOptionPane.showInputDialog("What's the interest rate?");
years = JOptionPane.showInputDialog("How many years?");
// convert from String to integer
newPrinciple = Float.parseFloat(principle);
newYears = Float.parseFloat(years);
double newInterestVal = Float.parseFloat(interestVal);
//You could change your calculation here if this isn't the need formula
double interest = newPrinciple * Math.pow(1 + newInterestVal, newYears);
//you were assigning the result to a total variable. That's not neccesary
JOptionPane.showMessageDialog(null, "Interest:" + NumberFormat.getCurrencyInstance(new Locale("en", "US")).format(interest) + " In years: " + newYears);
}
}

Calling a method for calculation [duplicate]

This question already has answers here:
How to get the user input in Java?
(29 answers)
Closed 6 years ago.
So I made a class that is supposed to calculate the number of beers needed to become intoxicated. My class receives User Input for the name of the beer, the alcohol content, and then the user's weight to make the calculation.
Here's my whole Beer class
public class Beer {
private String name;
private double alcoholContent;
//Default apple values (Constructors)
public Beer()
{
this.name = "";
this.alcoholContent = 0.0;
}
//Accessors
public String getName()
{
return this.name;
}
public double getAlcoholContent()
{
return this.alcoholContent;
}
//Mutators
public void setName (String aName)
{
this.name = aName;
}
public void setAlcoholContent (double aAlcoholContent)
{
if (aAlcoholContent < 0 || aAlcoholContent > 1)
{
System.out.println("That is an invalid alcohol content");
return;
}
this.alcoholContent = aAlcoholContent;
}
//Methods
public double Intoxicated (double aWeight)
{
double numberOfDrinks = (0.08 + 0.015) * aWeight / (12 * 7.5 * this.alcoholContent);
return numberOfDrinks;
}
This is specifically my intoxicatedmethod in the class (I think it's right):
public double Intoxicated (double aWeight)
{
double numberOfDrinks = (0.08 + 0.015) * aWeight / (12 * 7.5 * this.alcoholContent);
return numberOfDrinks;
}
This is what the output window is supposed to look like, receiving User Input for the weight and then performing the calculation to see how many beers it would take based on the user's input when previously defining two beers to be considered intoxicated:
What’s the weight of the person consuming said beverages?
185
It would take 3.166 "firstBeerName" beers to become intoxicated.
It would take 1.979 "secondBeerName" beers to become intoxicated.
The intoxicated formula was given to me, I don't know how to properly set up my class testing main method file which calls this class to reflect that output.
You need to write a testing class, that contains a main method. In the main method you can create several Beer-Objects.
By iterating over your Beers, you can get the wanted results.
Look here to get information about how to set up a main method.
Create an Array of Beer-Objects in that method with different alcohol content
Get the user input for the weight and then
Iterate over your Array, call intoxicated() and print the results
You are going to want to create a main method which does the following:
1) Prints the prompt for the beer values (name and % alcohol)
2) Takes in user input for those beer values
3) Prints the prompt for the user's weight
4) Takes in the user input for the weight
5) Calculates and prints the result
For printing prompts, you will most likely want to use System.out.println("Some prompt here!");
For taking input, you will most likely want to use a Scanner. You can search around on this website and others, as well as read the documentation, for how to take input with using that class.
Here is an example of a main method:
public static void main(String[] args) {
Beer blueMoon = new Beer("Blue Moon", 5.4);
Beer hoegaarden = new Beer("Hoegaarden", 4.9);
System.out.println("Enter your weight: ");
Scanner input = new Scanner();
Double weight = input.nextLine();
double value = beer1.Intoxicated(weight);
System.out.println("It would take " + value + " of " + blueMoon.getName() + " to become intoxicated.");
}
I would suggest renaming your Intoxicated method to intoxicated, as method names are generally camelCased in Java.
I am not going to give you the exact code because this seems like homework and I already graduated, but that should be enough to get you started. My advice would be to search around for any specific questions you come up with.
You can write a main method like this:
public static void main(String [ ] args)
{
Beer beer1 = new Beer().
beer1.setName("firstBeerName");
beer1.setAlcoholContent(3.166);
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("What’s the weight of the person consuming said beverages?");
double weight = reader.nextDouble();
double answer = beer1.Intoxicated(weight);
System.out.println("It would take "+answer+" "+beer1.getName()+" beers to become intoxicated.")
// similar for beer2
}
I would encourage you to throw IllegalArgumentException when checking condition in setter:
public void setAlcoholContent(double aAlcoholContent) {
if (aAlcoholContent < 0 || aAlcoholContent > 1) {
throw new IllegalArgumentException("Alcohol content can't be more than 1 or less than 0");
}
this.alcoholContent = aAlcoholContent;
}
And for your question you can test it like this:
public static void main(String[] args) {
List<Beer> beers = new ArrayList<>();
beers.add(new Beer("firstBeerName", 0.04));
beers.add(new Beer("secondBeerName", 0.06));
Scanner reader = new Scanner(System.in);
System.out.println("What’s the weight of the person consuming said beverages?");
double weight = reader.nextDouble();
DecimalFormat decimalFormat = new DecimalFormat("0.000");
for(Beer beer : beers){
System.out.println("It would take " + decimalFormat.format(beer.Intoxicated(weight)) + " " + beer.getName() +" beers to become intoxicated.");
}
}
Also you can use loop for creating new beers, just ask user for amount of beers that he can obtain result for, and then create for loop.

nothing will print in the compiler. [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Here's the question I was asked:
Write a complete Java program called CalcTotalPrice. The program must include five methods:
getSaleTotal, getSalePrice, getSaleWeight, calcTax, and calcShipping.
getSaleTotal takes no input parameters and returns a double, which is the sale total, and which it computes by calling the other four methods.
getSalePrice returns a double, which it gets from the user at the command line.
getSaleWeight returns a double, which it gets from the user at the command line.
calcTax takes a double as a parameters (the sale price) and returns the tax amount as a double (use 6% as a fixed tax rate).
calcShipping takes a double as a parameter (the sale weight) and returns the shipping amount as a double (calculate shipping as $10 if weight is less than 10 and $20 if weight is 10 or greater).
getSaleTotal should print the sale price amount, tax amount, shipping amount, and sale total amount to the command line.
nothing will print in the compiler. Please help me.
Here's my code:
import java.util.Scanner;
/**
*
* #author Kramer1
*/
public class CalcTotalPrice {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
public static double getSaleTotal(){
Scanner in = new Scanner(System.in);
double price = getSalePrice(in);
System.out.println(price);
double tax = calcTax(.06);
System.out.println(tax);
double shipping = calcShipping(in.nextDouble());
System.out.println(shipping);
double saleTotal = ((price)*tax)+price+shipping;
System.out.println(saleTotal);
return saleTotal;
}
public static double getSalePrice(Scanner in){
double salePrice = in.nextDouble();
return salePrice;
}
public static double getSaleWeight(Scanner in){
double saleWeight = in.nextDouble();
return saleWeight;
}
public static double calcTax(double salePrice){
double salesTax = .06;
return salesTax;
}
public static double calcShipping(double saleWeight){
double amountShipping = 0;
if (saleWeight < 10){
amountShipping = 10.;
}else if(saleWeight > 10){
amountShipping = 20.;
}
return amountShipping;
}
}
You arent doing anything in your main()
To see the output, you will have to create the Scanner in main and then call appropriate methods.
You need to do some code refactoring. First, move your Scanner to the main method. Then pass it around as an argument to other methods to read data from or read data in main and pass the values directly. I suggest the latter
You also need to declare the variables you use outside the methods and into the class so that their values persist till the end of the program and you will have access to them in various methods. Do declare them static.
You have a main method that is empty - it is not doing anything or calling any code.
Try instantiating your class and calling some methods in it.
it also looks like it is expecting some input from the user. So also try instantiating a Scanner class in your main which can then be passed to some methods. Remember to also call in.nextLine(); to flush the input before calling the next in.nextDouble();
try
Static Double salesPrice = null;
public static void main(String[] args) {
CalcTotalPrice ctp = new CalcTotalPrice ();
Scanner sc = new Scanner(System.in);
salesPrice = ctp.getSalesPrice (in);
in.nextLine();
//etc
}

Decimal Format?

I just wrote a lab that is supposed to flip two coins 500 times and count how many times heads and tails were flipped and is supposed to calculate the percentage to the tenth. I remember the template for Decimal formatting, but forgot how to use it. Can somebody help? My program is as follows:
import java.util.Scanner;
import java.text.DecimalFormat;
public class Lab97a
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
DecimalFormat accuracy=new DecimalFormat("0.0");
Dice coin;
int numCoin;
int numHeads;
int numTails;
int count;
double percentageHeads;
double percentageTails;
coin=new Dice(2);
numHeads=0;
numTails=0;
System.out.println("A coin is tossed 500 times. The results are asfollows: ");
for (count=1;count<=500;count=count+1)
{
numCoin=coin.roll();
if (numCoin==1)
{
numHeads+=1;
}
if (numCoin==2)
{
numTails+=1;
}
}
percentageHeads=numHeads/5;
percentageTails=numTails/5;
System.out.println("Heads was flipped "+numHeads+" times,
"+percentageHeads+"%.");
System.out.println("Tails was flipped "+numTails+" times, "+percentageTails+"%");
}
}
It looks like you just need to format the accuracy with e.g. accuracy.format(percentageHeads). See NumberFormat.format(double) that DecimalFormat extends.
You can use the String.format method for this, as described here:
System.out.println(String.format("Heads was flipped %d times, %.2f %%"), numHeads,percentageHeads);

Categories