How to use the \n in java properly - java

Whenever I compile and run my code, the output becomes a big mess and I would like if someone could show me how to make my output look good.
import java.util.*;
public class JavaApplication3 {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int NumPerHamper;
int NumHampersMade;
int NumItemsLeftOver;
int NumAvalable;
double ValuePerHamper;
double ItemCost;
double ValueAllotedHamper;
double ValueItemsLeftOver;
String name="";
Date TheDate = new Date();
System.out.println("Enter the number of avaliable mac and cheese");
NumAvalable = sc.nextInt();
System.out.println("Enter the number of items per hamper");
NumPerHamper = sc.nextInt();
System.out.println("Price Of Item");
ItemCost = sc.nextDouble();
NumHampersMade = NumAvalable / NumPerHamper;
NumItemsLeftOver = NumAvalable % NumPerHamper;
ValuePerHamper = NumPerHamper * ItemCost;
ValueAllotedHamper = ValuePerHamper * NumHampersMade;
ValueItemsLeftOver = NumItemsLeftOver * ItemCost;
System.out.printf("\n");
System.out.printf(TheDate + "\n");
System.out.printf("Amount of Hampers Made: ", NumHampersMade,"\n");
System.out.printf("The Items Left Over is: ", NumItemsLeftOver,"\n");
System.out.printf("Each Value Of the Hampers are: $%.2f.", ValuePerHamper,"\n");
System.out.printf("The Price Of All The Hampers Is: $%.2f.", ValueAllotedHamper,"\n");
System.out.printf("The Value Of Mac And Cheese Is: $%.2f.", ValueItemsLeftOver,"\n");
}
}

This isn't right:
System.out.printf("Each Value Of the Hampers are: $%.2f.", ValuePerHamper,"\n");
The first argument (the format string) is the string you actually print, after replacing "format specifiers", or placeholders. Format specifiers in that string, such as %.2f, get substituted with the other arguments. So the second argument, ValuePerHamper, is used for the first specifier, %.2f; and the third argument, \n, is used for the second specifier---um, except that there aren't any other specifiers, so it doesn't get used at all.
You want to put \n in the format string:
System.out.printf("Each Value Of the Hampers are: $%.2f.\n", ValuePerHamper);
(printf also allows you to use %n instead of \n, which is more portable since it will also work on Windows systems where going to a new line needs \r\n instead of \n.)

You could use %n or \n. Either of these should be in the first parameter in the printf() method like this.
System.out.printf("Each Value Of the Hampers are: $%.2f. %n", ValuePerHamper);
System.out.printf("The Price Of All The Hampers Is: $%.2f.%n", ValueAllotedHamper);
System.out.printf("The Value Of Mac And Cheese Is: $%.2f.%n", ValueItemsLeftOver);
And you are missing %d for the first 2 lines to display the values.
System.out.printf("Amount of Hampers Made: %d %n", NumHampersMade);
System.out.printf("The Items Left Over is: %d %n", NumItemsLeftOver);

Related

How can I change the decimal to a colon?

Without changing the code, how would I be able to change the output from being 13.00 to 13:00? Is it possible to do so in the printf string?
System.out.print("Please enter the current hour on the clock(no minutes): ");
double time = sc.nextDouble();
System.out.print("Please enter the duration in hours: ");
int duration = sc.nextInt();
double newTime = (time+duration)-24;
System.out.println();
System.out.printf("If it is %.2f, in %d hours, it will be %.2f.\n",time,duration,newTime);
I would recommend replacing the "." to ":" as a stand-alone line. I don't see why you'd want to do that within the printf. Nonetheless, here is an example of how you could do it
System.out.printf("If it is %s.\n", String.valueOf(time).replace(".",":"));
Essentially converting the double to a string, then replacing the character.
Also, remember to change the %s tag.

Can I force the console to keep both price and tiprate on the same line?

import java.util.Scanner;
public class Tipping {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Please enter initial price followed by tip percentage: ");
double Price = s.nextDouble(); double TipRate = s.nextDouble();
double TipAmount;
TipAmount = (Price*TipRate)/100;
System.out.println("Tip amount: " + TipAmount);
System.out.print("Total price: " + (TipAmount + Price) +".");
}}
I always get the price on the first line and the tiprate on the other.
Judging by your wording, you don't like that when input is handled via the Scanner, pressing Enter on the first double value (The Price) it advances to the next line and waits for the second double value (The TipRate). First of all, the character "Enter" is essentially the system dependent new-line character, so the Scanner immediately splits the input when the enter key is pressed. Specifically, the Scanner uses the Character.isWhiteSpace(char ch); function to evaluate where to split the tokens.
It all depends on how you want your input handled. Sadly, without importing a Curses-esque library and using a custom command prompt, the "\n" character cannot be reversed. What you can do is write your input and separate it by a space, for example writing "23.4 12.3" will write the input in the same line and correctly break the line into the 2 tokens you want.
If it is purely for aesthetic reasons you could catch the token as a String, evaluate if the "\n" character exists within and ask the user to re-input the variables in a single line or, if the "\n" character doesn't exist, split the String on the " " character and then use the Double.valueOf(String str); function.
Beware not to use the (Scanner in).setDelimiter(String str) since that will avoid breaking the tokens on the "\n" character (If the str String is for example " ") and will only freeze your program until the user splits 2 inputs with the space character and then throw an InputMismatchException because 12.3\n12.3 32.3 would be "valid" input but the token "12.3\n12.3" can't be evaluated to a single Double variable.
Sure, avoid calling:
System.out.println()
As the name (somehow) indicates, that prints a whole "line"; ending with a line break.
So, either call System.out.print() multiple times; or better practice: call System.out.println() once, but give all the strings you wanted to be printed to that call.
And as I just saw your comment: you are calling println() - in the line before you call print()!
Given your comment: you have to understand how that scanner works. The scanner reads strings; and by default, line by line.
In other words: when you use nextDouble() then the scanner assumes that you will enter a string that represents a number - but that your input is "terminated" by the user pressing ENTER. In other words; those line breaks are inevitable!
So, simply deal with them like:
System.out.print("Please enter initial price: ");
double Price = s.nextDouble();
System.out.print("Please enter tip percentage: ");
double TipRate = s.nextDouble();
double TipAmount = (Price*TipRate)/100;
System.out.println("Tip amount: " + TipAmount + " results in Total price: " + (TipAmount + Price) +".");
Long story short: when using the console in/out like this; you can't prevent certain line breaks. Simply accept that, and don't get to much into perfectionism.
Use instead of System.out.println (which stands for print line) with System.out.print. The System.out.println will print an line break after the given string on the output stream.
You could also combine the print's with a single print line.
For example you could use this:
System.out.println(String.format("Tip amount: %f Total Price: %f", TipAmount, (TipAmount + Price)));
Update
Simple solution for the scanner problem would be to input the numbers in one line separated with a whitespace.

User input for file reader

Not sure if the title will make much sense but I'm currently quite confused and not sure how to work around my problem.
I'm trying to request from the user, a destination, a max time period (in the format HH:MM) and a maximum number of changes, which so far I have done. It should then calculate each journey’s total mins along with number of changes and then compare both with the user’s criteria, I recently edited my program to use case statements.
It does link to a .txt file that has the following data in it:
York
1
60
60
Alnwick
0
130
Alnwick
2
30
20
20
So my program asks for a destination, either York or Alnwick and a number of changes, maximum time, and so on but I can't figure out how to make it work with the chosen destination, current code to follow:
import java.io.FileReader;
import java.util.Scanner;
public class InputOutput {
public static void main(String[] args) throws Exception {
// these will never change (be re-assigned)
final Scanner console = new Scanner(System.in);
final Scanner INPUT = new Scanner(new FileReader("C:\\Users\\Luke\\workspace\\Coursework\\input.txt"));
System.out.print("-- MENU -- \n");
System.out.print("1: Blahblahblah \n");
System.out.print("2: Blahblahblah \n");
System.out.print("Q: Blahblahblah \n");
System.out.print("Pick an option: ");
int option = console.nextInt();
switch(option) {
case 1 :
while(INPUT.hasNextLine()) {
System.out.println(INPUT.nextLine());
}
break;
case 2 :
System.out.print("Specify desired location: ");
String destination = console.next();
System.out.print("Specify Max Time (HH:MM): ");
String choice = console.next();
// save the index of the colon
int colon = choice.indexOf(':');
// strip the hours preceding the colon then convert to int
int givenHours = Integer.parseInt(choice.substring(0, colon));
// strip the mins following the colon then convert to int
int givenMins = Integer.parseInt(choice.substring(colon + 1, choice.length()));
// calculate the time's total mins
int maxMins = (givenHours * 60) + givenMins;
System.out.print("Specify maximum changes: ");
int maxChange = console.nextInt();
// gui spacing
System.out.println();
int mins = INPUT.nextInt();
int change = INPUT.nextInt();
if ((mins > maxMins) || (change > maxChange)) {
System.out.format("Time: %02d:%02d, Changes: %d = Unsuitable \n", (mins / 60), (mins % 60), change);
}
else {
System.out.format("Time: %02d:%02d, Changes: %d = Suitable \n", (mins / 60), (mins % 60), change);
}
//Do stuff
break;
case 3 :
default :
//Default case, reprint menu?
}
}
}
Have edited it to reduce the size of the question for StackOverflow but if more code is needed please let me know - any further help would be greatly appreciated!
You should really learn how the Scanner works:
int Scanner.nextInt() Returns the next int value that occurred in the next line.
String Scanner.next() Returns the next piece of String separated by the default delimiter which is space " ". (You could use a different Delimiter with Scanner.useDelimiter(String)). In default case this returns the next single Word.
String Scanner.nextLine() Returns the next full line separated with the "\n" Character.
So if you want to get a destination that has two words for Example "New York" and you fetch it with Scanner.next() like you do. Then you take the time the same way. You will get destination="New" and choice = "York" which is not parsable for : and will crash.
The other problem you have is that a Scanner works from start to end. So if you choose option 1 and print all the output from your input file you will reach the end and hasNextLine() == false. Means you cannot get any INPUT.nextInt() after that point. But you try when chosing option 2 after that.
Your prorgamm should start by reading in your input file into a data structure that stores all the informations for you. And get them from there in further process.
What is crashing in your code for now is that you start reading your text file with INPUT.nextInt() but the first line of your text file is York which has no Int value in it. You could repair that by adding:
[...]
System.out.println();
INPUT.nextLine(); // skips the first line which is York
int mins = INPUT.nextInt();
int change = INPUT.nextInt();
[...]

The method println(double) in the type PrintStream is not applicable for the arguments (String, double)

Here is the code:
import java.util.Scanner;
public class MoviePrices {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
double adult = 10.50;
double child = 7.50;
System.out.println("How many adult tickets?");
int fnum = user.nextInt();
double aprice = fnum * adult;
System.out.println("The cost of your movie tickets before is ", aprice);
}
}
I am very new to coding and this is a project of mine for school. I am trying to print the variable aprice within that string but I am getting the error in the heading.
Instead of this:
System.out.println("The cost of your movie tickets before is ", aprice);
Do this:
System.out.println("The cost of your movie tickets before is " + aprice);
This is called "concatenation". Read this Java trail for more info.
Edit: You could also use formatting via PrintStream.printf. For example:
double aprice = 4.0 / 3.0;
System.out.printf("The cost of your movie tickets before is %f\n", aprice);
Prints:
The cost of your movie tickets before is 1.333333
You could even do something like this:
double aprice = 4.0 / 3.0;
System.out.printf("The cost of your movie tickets before is $%.2f\n", aprice);
This will print:
The cost of your movie tickets before is $1.33
The %.2f can be read as "format (the %) as a number (the f) with 2 decimal places (the .2)." The $ in front of the % is just for show, btw, it's not part of the format string other than saying "put a $ here". You can find the formatting specs in the Formatter javadocs.
you are looking for
System.out.println("The cost of your movie tickets before is " + aprice);
+ concatenates Strings. , separates method parameters.
Try this one
System.out.println("The cost of your movie tickets before is " + aprice);
And you can also do that:
System.out.printf("The cost of your movie tickets before is %f\n", aprice);
This will help:
System.out.println("The cost of your movie tickets before is " + aprice);
The reason is that if you put in a coma, you are sending two different parameters. If you use the line above, you add the double onto your string, and then it sends the parameters as a String rather than a String and a double.
It occurs when you use , instead of + i.e:
use this one:
System.out.println ("x value" +x);
instead of
System.out.println ("x value", +x);
I don't know if you have found the answer yet, but I understood that you should write like this:
System.out.println(MessageFormat.format("My name is = {0}, My FirstLetter Name is {1}, Myage is = {2}",Myname,myfirstl,d));

double + double = String?

I have a problem the output is supposed to be double but instead it is string
I am trying to add two double values but it is giving it as a string. I am using eclipse. Currently the program is compiling and running. If anyone have a moment I would appreciate it.Cheers guys. Here is the source code.
import java.util.Scanner;
public class FutureInvestment
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter investment amount: ");
double investmentAmount = input.nextDouble();
System.out.println("Enter monthly interest rate: ");
double monthlyInterestRate = input.nextDouble();
System.out.println("Enter number of years: ");
int numberOfYears = input.nextInt();
double futureInterestValue = investmentAmount * ( Math.pow((1 + monthlyInterestRate), numberOfYears * 12));
System.out.println("Accumulated value is: " + futureInterestValue + investmentAmount);
}
}
You need to format your output. You can use DecimalFormat or you can try the String#format function:
System.out.println(
String.format("Accumulated value is: %.2f",
futureInterestValue + investmentAmount));
So you can get the 2 decimal output. Plus, I recommend to create a variable with your result, so you can turn your code into
double accumulatedValue = futureInterestValue + investmentAmount;
System.out.println(
String.format("Accumulated value is: %.2f", accumulatedValue);
Since you're doing it in a println, it's doing string concatenation. If you want to add the double's together, you need to group them using ().
Try
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
double accumulatedValue = futureInterestValue + investmentAmount;
System.out.println("Accumulated value is: " + accumulatedValue);
Try this.
You were getting String as result of concatenation, since anything concatenated to a string is converted to string. Therefore, you need to complete the value beforehand as I shown above, or you need parentheses.
I think change it to this would work:
double futureInterestValue = investmentAmount * ( Math.pow((1 + monthlyInterestRate / 100), numberOfYears * 12));
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
you are missing some brackets, so your statement gets executed from left to right, thus appending the double to the string. You would need something like:
System.out.println("Accumulated value is: " + (futureInterestValue +
investmentAmount));
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
After the first +, Java has concatenated the first string with the first double, resulting in a string. Then it does another concatenation with the second double. You need to calculate the result first before making a string out of it.
When two operators could be evaluated within a line of code, they do so with a fixed precedence. While this example has been explained by many, you might want to review all of the precedence rules.
You can try:
System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));
or add a variable like double accumulatedValue=futureInterestValue + investmentAmount;
and then System.out.println("Accumulated value is: " + accumulatedValue);
The problem is your number is getting way too large, and Java switches over to scientific notation when printing the value.
If your monthly interest rate is entered as 4.25 (meaning 4.25%), you have to convert that to the correct decimal representation of 0.0425 before using it in your calculations - you have to divide it by 100. If you don't, the interest rate used will be much larger than you intended; in this case 425%.
In other words, change
double monthlyInterestRate = input.nextDouble();
to
double monthlyInterestRate = input.nextDouble()/100;

Categories

Resources