Code Format, Structure, consistency - java

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..

Related

Questions about creating UML Class diagram from Java program - default constructor? Are there no attributes in this example?

I have a class where I have to manually create a UML diagram for the program below. In order to understand better, I automatically created a UML diagram in Eclipse with ObjectAid.
I have a few questions I would like to understand:
Of the three sections class, attributes, and methods, why is "PayrollDialog()" included in the methods section? Is it because you should always include the default constructor?
Are JOptionPane.showInputDialog really not considered for the methods section? Why not? I ask because I notice getting the user name, hours worked, and pay rate are not included.
Are there really no attributes to be listed in the UML for this program? I think this is correct because they are not listed under the public class PayrollDialog.
Is the UML diagram listed really accurate for this program? If not, what should it look like? I find it hard to believe the assignment is that simple.
import javax.swing.JOptionPane;
/**
4 * This program demonstrates using dialogs
* with JOptionPane.
*/
public class PayrollDialog
{
public static void main(String[] args)
{
String inputString; // For reading input
String name; // The user's name
int hours; // The number of hours worked
double payRate; // The user's hourly pay rate
double grossPay; // The user's gross pay
// Get the user's name.
name = JOptionPane.showInputDialog("What is " +
"your name? ");
// Get the hours worked.
inputString =
JOptionPane.showInputDialog("How many hours " +
"did you work this week? ");
// Convert the input to an int.
hours = Integer.parseInt(inputString);
// Get the hourly pay rate.
inputString =
JOptionPane.showInputDialog("What is your " +
"hourly pay rate? ");
// Convert the input to a double.
payRate = Double.parseDouble(inputString);
// Calculate the gross pay.
grossPay = hours * payRate;
// Display the results.
JOptionPane.showMessageDialog(null, "Hello " +
name + ". Your gross pay is $" +
grossPay);
// End the program.
System.exit(0);
}
}
Yes you are basically correct.
JOptionPane is not listed in the Class Diagram because it is found in javax.swing.JOptionPane and its not globally declared as property/attribute or method of your PayrollDialog class.
Based on your source code, there are no global properties/attribute declared.
For example
class PayrollDialog{
static JFrame f; // this would appear as property in UML
public static void main(String[] args){..}
}

OOP Ticket Price Program

So this one is a bit lengthy. I'm trying to finish off a program where ticket price varies depending on purchase date. I need the Tester.Java to take the info from the objects, and output the proper price depending on the ticket type. I have already set a set of if statements in the Tester, but I am now at an impass on how to finish this program off. I will paste my code below.
Tester (contains the main method):
package tester;
import java.util.Scanner;
public class Tester extends Ticket{
/**
* #param args the command line arguments
*/
public static void main(String[] args){
Scanner db = new Scanner(System.in);
Ticket firstTicket = new Ticket();
System.out.println("The first ticket: "+firstTicket.toString());
int x = 0;
while(x!=2){
if(x==2){
System.out.println("Goodbye.");
}
else{
System.out.println("What type of ticket are you purchasing?");
System.out.println("1.Walk Up");
System.out.println("2.Advance");
System.out.println("3.Student Advance");
int t = db.nextInt();
if(t==1){
}
if(t==2){
}
if(t==3){
}
}
System.out.println("Do you need another ticket?");
x= db.nextInt();
}
}
}
Ticket (Super class):
package tester;
import java.util.Scanner;
public class Ticket {
public int ticket;
public double price;
/**
* holds default values for ticket number and price
*/
public Ticket(){
super();
this.ticket=1;
this.price=15.0;
}
/**
* Stores the values for ticket number and the price, based upon ticket type
* #param ticket
* #param price
*/
public Ticket(int ticket, double price){
this.ticket=ticket;
this.price=price;
}
/**
* returns the value of price
* #return price
*/
public double getPrice(){
return price;
}
#Override
public String toString(){
return "Ticket #" + ticket + " Ticket price: $"+ price;
}
}
Walkup Ticket:
package tester;
/**
*
* #author dylan
*/
public class WalkupTicket extends Ticket{
/**
* holds the price of a walkup ticket 50$
*/
public WalkupTicket(){
this.price=50;
ticket++;
}
}
Advance Ticket:
package tester;
import java.util.Scanner;
public class AdvanceTicket extends Ticket {
/**
* stores the values of an advance ticket, depending on how many days before
* the event it is purchased
*/
public AdvanceTicket(){
Scanner db = new Scanner(System.in);
System.out.println("How many days before the event are you purchasing your ticket?");
int days = db.nextInt();
// days before is 10 or less days
if(days >= 10){
price=30;
ticket++;
}
// days before is more than 10
else{
this.price=40;
ticket++;
}
}
}
Student Advance Ticket:
package tester;
import java.util.Scanner;
public class StudentAdvanceTicket extends AdvanceTicket{
/**
* stores the values of an advance ticket, depending on how many days before
* the event it is purchased, with student discount.
*/
public StudentAdvanceTicket(){
Scanner db = new Scanner(System.in);
System.out.println("How many days before the event are you purchasing your ticket?");
int days = db.nextInt();
System.out.println("Are you a student?");
System.out.println("1. Yes");
System.out.println("2. No");
int stud = db.nextInt();
// days before is 10 or less days
if(days >= 10 && stud == 1){
price=15;
ticket++;
}
// days before is more than 10
if(days <= 10 && stud == 1){
this.price=20;
ticket++;
}
}
}
I feel like I'm making a simple mistake, but I am new to OOP so I'm having bit of trouble with this.
Are you supposed to be saving a total for all tickets bought or just the one ticket at a time total?
For walk-up tickets you don't have to do anything. Its a flat $50 total.
For Advance and StudentAdvance you would create a new object of that type and the way you have it the constructor will display the menu for how many days in advance and what not. You can then get the total from that.
As for the structure of your code it is not ideal. The object's constructor should not have all that code in it. They should have a ShowMenu function that will display the menu to the user and read their input. The constructor should be blank for the most part.
You also don't need three different ticket objects. One ticket object should be able to handle all this by itself. The ticket object can show the menu and handle the different prices based on user input. If you need to save a total or the different tickets you can have an array of ticket objects on the main method. You can then loop through that array to display or sum the tickets.
Hope this helps.
Your question is pretty broad, but well, some thoughts on your input:
Names matter. It is good that you made a first step and that you are using a specific package (instead of the default package); but tester says nothing. You could call it dylan.tickets for example: to make clear A) its your thing and B) it is about that ticket system
It seems that you are serious about your work, thus: do not use a static main to drive testcases. Using JUnit and simple testcases is really easy. And beyond that: driving tests "manually" using a main is cumbersome and error prone. Unit tests are almost automatically automated.
More importantly: tests that just print something are almost useless. If your code behaves unexpectedly, you might only notice when you carefully check that printed output. As said: use unit tests, and Junit assert calls to check expected versus actual results of method calls. Because then you will be told when you make changes that break functionality which was previously working.
You absolutely avoid to ask for user input in so many different places. Meaning: the reasonable thing is that a class has a constructor or setter methods; and that all the arguments required to instantiate the new object are given to that object. If at all, your main uses a scanner and asks the user for input. But all your "business logic" objects do not require any "user interaction" at all. You see, you actually want to start the whole project without using a scanner. You want to hardcode things like AdvancedTicket at = new AdvancedTicket(100); - because now you can easily code all kinds of different objects; and start your program again and again. Your current solution requires you to enter all such data manually ... every time you re-start your program! So: no scanner usage in constructors. Never!
Then: good OO is about behavior, not about state. Meaning: you dont use public fields to spread information. If at all, your fields should be protected; but even that is most often not a good idea. You want to isolate your classes from each other ...
The core problem: it seems that nobody told you yet about FCoI. You should favor composition over inheritance. Meaning: you dont just put A extends B everywhere. There is absolutely no reason that your Tester class extends Ticket. The tester is a Tester, not a ticket!
As said: that last point is the most important one. You are careful about making A a subclass of B; very often, it is more appropriate to maybe have A own a B object, but not to make A a B!

Amortization Table

This program will calculate the amortization table for a user. The problem is my assignment requires use of subroutines. I totally forgot about that, any ideas on how to modify this to include subroutines?
public class Summ {
public static void main(String args[]){
double loanamount, monthlypay, annualinterest, monthlyinterest, loanlength; //initialize variables
Scanner stdin = new Scanner (System.in); //create scanner
System.out.println("Please enter your loan amount.");
loanamount = stdin.nextDouble(); // Stores the total loan amount to be payed off
System.out.println("Please enter your monthly payments towards the loan.");
monthlypay = stdin.nextDouble(); //Stores the amount the user pays towards the loan each month
System.out.println("Please enter your annual interest.");
annualinterest = stdin.nextDouble(); //Stores the annual interest
System.out.println("please enter the length of the loan, in months.");
loanlength = stdin.nextDouble(); //Stores the length of the loan in months
monthlyinterest = annualinterest/1200; //Calculates the monthly interest
System.out.println("Payment Number\t\tInterest\t\tPrincipal\t\tEnding Balance"); //Creates the header
double interest, principal; //initialize variables
int i;
/* for loop prints out the interest, principal, and ending
* balance for each month. Works by calculating each,
* printing out that month, then calculating the next month,
* and so on.
*/
for (i = 1; i <= loanlength; i++) {
interest = monthlyinterest * loanamount;
principal = monthlypay - interest;
loanamount = loanamount - principal;
System.out.println(i + "\t\t" + interest
+ "\t\t" + "$" + principal + "\t\t" + "$" + loanamount);
}
}
}
any ideas on how to modify this to include subroutines?
Well, you are better off doing it the other way around; i.e. working out what the methods need to be before you write the code.
What you are doing is a form or code refactoring. Here's an informal recipe for doing it.
Examine code to find a sections that perform a specific task and produces a single result. If you can think of a simple name that reflects what the task does, that it a good sign. If the task has few dependencies on the local variables where it currently "sits" that is also a good sign.
Write a method declaration with arguments to pass in the variable values, and a result type to return the result.
Copy the existing statements that do the task into the method.
Adjust the new method body so that references to local variables from the old context are replaced with references to the corresponding arguments.
Deal with the returned value.
Rewrite the original statements as a call to your new method.
Repeat.
An IDE like Eclipse can take care of much of the manual work of refactoring.
However, the real skill is in deciding the best way to separate a "lump" of code into discrete tasks; i.e. a way that will make sense to someone who has to read / understand your code. That comes with experience. And an IDE can't make those decisions for you.
(And did I say that it is easier to design / implement the methods from the start?)
I deleted my previous comment as I answered my own question by reading the associated tags :-)
As an example, define a method like this in your class:
public double CalculateInterest(double loanAmount, double interestRate) {
//do the calculation here ...
}
And then call the method by name elsewhere in your class code e.g.
double amount = CalculateInterest(5500, 4.7);

passing user input to methods 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.

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));

Categories