passing user input to methods java - java

Hey guys i am a complete beginner in java and i am trying to write a program that goes this way:
painting company has determined that for every 115 square feet of wall
space, one gallon of paint and eight hours of labor will be required.
The company charges $18.00 per hour for labor.
Write a program that allows the user to enter the number of rooms to
be painted and the price of the paint per gallon. It should also ask for
the square feet of wall space in each room. The program should have
methods that return the following data:
The number of gallons of paint required
The hours of labor required
The cost of the paint
The labor charges
The total cost of the paint job
Then it should display the data on the screen
this is what i have so far. i can get the user input and the number of gallons but when i try to calculate the number of hours of labor what it does is it calculates the labor from the result of the previous calculation which is not what i want..this is what i have so far
int resultnumberofhours = hoursoflabor(numberofsquarefeet,115,8);
System.out.println("the number of hours needed are " + resultnumberofhours);
}
public static int hoursoflabor(int numberofsquarefeet, int squarefeet,int labor){
int resultnumberofhours = numberofsquarefeet/115*8;
return resultnumberofhours;
}

Rather then taking one by one you can try code like this
Scanner dd = new Scanner(System.in);
int[] vars = new int[5];
for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}

The only problem that I can see with the code is that you are not doing anything with the results. Try the following:
int result = numberofsquarefeet(numberofsquarefeet, 115, 1);
System.out.println("Number of square feet: " + result);
When returning something from a java function you can either assign that value to a variable of the same type you specify as the return type of the function, or you can use the output in a print statement for example. If you do nothing with the output, that result is lost.
Hope this helps.

You have to either print the result at the end:
System.out.println("enter number of square feet");
numberofsquarefeet = Keyboard.nextInt();
int resultSqFeet = numberofsquarefeet(numberofsquarefeet, 115, 1);
System.out.println("number of square feet is" + resultSqFeet);
}
or inside the methods:
public static int numberofsquarefeet(int numberofsquarefeet, int squarefeet, int paint) {
int result = numberofsquarefeet / 115 * 1;
System.out.println("number of square feet is " + result);
return result;
}
The same goes with hoursoflabor

I suggest you step back from writing the code and analyze your problem a bit first.
You have a data model and a process which you can describe in more detail. This will help you come up with a good design for your classes and methods. If you immediately start writing code, especially as a beginner, it usually ends up like a pile of spaghetti.
Here is my suggestion for the data model:
PaintingCompany
PAINT_GALLONS_PER_SQUARE_FOOT = 1 / 115
LABOR_HOURS_PER_SQUARE_FOOT = 8 / 115
LABOR_DOLLARS_PER_HOUR = 18
Room
wallSpaceSquareFeet
Paint
dollarsPerGallon
gallons
calculatePaintCostInDollars()
Project
rooms
paint
calculateGallonsOfPaintRequired()
calculateHoursOfLaborRequired()
calculateLaborChargesInDollars()
calculateTotalCostInDollars()
Note that the PaintingCompany class only contains constants. You could put the main() method in this class if you like.
The type and amount of paint are modeled as a single class 'Paint'. You could argue this is inaccurate and have a separate PaintType (enum) representing known types of paint and their prices but I figured this was feature creep at this point. So with the model above you need to instantiate a Paint instance with the correct price and then set the amount of paint on it. The Paint class will then have a function to calculate the total paint price.
It would be an idea to model the units explicitly. The model is now fixed on dollars and gallons but in future you might wish to switch to euros and liters in order to sell the application in Europe. For now I didn't model units because it probably over complicates the exercise. To avoid confusion it is important that the units are specified clearly as part of the variable or method name Space rockets have been known to crash due to errors of this genre.
The process could look like this:
Create a new Project
Ask the user for the paint price
Set the paint price on the project's Paint object
Start an iteration:
Add a new Room object to the Project
Ask the user for the wall space of the Room in square feet
Ask the user if there is another room
If yes, iterate from step 4
If no, print a report with the required project data
Note that some of these process steps are good candidates for separate classes:
Iteration could be put in the PaintingCompany class
Getting input from the user. It's good to keep this separate so you can easily change it later without affecting other code.
Printing the report. Reporting is usually a bit complex, has output formatting etc and is a nice separate concern. You also want to be able to change the report implementation without affecting other code.
If you post new code based on this (or your own) design I am happy to comment on it or help you with any questions.

Related

Can someone help analyse my java code on an averaging program?

Hi so I've started learning java online for two weeks now, but as I watched those tutorials, I felt the only way I'd actually grasp that information was to practice it. My other programs worked great, but just when I decided to do something spectacular (for me only of course; a java expert would find creating this program mind-numbing), something went terribly wrong. I'd really appreciate if you could take a look at my code below of an averaging program that could average any amount of numbers you want, and tell me what in the world I did wrong.
UPDATE: Eclipse just outputs a random number after typing in just one number and then shuts down the program.
Here is a snapshot where I type in the console to average 6 numbers and then start with the number 7, but for some reason, when I hit enter again, it outputs 8.
package justpracticing;
import java.util.*;
public class average{
int grade = 0;
int average;
Scanner notoaverage = new Scanner(System.in);
System.out.println("Please enter the amount of numbers you'd like the average of! ");
final int totalaverage = notoaverage.nextInt();
Scanner averagingno = new Scanner(System.in);
System.out.println("Start typing in the " + totalaverage + " numbers");
int numbers = averagingno.nextInt();
int counter = 0;
public void averagingnumbers(){
while(counter<=totalaverage){
grade+=numbers;
++counter;
}
}
public void printStatement(){
average = grade/totalaverage;
System.out.println(average);
}
}
It seems that you have created an average Object in another class, and are calling the methods given from a main class.
I don't know what exactly you're having trouble with, but one problem is here:
average = grade/totalaverage;
These 2 variables that you are dividing are both integers. That means that the result will also be an integer. This is called truncation. What you want to do is first convert at least one of the integers to a double:
... = (grade * 1.0) / totalaverage;
You also want your average variable to be a double instead of an integer so that it can be a lot more accurate.

If and if else again

The problem I seem to be having is that I am unsure on how to make the program recognize if the player is in one of the "MVP" positions (C,SS,CF) before moving forward with my program logic.
These three positions qualify for "MVP" status only if their OPS is above 800 for everyone else, it has to be 900 or above to be considered for "MVP".
Once again, I am having trouble with the "if" and "if else" statement.
Again, This IS school given problem and I don't want the answer. Only insight into what I am doing wrong. I want to learn this not have it done for me. Thank you in advance.
import java.util.Scanner;
public class baseBall {
public static void main(String[] args) {
/* A good part of a baseball player's offensive value is captured by the
statistic OPS - the sum of the player's on base percentage and slugging
percentage. An MVP candidate will typically have an OPS above 900,
however if they play a difficult defensive position (catcher, shortstop, or center field)
then they are an MVP candidate if their OPS is above 800. Write a program that will prompt the user for
a player's name, their on base percentage, slugging percentage, and defensive position and report whether the player is an MVP candidate*/
Scanner input = new Scanner(System.in);
System.out.println("Please enter players name: ");
String name = input.next();
System.out.println("Please enter On Base Percentage: ");
double Obp = input.nextDouble();
System.out.println("Please enter slugging Percentage: ");
double Slg = input.nextDouble();
System.out
.println("Please enter position (P,C,1B,2B,3B,SS,LF,CF,RF): ");
String ball = input.next();
String position;
double Ops = Obp + Slg;
if ( position.equalsIgnoreCase("ss")){
if (position.equalsIgnoreCase("cf")){
if (position.equalsIgnoreCase("c")){
System.out.println("MVP Candidate!");
else
System.out.println("NOT an MVP Candidate!);
}
}
}
}
}
Try doing it without nested IFs. Instead, try using Boolean operators like AND and OR.
As previously stated try using a paper first. Try drawing a decision tree to see what and where it might be going wrong.
Your code is checking if the player position is c AND ss AND cf. But the player will be only in one position, it can't be in all the three, so your code will always print "Not an MVP Candidate!".
To make it simple your code is checking if the position is c AND ss AND CF, instead you want to check if the position is c OR ss OR cf.
So you have to use the conditional operator OR -> ||:
if(position.equalsIgnoreCase("ss") || position.equalsIgnoreCase("cf") || position.equalsIgnoreCase("c") {
System.out.println("MVP Candidate!");
} else {
System.out.println("NOT an MVP Candidate!);
}
Your nested ifs will never be true. Think about this logically and on paper.
If position equals ss how can it equal cf and c at the same time? Always ask yourself: "does this make sense?" -- do this before committing code to screen and you'll be golden.
As a side recommendation, please get rid of those distracting // from your question text. They serve no purpose other than to annoy.

Can't understand this scanner or addition command

I'm very new to Java and don't quite understand it all fully, I'm working on a Uni workshop assignment but am having trouble with this particular question.
"Write a program that asks the user to enter how many minutes they have used, and how many texts they have used.
Both inputs should be whole numbers (integers).
The program should then calculate the user’s mobile phone bill, assuming that texts cost 7p and calls 12p.
Should display price of calls, texts and the total bill, both figures added together"
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
String one = userInput.nextLine();
System.out.println("How many texts have you used?");
String two = userInput.nextLine();
int a = 12;
int b = 7;
System.out.println("The total cost of your minutes is "+one);
System.out.println("The total cost of you texts is "+two);
System.out.println("The total cost of your phone bill is "+one + two);
I have the basic part to the question figured out, but can't figure out why I can't add to the code for it to figure out the price, being 12 p for minutes, and 7p for texts. As well as this I can't get the total cost of the phone bill to add together correctly. I did earlier and I know it's very easy, but I've completely forgotten how to do it.
I know I need to be able to understand a scanner better, but I did the previous tasks easy enough but this has really stumped me tbh. Do I need to rename the scanner, but when I change the name of the integer line to something like "totalCostOfTexts/Minutes etc" it either says it has already been defined, or is missing some kind of symbol.
Any feedback is appreciated.
I add the code :
int = userInput = minutes * 12:
As that's what is used in the previous part of a similar question, but all the feedback I get is that it is not a statement, so it can't process. I'm really struggling with this tbh.
Following code will work for you
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
int one = userInput.nextInt();
System.out.println("How many texts have you used?");
int two = userInput.nextInt();
int a = 12; //don't use such variable names
int b = 7;
int minute_bill=12*a; //see the variable,will make things easier to review
int text_bill=7*b;
int result=minute_bill+text_bill;
System.out.println("The total cost of your minutes is "+minute_bill);
System.out.println("The total cost of you texts is "+ text_bill);
System.out.println("The total cost of your phone bill is "+result);
and also
You can use Scanner's nextInt() method for taking integer input
from console.
Don't use such variable names like a,b etc. define them according to the attribute whose value you are storing in them (see above minute_bill and text_bill are making the code clean and easy to review)
And if you are bound to get String value from console,but want to convert entered value to Integer later on, then you can do it like following code
String mystring=userInput.nextLine(); //userInput is user Scanner's object
int num=Integer.parseInt(mystring);
I think this is what you want to do...
Scanner userInput = new Scanner(System.in);
System.out.println("How many minutes have you used?");
int one = Integer.valueOf(userInput.nextLine());
System.out.println("How many texts have you used?");
int two= Integer.valueOf(userInput.nextLine());
int a = 12;
int b = 7;
System.out.println("The total cost of your minutes is "+ (one * 12);
System.out.println("The total cost of you texts is "+ (two * 7));
System.out.println("The total cost of your phone bill is "+ ((one * 12) + (two * 7));

Code Format, Structure, consistency

Hello I am a beginner and currently trying to learn java programming.
The question in the textbook:
Write a program that helps a person decide whether to buy a hybrid car. Your program’s inputs should be:
•The cost of a new car
•The estimated miles driven per year
•The estimated gas price •The efficiency in miles per gallon
•The estimated resale value after 5 years
Compute the total cost of owning the car for five years. (For simplicity, we will not take the cost of financing into account.) Obtain realistic prices for a new and used hybrid and a comparable car from the Web. Run your program twice, using today’s gas price and 15,000 miles per year. Include pseudocode and the program runs with your assignment.
My question: I got the code right, my program runs perfectly. My main concern is how can I present this in a professional manner. How can I structure it professionally, what would I have to do in order to have it published (for example). I am trying to get in the habit of having my codes organized and neatly presented. Any suggestions would help, thanks!
public class car
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Car Model: ");
String carModel = in.nextLine();
System.out.print("Cost of Car: ");
int costOfCar = in.nextInt();
System.out.print("The estimated miles driven per year: ");
int milesDriven = in.nextInt();
System.out.print("The estimated gas price: ");
int gasPrice = in.nextInt();
System.out.print("Efficiency in miles per gallon: ");
int milesPerGallon = in.nextInt();
System.out.print("Estimated resale value after 5 years: ");
int retailValue = in.nextInt();
double carEfficiency = (double) gasPrice / milesPerGallon;
double milesDrivenCost = (double) milesDriven * carEfficiency * 5; //5 years of driving
double retailValueInFiveYears = retailValue;
double carUseLoss = costOfCar - retailValueInFiveYears;
double totalCost = carUseLoss + milesDrivenCost;
System.out.print(carModel + " will cost you after 5 years: ");
System.out.format(" %,d%n", Math.round(totalCost));
}
}
I hope that's not your real indentation.
Use Java naming conventions. In particular, class car should be 'Car'.
I would have said add a few comments, but variable names are pretty descriptive.
Add JavaDoc comments to the class and to the main method.
Always close resources explicitly.
The user could want to enter several of the inputs with decimals. Use doubles instead of ints. Scanner will accept numbers with no decimals too.
Perhaps you could include the generated JavaDoc HTML output.
Java code:
import java.util.Scanner;
/**
* Computes a car's 5-year cost of ownership.
* Usage:
* java Car
*
* #author Mario Rossi
*/
public class Car {
/**
* Computes a car's 5-year cost of ownership.
*
* #param args Not used.
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Car Model: ");
String carModel = in.nextLine();
System.out.print("Cost of Car: ");
double costOfCar = in.nextDouble();
System.out.print("Estimated miles driven per year: ");
double milesDriven = in.nextDouble();
System.out.print("Estimated gas price in $ per gallon: ");
double gasPrice = in.nextDouble();
System.out.print("Efficiency in miles per gallon: ");
double milesPerGallon = in.nextDouble();
System.out.print("Estimated resale value after 5 years: ");
double retailValueInFiveYears = in.nextDouble();
in.close();
double carEfficiency = gasPrice / milesPerGallon;
double milesDrivenCost = milesDriven * carEfficiency * 5; //5 years of driving
double carUseLoss = costOfCar - retailValueInFiveYears;
double totalCost = carUseLoss + milesDrivenCost;
System.out.print(carModel + " will cost you after 5 years: ");
System.out.format(" %,.2f%n", totalCost );
}
}
First of all you need to use the Object Oriented approach i.e. follow the rules:
Abstraction : Identify the entities as classes and their attributes
and operations. you have created a class Car but not defined its
attributes and operations properly so think around it.
Enacapsulation: Data hiding, make sure you use the proper access
specifiers for your Class attributes and operations
Inheritence: Car is quite an abstract thing, so you better define an
abstract class. And inherit real classes such as Ford Car, Merc Car
from your base Car class.
Polymorphism : When you define your Car and its subclasses, you may
have to override the methods define in your abstract class into your
child classses.
Packaging the software: You can do it in multiple ways:
Package it is an executable jar, so a user can simply double click it and run
Create an exe file, which internally calls your java code.
etc
you may have to write a release note or a small documentation to mention that jre should be installed on the computer, path should be set etc.
hope it helps!
as you said you are beginner and started to learn the java, you should always keep the following things in mind,
As Java is object oriented and your program is like as c program you must use the OOPs concepts like class, object and all.
While writing the program you should use the proper indentation.
While giving names for variables, methods use proper naming conventions and don't forget to give comments so that new users can get for what purpose what things you have given.
As you learn new thing try to implement these in your programs or in project.
Try the packages and try to keep small classes and programs so that you will not get confused in the future as well as other users too.
If you find this answer is useful then don't forget to mark as accepted..

How to write a method to calculate compound interest by the year?

public class Balance {
public static void main(String[] args) {
System.out.printf("%.2f\n", balance(0.0, 0.0, 0.0));
}
/**
* #param principal
* #param rate
* #param years
* #return
*/
public static double balance(double principal, double rate, double years) {
double amount = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the initial investment amount: ");
principal = sc.nextDouble();
System.out.print("Enter the interest rate: ");
rate = sc.nextDouble();
System.out.print("Enter the number of years: ");
years = sc.nextDouble();
for (int i = 1; i < years; i++) {
amount = principal * Math.pow(1.0 + rate, years);
amount += principal;
}
return amount - principal;
}
}
My problem is with the printf line that I am using within the main method. Eclipse wants me to change the method balance from void to Object[]. When I do this I must return a value from balance. So I guess my question is, how would I return the proper value? Am I on the right track? Thank you for your time and constructive criticism. :)
EDIT - Thanks for the help everyone, much appreciated :) My math is off. I end up with 1000 more than I should have. hmmm.
So should I just take a 1000 from amount like so:
return amount - 1000;
Or this:
return amount - principal;
EDIT this is what I am going with since it is due tonight. Thanks to all for the assistance. :)
A few points:
balance() cannot be void, because you use its return value in S.out.printf(). Do you want balance to print to the screen, or do you want it to yield a number?
Your loop for (years = 0; years > 10; years++) won't run. Think about why. It might help to convert the for into a while, to visualize why.
You read in years as a double, but then use it as a counter in your loop. What type should it actually be?
Your balance() function takes three parameters, then immediately gets input and obliterates them. Do you want balance() to be provided these numbers, or do you want it to fetch them?
Otherwise, you seem to be on the right track.
The problem is that balance doesn't return anything, (it's a void function). Change it to:
public static double balance(double principal, double rate, double years) {
...
And inside that function, return the balance.
Java is telling you it wants an Object[] because printf is defined like this:
public static void printf(String format, Object ... params) {
// params is an Object[]
}
What this lets you do is pass parameters like this:
printf("some string", first, second, etc);
It lets you pass as many parameters as you want, and the function can handle them as if you passed an array.
It's exactly the same as if it was defined like this:
public static void printf(String format, Object[] params);
And you used it like this:
printf("some string", new Object[] { first, second, etc});
It's just easier to use.
EDIT:
The other option is to not print anything in main, but I would definitely advise returning the result and printing it in main. This follows the principle of making each function do as little as possible. balance should just calculate the balance. Printing it is unrelated.
Please consider a more drastic re-working of your code; as it is, your balance() function is doing all the work of your program (and your printf() line feels like an afterthought). If you break apart your code based on what the code does, I think you can do much better:
create a function that prompts the user and then reads in their input
create a function that calls the previous function three times for principal, rate, and years
create a function that computes and populates a payment schedule. Keep track of year, balance, payment, principal payment, and interest payment. (Or just the variables you're interested in -- but be aware that programs tend to grow new features, and these variables are often the second thing that users (or professors) ask to know when paying down a loan.)
create a function that prints the selected columns from your payment schedule.
create a function that orchestrates the previous functions.
When you re-write your program to use a GUI or webservice in three weeks, you'll definitely thank yourself for having written each function to do one task, and do it well. You'll also find it far easier to test smaller pieces of code that do only one task.
There is the risk of over engineering a too-generic solution -- what I'm really trying to suggest is a functional decomposition of your code into multiple smaller routines that do exactly what their name says. You might never move the program into a GUI or webservice or whatever, but you'll definitely be happier when someone reports that your amortization schedule is wrong, that you can control it via simpler programming, rather than having to re-type inputs all day long.
Yours is wrong, do this:
public static void main(String[] args) {
balance(1000.0, .05, 8.5);
}

Categories