I am a novice programmer who is learning Java and though my homework is complete I want to make it neater. I wanted to know if I can combine the following print methods into one and at least combine Kilograms to Pounds and Pounds to Kilograms Methods into one.
Note, I can't use anything more advanced then if statements and loops.
Because this is my first time posting and I want to make sure I provide all answerers with adequate information I have uploaded my Weight Conversion java file to here: Weight Conversion Java file.
Any other advice as to how to simplify the code, or following better code etiquette is welcomed too.
Here are the print statements:
/**
* This method below prints the calculations calculateKG and calculateLBS
*/
public static void printRESULTS1( double dResult1, double dResult2){
// Prints the result of Pounds to Kilograms
System.out.print(dResult1 + " pounds is " + dResult2 + " kilograms.");
}// end method printRESULTS1
/**
* This method below prints the calculations calculateKG and calculateLBS
*/
public static void printRESULTS2( double dResult1, double dResult2){
// Prints the result of Pounds to Kilograms
System.out.print( dResult1 + " kilograms is " + dResult2 + " pounds");
}// end method printRESULTS2
/**
* This method below prints the calculations calculateOZ and calculateLBS
*/
public static void printRESULTS3( double dResultOZ, double dResultLBS){
// Prints the result of Pounds to Kilograms
System.out.print( dResultOZ + " ounces is " + dResultLBS + " pounds");
}// end method printRESULTS3
/**
* This method below prints the calculations calculateOZ and calculateLBS
*/
public static void printRESULTS4( double dResultLBS, double dResultOZ){
// Prints the result of Pounds to Kilograms
System.out.print( dResultLBS + " pounds is " + dResultOZ + " ounces ");
}// end method printRESULTS4
For a start, consider this:
public static void printResults(
double dResultFrom,
String from,
double dResultTo,
String to)
{
System.out.print(dResultFrom + " " + from + " is " + dResultTo + " " + to);
}
Not sure about the whole context you're using it and about your limitations. Of course further refactoring steps are possible. For example:
public static void printResults(
double resultFrom,
String fromDescription,
double resultTo,
String toDescription)
{
String formattedResult = formatResult(
resultFrom,
fromDescription,
resultTo,
toDescription);
System.out.print(formattedResult);
}
public static String formatResult(
double resultFrom,
String fromDescription,
double resultTo,
String toDescription)
{
return formatQuantity(resultFrom, fromDescription)
+ " is "
+ formatQuantity(resultTo, toDescription);
}
public static String formatQuantity(double value, String description)
{
return value + " " + description;
}
Note much less code duplication than in your example, and a clear separation of responsibilities (formatting functions, and printing function). For example, if you had to print results to a file, not to the console, this design would prove more flexible.
Thanks for the help, it made me think harder as to how to simplify the code and organize it better. Also great advice on making sure that the code could be universal as in the print method could be used in another language that isn't English. What really helped was understanding that I can have more then 2 parameters in a Method.
public static void printRESULTS(int nConversion, double dResult1, double dResult2){
//Declare variable
String output = "";
//Pounds to Kilogram output
if (nConversion == 1){
output = dResult1 + " pounds is " + dResult2 + " kilograms.";
System.out.println(output);
}
//Kilograms to Pounds output
else if (nConversion == 2){
output = dResult1 + " kilograms is " + dResult2 + " pounds. ";
System.out.println(output);
}
//Ounces to Pounds output
else if (nConversion == 3){
output = dResult1 + " ounces is " + dResult2 + " pounds. ";
System.out.println(output);
}
//Pounds to Ounces output
else if (nConversion == 4){
output = dResult1 + " pounds is " + dResult2 + " ounces. ";
System.out.println(output);
}
Related
/**
* #param newProfitMarginParam is used to set the gained profit margin.
*/
public void setCalculateProfitMargin(double newProfitMargin){
this.profitMargin = (this.sellingPrice - this.dealerCost) / this.sellingPrice;
}
/**
* A method to calculate the profit.
*/
public void calculateProfit(){
double dollar = this.sellingPrice - this.dealerCost;
}
public void main(String[] printDetails){
System.out.println("Jalopies Are Us Vehicle Summary:");
System.out.println("Vehicle: " + this.year + " " + this.make + " " + this.model);
System.out.println("Stock code: " + this.stockCode);
System.out.println("Dealer Cost: $" + this.dealerCost);
System.out.println("Selling Price: $" + this.sellingPrice);
System.out.println("Profit Margin: " + this.profitMargin + "%");
System.out.println("Dollare Profit: $");
calculateProfit();
}
e.g. here I want to add those aforesaid method in the main method.
How can I do that?
I add the last statement in the main method and I didn't get any Syntex error, but I'm not sure if it's correct or not.
Also how can I add the first method as well?
These concepts may help you understand better what is wrong with your code: Java Modifiers
I'm trying to find out why the %.2f declaration when outputting a decimal isn't working in my code, I've checked other similar questions but I can't seem to locate the issue in the specific logic error I'm receiving. When I go to compile my program it compiles fine, I go to run it and everything outputs fine until I get to the final cost where I'm trying to only display that decimal value with 2 decimal places.
I get an exception in thread "main"
Java.util.illegalformatconversionexception f! = Java.lang.string
At java.util.Formatter$formatspecifier.failconversion(Unknown Source)
At java.util.Formatter$formatspecifier.printFloat(Unknown Source)
At java.util.Formatter.format(Unknown Source)
At java.io.printstream.format(Unknown Source)
At java.io.printstream.printf(Unknown Source)
At Cars.main(Cars.java:27)
Here is my code:
import java.util.Scanner;
public class Cars
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
int carYear, currentYear, carAge;
double costOfCar, salesTaxRate;
double totalCost;
String carModel;
System.out.println("Please enter your favorite car model.");
carModel = input.nextLine();
System.out.println("Please enter the year of the car");
carYear = input.nextInt();
System.out.println("Please enter the current year.");
currentYear = input.nextInt();
carAge = currentYear - carYear;
System.out.println("How much does the car cost?");
costOfCar = input.nextDouble();
System.out.println("What is the sales tax rate?");
salesTaxRate = input.nextDouble();
totalCost = (costOfCar + (costOfCar * salesTaxRate));
System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f",totalCost + " " + " dollars.");
}
}
I'm not exactly sure what's causing the issue.
Try:
System.out.printf("The model of your favorite car is %s, the car is %d years old, the total of the car is %.2f dollars.", carModel, carAge, totalCost);
Or the more readable:
System.out.printf("The model of your favorite car is %s," +
" the car is %d years old," +
" the total of the car is %.2f dollars.",
carModel, carAge, totalCost);
It's because %.2f is replaced with the entire second argument in that method call. The problem is that by specifying f in %.2f, you are saying that the second argument is a float or double. The second argument in this case is totalCost + " " + " dollars." which evaluates to a string.
To fix this problem, you need to make the second argument be a float or double. This can be achieved by moving + " " + " dollars." from the end of the second argument to the end of the first argument, like so:
System.out.printf("The model of your favorite car is" + carModel + ", the car is" + " " + carAge + " " + " years old, the total of the car is" + " " + "%.2f" + " " + " dollars.",totalCost);
You can also remove many of the unnecessary concatenations from that line, resulting in this:
System.out.printf("The model of your favorite car is" + carModel + ", the car is " + carAge + " years old, the total of the car is %.2f dollars.", totalCost);
The variable has to go as a parameter to the System.out.printf() function. The "%.2f" will be replaced by the double value that is passed as the second parameter.
For Example:
System.out.printf("The value is %.2f", value);
The same thing is true for other variable types and for multiple variables,
String str = "The value is: ";
double value = .568;
System.out.printf("%s %.2f", str, value);
This will output: "The value is: .57"
The project I am working on requires a bank account balance to be printed using a toString method. I am not allowed to add any methods to my current program, but I need to format my myBalance variable to a double that goes to two decimal places instead of one. In this particular instance my program should be printing 8.03, but it is printing 8.0.
Here is my toString method:
public String toString()
{
return"SavingsAccount[owner: " + myName +
", balance: " + myBalance +
", interest rate: " + myInterestRate +
",\n number of withdrawals this month: " + myMonthlyWithdrawCount +
", service charges for this month: " +
myMonthlyServiceCharges + ", myStatusIsActive: " +
myStatusIsActive + "]";
}
I am very new to Java still, so I would like to know if there is a way to implement %.2f into the string somewhere to format only the myBalance variable. Thank you!
Use String.format(...) for this:
#Override
public String toString() {
return "SavingsAccount[owner: " + myName +
", balance: " + String.format("%.2f", myBalance) +
", interest rate: " + String.format("%.2f", myInterestRate) +
",\n number of withdrawals this month: " + myMonthlyWithdrawCount +
", service charges for this month: " +
myMonthlyServiceCharges + ", myStatusIsActive: " +
myStatusIsActive + "]";
}
or more succinctly:
#Override
public String toString() {
String result = String.format("[owner: %s, balance: %.2f, interest rate: %.2f%n" +
"number of withdrawals this month: %d, service charges for this month: %.2f, " +
"myStatusIsActive: %s]",
myName, myBalance, myInterestRate, myMonthlyWithdrawCount,
myMonthlyServiceCharges, myStatusIsActive);
return result;
}
Note that khelwood asked about my use of "%n" for a new-line token rather than the usual "\n" String. I use %n because this will allow the java.util.Formatter to get a platform specific new-line, useful in particular if I want to write the String to a file. Note that String.format(...) as well as System.out.printf(...) and similar methods use java.util.Formatter in the background so this applies to them as well.
Use String.format()
Example :
Double value = 8.030989;
System.out.println(String.format("%.2f", value));
Output :
8.03
I get this error; bad operand types for binary operator '-'
All other operations work...when I leave out the subtraction via comments like // and /* */; can someone help?
This is the code by the way; the exception is on the subtraction line.
public class Calculator {
/*
*use 'javac Calculator.java' to compile;
*use 'jar cvf Calculator.jar Calculator.class' for jar;
*use 'java Calculator' to run;
*/
public static void main(String []args) {
String NewName
Scanner user_input = new Scanner( System.in );
System.out.println("Type your name please.");
NewName = user_input.next();
System.out.println("");
System.out.println("Hello " + NewName + ".");
System.out.println("I am Hunter's java calculator program.");
System.out.println("");
//mathematical input
String operator;
float cal1, cal2;
System.out.println("Type a Number...");
cal1 = user_input.nextFloat();
System.out.println("");
System.out.println("Type another Number...");
cal2 = user_input.nextFloat();
System.out.println("");
Scanner opt = new Scanner(System.in);
System.out.println("Enter an operator");
operator = opt.next();
//operation decisions
if (operator.equals("+")){
System.out.println("The answer is " + cal1+cal2 + ".");
}
if (operator.equals("-")){
System.out.println("The answer is " + cal1-cal2 + ".");
}
if (operator.equals("/")){
System.out.println("The answer is " + cal1/cal2 + ".");
}
if (operator.equals("*")){
System.out.println("The answer is " + cal1*cal2 + ".");
}
}
}
You need parenthesis:
System.out.println("The answer is " + (cal1-cal2) + ".");
Otherwise what you have is treated as
System.out.println(("The answer is " + cal1) - (cal2 + "."));
which is invalid since you can't subtract strings.
Why don't you have an error with the other operators? Well, * and / have higher precedences, so those are working as expected. +, on the other hand, is overloaded to concatenate strings:
System.out.println("The answer is " + cal1+cal2 + "."); // concatenates, doesn't add
For example, if call1 is 1 and call2 is 2, the result will be:
The answer is 12.
which isn't what you want. Again, this can be solved with parenthesis.
I'm coding a simulation of a sports game, and it works fine for the most part; compiles and runs like it should. The directions ask that I I assume that I am supposed to be using printf and %.2f, but whenever I try to incorporate that into my code, it ceases to run properly. Help would be much appreciated!
import java.util.Scanner;
public class Team {
public String name;
public String location;
public double offense;
public double defense;
public Team winner;
public Team(String name, String location) {
this.name = name;
this.location = location;
this.offense = luck();
this.defense = luck();
}
public double luck() {
return Math.random();
}
Team play(Team visitor) {
Team winner;
double home;
double away;
home = (this.offense + this.defense + 0.2) * this.luck();
away = (visitor.offense + visitor.defense) * visitor.luck();
if (home > away)
winner = this;
else if (home < away)
winner = visitor;
else
winner = this;
return winner;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter name and location for home team (on separate lines)");
String homeName = s.next();
String homeLocation = s.next();
Team homeTeam = new Team(homeName, homeLocation);
System.out.println("Enter name and location for home team (on separate lines)");
String awayName = s.next();
String awayLocation = s.next();
Team awayTeam = new Team(awayName, awayLocation);
Team winnerTeam = homeTeam.play(awayTeam);
System.out.printf("Home team is:" + homeName + " from" + homeLocation + " rated" + homeTeam.offense + " (offense) +" + homeTeam.defense + " (defense)" + "\n");
System.out.printf("Away team is:" + awayName + " from" + awayLocation + " rated" + awayTeam.offense + " (offense) +" + awayTeam.defense + " (defense)" + "\n");
System.out.printf("Winner is:" + winnerTeam.name + " from" + winnerTeam.location + " rated" + winnerTeam.offense + " (offense) +" + winnerTeam.defense + " (defense)" + "\n");
}
You have misunderstood the printf method. You do not concatenate strings the way you do in this line and its successors (reformatted for width reasons):
System.out.printf("Home team is:" + homeName +
" from" + homeLocation +
" rated" + homeTeam.offense +
" (offense) +" + homeTeam.defense +
" (defense)" + "\n");
This is like the way an old coworker tried to use PreparedStatements to prevent SQL injection attacks, but constructed the query string by concatenation anyway, making the attempt ineffective. Instead, look at the signature of printf:
public PrintWriter format(String format, Object... args)
The first argument is a format string, which contains static text and format directives beginning with %. In typical use, each format directive corresponds to one argument of the method. Replace the interpolated variables with directives.
Strings are usually formatted with %s: s for string. Doubles are usually formatted with %f: f for float (or double). Characters between the % and the letter are options. So, let's replace the strings you interpolated with directives:
"Home team is: " + "%s" + // Inserted a space.
" from" + "%s" +
" rated" + "%6.2f" + // Six characters, 2 after the decimal.
" (offense) +" + "%6.2f" +
" (defense)" + "%n" // %n means the appropriate way to get a new line
// for the encoding.
Now we put it all together:
System.out.format("Home team is: %s from %s rated %6.2f (offense) + %6.2f (defense)%n",
homeName, homeLocation, homeTeam.offense, homeTeam.defense);
This is a lot simpler. Additionally, another reason to avoid interpolating strings in a format string is that the strings you interpolate may contain a percent sign itself. See what happens if you unguardedly write this:
String salesTax = "5%";
System.out.format("The sales tax is " + salesTax);
That's equivalent to
System.out.format("The sales tax is 5%");
Unfortunately, the percent sign is treated as a format directive, and the format statement throws an exception. Correct is either:
System.out.format("The sales tax is 5%%");
or
String salesTax = "5%";
System.out.format("The sales tax is %s", salesTax);
But now I should ask why you did not take homeName and homeLocation from Team. Certainly they are more relevant to Team than to each other. In fact, you should look up the Formattable interface, and with proper coding you can write:
System.out.format("%s%, homeTeam);
Try this:
public class A {
public static void main(String[] args) {
System.out.println(String.format("%.2f", 12.34123123));
}
}