How do I invoke a class from my Main method in Java? - java

I'm trying to have a user input a couple of numbers and I show the output using newNumerator = in.nextDouble(); but I'm asked to change Fraction newNumerator to a double and if I do, I than have to change it to Fraction.
What am I missing?
import java.util.Scanner;
public class FractionTest {
public static void main(String[] args){
Fraction newNumerator;
Fraction newDenominator;
newNumerator = new Fraction();
newDenominator = new Fraction();
Scanner in = new Scanner(System.in);
System.out.println("Please enter a numerator: ");
newNumerator = in.nextDouble(); // I get an error here
System.out.println("Please enter a denominator: ");
newDenominator = in.nextDouble(); // I get an error here
in.close();
}
}
The above is my Main() and the following is my class.
public class Fraction {
public double numeratorAnswer;
public double denominatorAnswer;
public Fraction() {
}
public double getNumeratorAnswer(){
return numeratorAnswer;
}
public void setNumeratorAnswer(double newNumerator){
numeratorAnswer = newNumerator;
}
public double getDenominatorAnswer(){
return denominatorAnswer;
}
public void setDenominatorAnswer(double newDenominator){
denominatorAnswer = newDenominator;
}
}

You are trying to put a double into a Fraction variable instead of putting the double in the Fraction.
To fix this, use a single Fraction value and call setNumeratorAnswer and setDenominatorAnswer with your in.nextDouble().

You are trying to assign a double value to an object of Fraction class in following statements:
newNumerator = in.nextDouble(); // I get an error here
System.out.println("Please enter a denominator: ");
newDenominator = in.nextDouble(); // I get an error here
As this cast is not possible so you need to take the double inputs and then assign Fraction class numeratorAnswer and denominatorAnswer attributes. Something like this:
double dnewNumerator = in.nextDouble();
System.out.println("Please enter a denominator: ");
double dnewDenominator = in.nextDouble();
newNumerator.setNumeratorAnswer(dnewNumerator);
newNumerator.setDenominatorAnswer(dnewDenominator);
I am not sure what exactly you want to do with the inputs so not adding much code here, just showing how you can set the Fraction class attributes. I don't thin you need two Fraction objects

You are trying to make a double into a fraction. You need to take the values of the double and assign it to the fraction object.
I hope this helps answer your question.

Simply change the order of your code a little to:
Scanner in = new Scanner(System.in);
System.out.println("Please enter a numerator: ");
newNumerator = new Fraction(in.nextDouble());
System.out.println("Please enter a denominator: ");
newDenominator = new Fraction(in.nextDouble());
And after this, add a constructor to your Fraction class to receive double.
//Update your constructor as..
public Fraction(double numerator, double denominator) {
this.numeratorAnswer= numerator;
this.denominatorAnswer= denominator;
}
I guess you probably knows why get the errors as stated in your commented codes. The error is caused by giving variable of different data type.
Your newNumerator and newDenominator are by datatype of Fraction. Thus you can't use it to accept double values.
In the code sample I gave, you receive the double values and pass these values into the Fraction class's numerator & denominator.

Related

How to create a helper method that takes 2 double inputs into a class global array?

I'm new to java and I have a question about an assignment I have. I've written a bunch of methods that are different formulas, like the duration of a storm. The assignment asks me to write two helper methods to get input from the user. One of them is called get_S_Input() and I was able to implement it correctly I think. But the one I'm stuck on is this other helper method called get_2_Invals(). It wants me to prompt the user with my parameter, and read in 2 double values. It wants me to record the values in a class global array of doubles and then exit the method, but I don't know how to do this. I want to put it in the else statement in the method below. Here is my code so far...
import java.lang.Math;
import java.util.Scanner;
public class FunFormulas {
public void sd(){
double durationOfStorm = Math.sqrt(((Math.pow(get_S_Input("Enter the diameter of storm in miles:"), 3) / 216)));
if (durationOfStorm > 0)
System.out.println("The storm will last: " + durationOfStorm);
}
public void sl(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of seconds since the lightning strike:");
double secondsSinceLightning = Double.valueOf(scanner.nextLine());
double distanceFromLightning = (1100 * secondsSinceLightning);
System.out.println(distanceFromLightning);
}
public void si(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the edge of cube in inches:");
double edgeOfCubeInInches = Double.valueOf(scanner.nextLine());
if (edgeOfCubeInInches < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
double weightOfCube = (0.33 * (Math.pow(edgeOfCubeInInches, 3)));
System.out.println(weightOfCube);
}
public void dt(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the time in hours:");
double timeInHours = Double.valueOf(scanner.nextLine());
if (timeInHours < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
System.out.println("Enter the rate of speed in mph:");
double rateOfSpeed = Double.valueOf(scanner.nextLine());
if (rateOfSpeed < 0){
System.out.println("ERROR: please enter a non-negative number!!!");
}
double distanceTravelled = (rateOfSpeed * timeInHours);
System.out.println(distanceTravelled);
}
public void sa(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your weight in pounds:");
double weight = Double.valueOf(scanner.nextLine());
weight = weight * 0.4536;
System.out.println("Enter your height in inches:");
double height = Double.valueOf(scanner.nextLine());
height = height * 2.54;
double BSA = ((Math.sqrt(weight * height)) / 60);
System.out.println(BSA);
}
public double get_S_Input(String promptStr){
//Scanner helper method
System.out.println(promptStr);
Scanner scanner = new Scanner(System.in);
double value = Double.valueOf(scanner.nextLine());
if (value < 0 ){
System.out.println("ERROR: please enter a non-negative number!!!");
}
return value;
}
public void get_2_Invals(String promptStr){
/*Prompt the user with the promptStr passed in as a parameter
ii. Read in the first double precision value entered by the user with the Scanner
iii. Read in the second double precision value entered by the user with the Scanner
iv. Check to make sure the values entered by the user are non-negative
a. If either number entered by the user is negative, the method should print out an
error message, and return to step i. above.
b. If the number is non-negative (that is greater than or equal to zero) the method
should record the numbers obtained from the user in a class-global array of
doubles and exit.*/
System.out.println(promptStr);
Scanner scanner = new Scanner(System.in);
double firstValue = scanner.nextInt();
double secondValue = scanner.nextInt();
if (firstValue < 0 || secondValue < 0)
System.out.println("ERROR: please enter non-negative number!");
else
}
public static void main(String [] args){
FunFormulas fun = new FunFormulas();
fun.sd();
}
}

Possible lossy conversion while compiling in Java [duplicate]

This question already has an answer here:
What does "possible lossy conversion" mean and how do I fix it?
(1 answer)
Closed 4 years ago.
import java.util.*;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter price: $");
float price = keyboard.nextFloat();
System.out.println("Early payment (Y/N): ");
String char1 = keyboard.nextLine();
float amount = price;
if (char1.equals('Y'))
{
amount = price * 0.9;
}
System.out.printf("Amount due: $%0.2f\n", amount);
}
}
when compiling it gives the error of possible lossy conversion, regardless if i pass an int or float.. what is the issue here?
In Java by default every decimal number is considered double. You are multiplying a float by double which result in a double:
float price = 10.7f;
float result = price * 0.9; //this does not work
Here, we have two options. The first one is to convert 0.9 as float, putting the f in the front of the number:
float result = price * 0.9f;
The second option is to hold the result as double:
double result = price * 0.9;
Please, use double/float only for doing simple tests. Here we have a good explanation about the difference between Double and BigDecimal:
The main issue is that 0.9 is a double, which causes the value of price * 0.9 to be coerced to a double as well. To prevent that, you should use 0.9f to indicate you want a float type.
You also have an issue with char1 actually being a String, not a char, so char1.equals('Y') will always be false.
In addition, your %0.2f format says you want to zero-fill your output, but you neglected to specify a minimum width. Something like %04.2f should work.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter price: $");
float price = keyboard.nextFloat();
System.out.println("Early payment (Y/N): ");
String str1 = keyboard.next();
float amount = price;
if (str1.equals("Y")) {
amount = price * 0.9f;
}
System.out.printf("Amount due: $%04.2f\n", amount);
}
}

Calling a method from the superclass from subclass returns a value of 0

Pretty new to Java, this is for an assignment. Basically what I'm trying to do is the user inputs the amount of hours they've worked, their hourly rate, and their straight time hours and the program outputs their net pay.
I can calculate the gross pay just fine but the assignment requires me to calculate net pay within a subclass by calling the calc_payroll and tax methods from the superclass but it keeps returning a value of zero. I thought maybe there was something wrong with my tax method so I tried returning the gross pay from the subclass but it still returned zero.
I'm really stumped here, can anyone help?
Superclass:
class Pay
{
private float hoursWorked;
private float rate;
private int straightTimeHours;
public double calc_payroll()
{
double straightTimePay = rate * straightTimeHours;
double excessPay = (rate * 1.33) * (hoursWorked - straightTimeHours);
double grossPay = straightTimePay + excessPay;
return grossPay;
}
public double tax(double a)
{
double taxRate;
double netPay;
if(a <= 399.99)
taxRate = 0.08;
else if(a > 399.99 && a <= 899.99)
taxRate = 0.12;
else
taxRate = 0.16;
netPay = a - (a * taxRate);
return netPay;
}
public void setHours(float a)
{
hoursWorked = a;
}
public float getHours()
{
return hoursWorked;
}
public void setRate(float a)
{
rate = a;
}
public float getRate()
{
return rate;
}
public void setHrsStr(int a)
{
straightTimeHours = a;
}
public int getHrsStr()
{
return straightTimeHours;
}
}
Subclass:
class Payroll extends Pay
{
public double calc_payroll()
{
Pay getVariables = new Pay();
double getGrossPay = getVariables.calc_payroll();
double finalNetPay = getVariables.tax(getGrossPay);
return finalNetPay; //This returns a value of zero
//return getGrossPay; This also returns a value of zero
}
}
Main Method:
import java.util.*;
class Assign2A
{
public static void main(String args[])
{
float userHours;
float userRate;
int userStraight;
Scanner userInput = new Scanner(System.in);
System.out.println("I will help you calculate your gross and net pay!");
System.out.println("Please enter the number of hours you have worked: ");
userHours = Float.valueOf(userInput.nextLine());
System.out.println("Please enter your hourly pay rate: ");
userRate = Float.valueOf(userInput.nextLine());
System.out.println("Please enter the number of straight hours required: ");
userStraight = Integer.parseInt(userInput.nextLine());
Pay object = new Pay();
object.setHours(userHours);
object.setRate(userRate);
object.setHrsStr(userStraight);
Payroll objectTwo = new Payroll();
System.out.println("========================================");
System.out.println("Your gross pay is: ");
System.out.println("$" + object.calc_payroll());
System.out.println("Your net pay is: ");
System.out.println("$" + objectTwo.calc_payroll());
System.out.println("Thank you, come again!");
}
}
Typical Output:
----jGRASP exec: java Assign2A
I will help you calculate your gross and net pay!
Please enter the number of hours you have worked:
500
Please enter your hourly pay rate:
25
Please enter the number of straight hours required:
100
========================================
Your gross pay is:
$15800.0
Your net pay is:
$0.0
Thank you, come again!
----jGRASP: operation complete.
Several issues. For one, you're creating a Payroll object:
Payroll objectTwo = new Payroll();
//.....
System.out.println("$" + objectTwo.calc_payroll());
Not giving it any value, and then are surprised when it holds a value of 0.
You should use one single object here, a Payroll object, not a Pay object, fill it with valid data, and call both methods on this single object.
Secondly, your Payroll class is completely wrong. You have:
class Payroll extends Pay {
public double calc_payroll() {
Pay getVariables = new Pay();
double getGrossPay = getVariables.calc_payroll();
double finalNetPay = getVariables.tax(getGrossPay);
return finalNetPay; // This returns a value of zero
// return getGrossPay; This also returns a value of zero
}
}
But it should not create a Pay object but rather use the super methods as needed. To better help you with this, you will have to tell us your complete assignment requirements because you're making wrong assumptions about the assignment, I believe.

Calling methods with parameters in Java

So I have to make a program in class and i'm having some trouble.
I have to call the examAverage method, which has parameters and i'm not sure how to. Also, in the user prompts method, I have to make a loop in main that call user prompts method and ask the user to input their exam score 3 times to get the average. I hope I explained it well. Im not very good at programming.
package project5;
import java.util.*;
public class Project5 {
static final int NUM_EXAMS = 3;
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
//declare variable
double Average;
double examScore1 = 0;
double examScore2 = 0;
double examScore3 = 0;
double Average = examAverage(examScore1, examScore2, examScore3) / NUM_EXAMS;
printWelcome();
userPrompts();
display();
}
static void printWelcome() {
System.out.println("Welcome to the Exam Average Calculator");
}
public static void userPrompts() {
System.out.println("Please enter your 1st exam score.");
double examScore1;
examScore1 = console.nextDouble();
System.out.println("Please enter your 2nd exam score.");
double examScore2;
examScore2 = console.nextDouble();
System.out.println("Please enter your 3rd exam score.");
double examScore3;
examScore3 = console.nextDouble();
}
public static void display() {
double examAverage = 0;
}
public static double examAverage(double examScore1, double examScore2, double examScore3, double sum, double NUM_EXAMS) {
double Average;
sum = examScore1 + examScore2 + examScore3;
Average = (double) sum / NUM_EXAMS;
return Average;
}
public static void displayAverage(double Average) {
Object[] examAverage = null;
System.out.println("Your exam average is %.2f%", examAverage);
}
public static double examAverage(double examScore1, double examScore2, double examScore3) {
double Average;
{
return double Average
I don't want to do your homework for you but you call a method with paramaters severals times in your code. For example inside your main:
examAverage(examScore1, examScore2, examScore3)
you call the examAverage method passing in 3 variables. Your three variables are all set to 0, so that makes no sense. you probably should call your userPrompts before you call your examAverageMethod to initialize your examscores.
your program looks like it's almost done, think about the order of how you want to do it. good luck
So your exam average function is all messed up, what you want is it to take number of exams and the individual values and return the average.
So you make the function like this because you don't need to have sum as a parameter.
public static double examAverage(double examScore1, double examScore2, double examScore3, double NUM_EXAMS) {
double Average;
double sum = examScore1 + examScore2 + examScore3;
Average = sum / NUM_EXAMS;
return Average;
}
So when you call this function, you need to give it 4 values
so call it like this
double Average = examAverage(examScore1, examScore2, examScore3, 3);
That should solve your issue with the function. Let me know if I didn't explain it clearly enough or if you want me to elaborate.
You also have an issue on what order you call your code.
First, you want to welcome the user, then you want to ask them for their values, then you want to use those values to calculate the average and then you want to print that average so do this instead.
//declare variable
double Average;
double examScore1 = 0;
double examScore2 = 0;
double examScore3 = 0;
//Welcomes user, then prompts for exam values, calculates average using those values, and finally displays the average
printWelcome();
userPrompts();
double Average = examAverage(examScore1, examScore2, examScore3, 3);
System.out.println("your average is" + Average)
Also, delete your Display() and DisplayAverage() functions, they are useless.
On way would be to call your variables static by defining at class level like:
private static double examScore1 = 0;
private static double examScore2 = 0;
private static double examScore3 = 0;
Other best way would be to wrap all these variables in a class (or better create a list/array) and pass that call in userPrompts method and populate it and then using same object you calculate average.
Regarding looping, here's how you could do it:
create a counter and initialize it with 0.
while count <= 3
do
ask input from user
calculate average
display the average
done

How do I execute certain commands dependent on type of input

I have a Scanner set up to ask the user to either input a number or to input "EXAMPLE" to use preset numbers. If they input a number, the code is supposed to ask them more questions and then calculate that. That executes perfectly. If the user inputs "EXAMPLE", it is supposed to set the variables to preset numbers and calculate. I can't get the code to work when EXAMPLE was entered. I get this error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextFloat(Unknown Source)
at CarPool.main(CarPool.java:22)
This is my code: Sorry if it is so messy.
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Scanner;
public class CarPool {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
//inputs the scanner tool
float totaldistance;
float MPG;
float gasprice;
float gasused;
float totalpeople;
float totalcost;
//assigns variables
System.out.printf("Please type the total distance (miles) you are travelling, or type EXAMPLE for an example: ");
totaldistance = input.nextFloat();
if (isNan(totaldistance)) { //If the user types EXAMPLE, use preset numbers
totaldistance = 8;
MPG = 23;
gasprice = (float) 2.31;
totalpeople = 4;
} else if (isNumeric(totaldistance)); {
System.out.printf("Please enter the MPG of your vehicle: ");
MPG = input.nextFloat();
System.out.printf("Pleas enter the price of gas currently: $");
gasprice = input.nextFloat();
System.out.printf("Please enter how many people will be splitting the cost of gas:");
totalpeople = input.nextFloat();
//Prompts the user for some info that it can use for it's calculations. Sets them as floats for decimal numbers.
}
gasused = (totaldistance / MPG); //This finds how much gas the person is using by dividing the distance travelled by the mpg
totalcost = gasused * gasprice; //This calculates how much you will spend by multiplying the gas you use by the price of gas, given by the user
totalcost = totalcost / totalpeople; //splits the final cost amongst however many people are chipping in
NumberFormat formatter = new DecimalFormat("$" + "#0.00"); //Formats the price to two decimal places
System.out.println(formatter.format(totalcost)); //prints the final results
}
private static boolean isNumeric(float totaldistance) {
return false;
}
private static boolean isNan(float totaldistance) {
return false;
}
}
I'm having issues at line 22.
Obviously you will get a mismatch exception because if user enters examples you are reading it as float now you tell me can java convert example into float. no right??
So why dont you read the input data as string and check if it is example then use your preset values otherwise if it float use then accordingly
I think you should get my point.
cheers

Categories