Java - Format number to print decimal portion only **without decimal** - java

This question was asked before (Formatting Decimal Number) without an answer as to how one can do such WITHOUT showing the decimal. I have been searching hours for an answer to no avail. Thanks in advance!
Example:
System.out.println("It would take " + oneMileMins + " minutes and " + oneMileDfSecs.format(oneMileSecs) + " seconds for the person to run one mile.");
Which outputs:
It would take x minutes and .yy seconds for the person to run one mile.
I would like the .yy to just be yy

Just change your output to oneMileDfSecs.format(oneMileSecs).replace(".", "")
EDIT: Rodney said that "He did not ask for the proper equation he only asked how to remove the decimal.", so I strike out the following , to respect him.
ADDITIONAL NOTE:
just like #Alan said , oneMileSecs should be equal to (int)((oneMile % 1)*60), in this case, the way you get rid of the decimal sign is little bit different :
1). If you declare :
double oneMileSecs = (int)((oneMile % 1)*60)
then change your output to :
String.valueOf(oneMileSecs).substring(0,String.valueOf(oneMileSecs).indexOf("."))
2). If you declare :
int oneMileSecs = (int)((oneMile % 1)*60)
then just output oneMileSecs directly as it's an int, it won't produce decimal sign

Not sure this is the answer you're looking for, as it doesn't answer the question in the title (Fev's answer does that), but I think this should give a correct result for the specific example:
private static void calcOneMile(double mph)
{
double oneMile = 60 / mph;
int oneMileMins = (int)oneMile;
double oneMileFraction = oneMile % 1;
int oneMileSecs = (int)(oneMileFraction * 60);
System.out.println("It would take " + oneMileMins + " minutes and " + oneMileSecs + " seconds for the person to run one mile.");
}
Or simplified to:
private static void calcOneMile(double mph)
{
int secondsToRunMile = (int)(1.0 / (mph / 3600));
System.out.println("It would take " + (secondsToRunMile / 60) + " minutes and " + (secondsToRunMile % 60) + " seconds for the person to run one mile.");
}

Related

I'm getting a code error in a weird place, and when I try and fix it, I get lots of errors. How can I fix it? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I'm writing a program called SalesTax.java. The program will create an output that tells the sales tax on a $50 purchase, when the sales tax changes depending on the day in the month of January. I like to save my program and run it often, so I can see that I got that section right. When I run the stuff I have done, I get a super weird error and I have no idea what I'm doing wrong.
I've tried to create the syntax the compile message error told me, where I get more errors: SalesTax.java:6: error: variable N is already defined in method main(String[]) and
SalesTax.java:6: error: lambda expression not expected here.
public class SalesTax {
public static void main(String[] args) {
int N = 1;
int Item = 50;
int st = N;
System.out.println("On January " + (N)", The Sales Tax will be " + (st / 100) * Item);
}
}
I expect the output to be: On January 1, The Sales Tax will be 50.5. However, instead I'm getting this:
SalesTax.java:6: error: cannot find symbol
System.out.println("On January " + (N)", The Sales Tax will be " + (st / 100) * Item);
^
symbol: class N
location: class SalesTax
1 error
Any ideas on how to fix it?
You need a + after (N) to concatenate it with the next string:
System.out.println("On January " + (N) + ", The Sales Tax will be " + (st / 100) * Item);
You forgot a plus after (N). Try:
System.out.println("On January " + N + ", The Sales Tax will be " + (st / 100) * Item);
also note that in java, 1 / 100 (st is 1, so, that's what (st / 100) ends up being) is straight up 0, and not 0.01; integer math just rounds. If you want floating point stuff, you need double and not int. So, try: double st = N; instead.

How do you print variables? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
So I am working with this code but the end result should look something like this.
EX.
People: 4
Pizza: 1
Cost: $14.95
My code looks like this -
import java.util.*;
public class Pizza {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int people = keyboard.nextInt();
int pizza = people * 2 / 12 + 1;
double cost = pizza * 14.95;
System.out.println("People: " + people + "Pizzas: " + pizza + "Cost: $" + cost + );
}
}
The int people = keyboard.nextInt(); line allows me to input a integer value of people and the program then will take people * 2 and then divide by 12 (for the number of slices in a pizza) and + 1 to give me the pizzas I need. The cost will then be the pizza number * 14.95. I want the amount of people, pizzas, and cost to be displayed in the System.out.println method on the bottom. I do not know what I did wrong? Shouldn't + people + display the people in that line? Same with + pizza + and + cost + ?
The + operator joins strings (and other variables converted to strings). Just like in maths, you write it between two elements, so the final + was superfluous (and erroneous).
System.out.println("People: " + people + " Pizzas: " + pizza + " Cost: $" + cost);
When learning Java, you might want to use an IDE, which would point out this mistake for you, or just read the errors the compiler gives you.
You shouldn't have that last + at the end of your print statement, since there's nothing after it. When it's removed your code seems to run fine, albeit with a slight whitespace issue which you can fix by adding spaces to the print statement.
12
People: 12Pizzas: 3Cost: $44.849999999999994
System.out.println("People: " + people + "Pizzas: " + pizza + "Cost: $" + cost + );
You have put extra + at the end. Remove that.
String concatenation like str1 + str2 is OK, but pay attention to correctly print double value: you need only two fractional digits:
try (Scanner keyboard = new Scanner(System.in)) {
int people = keyboard.nextInt();
int pizza = people * 2 / 12 + 1;
double cost = pizza * 14.95;
System.out.printf(Locale.US, "People: %d, Pizzas: %d, Cost: $%.2f\n", people, pizza, cost);
}
Output:
10
People: 10, Pizzas: 2, Cost: $29.90

Can't remember how to do this for some reason

This one should be fairly simple I think, I just can't remember how, when using get methods of an object, how to pull the highest double out of the pack and put it in the println.
So far I just get every object to print with its percentages. But for the life of me I just can't remember and I know I've done this before.
public void displayBookWithBiggestPercentageMarkup(){
Collection<Book> books = getCollectionOfItems();
Iterator<Book> it = books.iterator();
while(it.hasNext()){
Book b = it.next();
double percent = b.getSuggestedRetailPriceDollars() / b.getManufacturingPriceDollars() * 100.0;
System.out.println("Highest markup is " + percent + " " + b.getTitle() + " " + b.getAuthor().getName().getLastName());
}
}
I'm pretty sure I need another local variable but I can't seem to do anything but make it equal the other percent. I have removed the other variable for now as I try to think about it.
I won't go into a lot of detail because it's homework (well done for being up-front about that, by the way) but here's the key idea: keep track of the largest percentage you've seen so far as your loop runs. That's what you want in your other variable.
Good job posting what you've tried so far. You were on the right track. As you loop through your books, keep a variables continuously updated with the highest percent seen so far and another variable for the associated book. Output the variable at the end outside the loop after iteration is done. Also, don't forget to check the edge case of an empty list of books! Something like this should do the trick:
public void displayBookWithBiggestPercentageMarkup(){
Collection<Book> books = getCollectionOfItems();
if (books.size() == 0) {
return;
}
Iterator<Book> it = books.iterator();
double highestPercent = 0;
Book highestPercentBook = null;
while(it.hasNext()){
Book b = it.next();
double percent = b.getSuggestedRetailPriceDollars() / b.getManufacturingPriceDollars() * 100.0;
if (percent > highestPercent) {
highestPercent = percent;
highestPercentBook = b;
}
}
System.out.println("Highest markup is " + highestPercent
+ " " + highestPercentBook.getTitle()
+ " " + highestPercentBook.getAuthor().getName().getLastName());
}

Unexpected outcome with System.out.println

I'm in the process of making a program using input from a text file, it only has 2 lines of text in it which is
120 (this is the time)
2 (this is changes)
My code is meant to read the user's input which converts hours to minutes, and then asks for a number of changes. If the hours entered are 02:00 which is 120 minutes and the changes entered are 2 or less then it will come back saying 'acceptable', and if not it will read 'unacceptable' however I am having a bit of trouble formulating this. If anybody could provide assistance I would appreciate it greatly!
Code to follow:
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class InputOutput {
public static void main(String[] args) throws IOException{
final Scanner S = new Scanner(System.in);
final Scanner inFile = new Scanner(new FileReader("task.txt"));
// open file and associate objects
int IOminutes = Integer.parseInt(inFile.next());
int changes = Integer.parseInt(inFile.next());
// close the input file
inFile.close();
System.out.print("Specify Time (HH:MM): ");
String givenTime = S.next();
System.out.print("Specify Changes: ");
String givenChanges = S.next();
// save the index of the colon
int colon = givenTime.indexOf(':');
// strip the hours preceding the colon then convert to int
int givenHours = Integer.parseInt(givenTime.substring(0, colon));
// strip the mins following the colon then convert to int
int givenMins = Integer.parseInt(givenTime.substring(colon + 1, givenTime.length()));
// calculate the time's total mins
int mins = (givenHours * 60) + givenMins;
// using given time
System.out.println(givenTime + " = " + mins + " minutes");
if (!givenTime.equals(IOminutes) && changes >= 3) {
System.out.println("Time: " + givenTime + ", Changes: " + givenChanges + " = unacceptable!");
} else if (givenTime.equals(IOminutes) && changes <= 2) {
System.out.println("Time: " + givenTime + ", Changes: " + givenChanges + " = acceptable!");
}
S.close();
}
}
Your inputs (file-based and user-based) look reasonable.
By the time you reach your if-elseif logic on line 40, you have the following values (all values based on the problem description in the question):
loaded from "task.txt"...
IOminutes: 120
changes: 2
user input:
givenTime="02:00"
givenChanges=2
givenHours=2
givenMins=0
mins=2*60+0 = 120
Your conversion from strings to integers looks like no problem.
Your desired outcome of "acceptable" / "unacceptable" is hard for me to understand; not what it is doing, but Why it is doing that.
I'm having trouble understanding why you have two "changes".
This would make more sense to me if you just had:
task.txt: IOminutes=120, changes=2
given: time="hh:mm"
Now compute difference (in minutes) between task.txt's IOminutes and user's given time. Let's call that difference givendiff. Then you have something like:
if givendiff > changes then unacceptable.
Examples (user input values more or less made up):
task.txt: IOminutes=120, changes=2
test 1: given time="02:00" (computed givendiff=0, so acceptable)
test 2: given time="01:50" (computed givendiff=-10, so unacceptable)
test 3: given time="02:05" (computed givendiff=5, so unacceptable)
test 3: given time="02:02" (computed givendiff=2, so acceptable)
test 3: given time="01:58" (computed givendiff=-2, so acceptable)
I would encourage you to review the original requirements and verify whether your user is supposed to be give you an extra "changes" in addition to task.txt's changes. Or if you're supposed to compute a the difference between task.txt's IOminutes and the user-entered value, and complain if that difference exceeds task.txt's changes value.
I would go further but this seems like a homework or code-challenge problem; if so, hopefully this is enough to help nudge your perspective to re-thing what "changes" means in the original requirements. Good luck.

What am I doing wrong here? if statements not adding up

total in this case is 500. Trying to make a calculator, but not everything's adding up. It seems to skip the multiplication and just display total*amount. Is there something I'm doing wrong? EDIT: Discount: in the example, .92. I get 455000 if amount is 1000.
if (wShipping==true){
if (GroundShipping.isSelected()){
if (amount<=99) {
shipping=1.05;
output.setText(output.getText() + amount + "\t" + total*1.05*amount*discount + "\n");
}
else{
output.setText(output.getText() + amount + "\t" + total*amount*discount + "\n");
}
}
if (AirShipping.isSelected()){
shipping=1.1;
output.setText(output.getText() + amount + "\t" + total*amount*1.1*discount + "\n");
}
if (FedexShipping.isSelected()){
shipping=1.25;
output.setText(output.getText() + amount + "\t" + (total*amount*discount)*(1.25) + "\n");
}
}
You should consider the following things--
1) Why is the variable shipping needed if you are directly using the value in the set statement
2) Use else if statement since all the options are exclusive
3) You might want to check the initial values for variables and the formula for calculating the price. Taking the initial values as given, the lowest possible price is-
Price = 1000*500*0.92 = 460000 (total x amount x discount)
Hence there must be something amiss with your initial values
Maybe, just maybe is the first rule of currency calculations:
why not use double or float to represent currency

Categories