This question already has answers here:
Random printing order for System.out & System.err calls [duplicate]
(3 answers)
System.out.println and System.err.println out of order
(7 answers)
Race between System.out and System.err in java [duplicate]
(3 answers)
Closed 4 years ago.
I added in the System.err.flush(); and System.out.flush(); however the problem still exists. It appears as if these printf statements are being output at a random unorthodox order.
When the (absoluteFinalGrade % 1) ranges from 0.45 to 0.49, I would like the output to be printed in red. This is because since I am given hundreds of lines of output, I would like the important ones to stand out. However, system.err.printf seems to be glitching my output in an unorthodox way. Is it possible to use a different method to make my text standout?
import java.util.Scanner;
public class FinalChemistryGradeCalculator {
public static void main (String [] args) {
Scanner input = new Scanner (System.in);
Scanner input2 = new Scanner (System.in);
double termGrade;
double examinationGrade;
double examinationMarkScore;
double examinationMarkTotal;
double lowestTestGrade;
double lowestTestMarkScore;
double lowestTestMarkTotal;
double initialFinalGrade;
double absoluteFinalGrade;
System.out.printf("Input the term grade.%n");
termGrade = input.nextDouble();
System.out.printf("%nThe term grade is %.2f.%n", termGrade);
System.out.printf("%nInput the lowest test mark score.");
lowestTestMarkScore = input.nextDouble();
System.out.printf("%nInput the lowest test mark total.");
lowestTestMarkTotal = input.nextDouble();
lowestTestGrade = (lowestTestMarkScore/lowestTestMarkTotal) * 100;
System.out.printf("%nThe lowest test grade is %.2f.%n", lowestTestGrade);
System.out.printf("%nInput the examination mark total.");
examinationMarkTotal = input.nextDouble();
for (examinationMarkScore = 0; examinationMarkScore <= examinationMarkTotal; examinationMarkScore += 0.5) {
examinationGrade = (examinationMarkScore/examinationMarkTotal) * 100;
initialFinalGrade = (termGrade * 0.7) + (examinationGrade * 0.3);
if (lowestTestGrade < examinationGrade) {
absoluteFinalGrade = initialFinalGrade - (lowestTestGrade * 0.05) + (examinationGrade * 0.05);
}
else {
absoluteFinalGrade = initialFinalGrade;
}
if (absoluteFinalGrade % 1 >= 0.45 && absoluteFinalGrade % 1 <= 0.49) {
System.err.printf("%n%n--------------------------------------------------------------------------------------------------------------");
System.err.printf("%nTerm Grade: %.2f ||||| Examination Grade: %.2f (%.1f/%.1f) ||||| Lowest Test Grade: %.2f (%.1f/%.1f)", termGrade, examinationGrade, examinationMarkScore, examinationMarkTotal, lowestTestGrade, lowestTestMarkScore, lowestTestMarkTotal);
System.err.printf("%nInitial Final Grade: %.2f ||||| Absolute Final Grade: %.2f", initialFinalGrade, absoluteFinalGrade);
System.err.printf("%n--------------------------------------------------------------------------------------------------------------");
System.err.flush();
}
else {
System.out.printf("%n%n--------------------------------------------------------------------------------------------------------------");
System.out.printf("%nTerm Grade: %.2f ||||| Examination Grade: %.2f (%.1f/%.1f) ||||| Lowest Test Grade: %.2f (%.1f/%.1f)", termGrade, examinationGrade, examinationMarkScore, examinationMarkTotal, lowestTestGrade, lowestTestMarkScore, lowestTestMarkTotal);
System.out.printf("%nInitial Final Grade: %.2f ||||| Absolute Final Grade: %.2f", initialFinalGrade, absoluteFinalGrade);
System.out.printf("%n--------------------------------------------------------------------------------------------------------------");
System.out.flush();
}
}
}
}
You can use jansi:
System.out.println( ansi().eraseScreen().render("#|red Hello|# #|green
World|#") );
This example is quoted from Jansi Github README.
Note that this won't probably work from Eclipse or any IDE wrapper.
Related
I'm doing a program on compound interest for a school assignment. I tried using System.out.format(); and used money.format to format the variables investment, interest, and investTotal. I don't know why but it keeps on throwing me an error for
"Invalid value type 'String' for format specifier '%.2f', parameter 2, 3, and 4" I've been trying to figure this out for quite a while now and I still can't seem to find why it is.
-- A
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// SPLASH
// CONSTANT
// OBJECT
Scanner input = new Scanner(System.in);
NumberFormat money = NumberFormat.getCurrencyInstance();
// VARIABLES
double investment;
double investTotal;
double rate;
double intrest;
int year;
// INPUT
do
{
System.out.print("Enter yearly investment (min $100.00 deposit): ");
investment = input.nextDouble();
}
while (investment < 100);
do
{
System.out.print("Enter intrest rate (%): ");
rate = input.nextDouble()/100;
}
while (rate <= 0);
do
{
System.out.print("Enter number of years: ");
year = input.nextInt();
}
while (year <= 0 || year > 15);
// PROCESSING
investTotal = investment;
for (int perYear = 1; perYear <= year; perYear++)
{
intrest = investTotal*rate;
investTotal = (investment+intrest);
System.out.format("%2s | %.2f | %.2f | %.2f\n", perYear, money.format(investment), money.format(intrest), money.format(investTotal));
investTotal = investTotal + investment;
}
// OUTPUT
}
}
getCurrencyInstance returns a String and therefor can't be formatted using %.2f.
You better look how NumberFormat works:
https://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html
As you can see, the result of the formatting is a String, when you are using String.format with %.2f you should enter a number e.g:
System.out.format("%2s | %.2f\n", 1.001, 1.005);
I'm not sure what are you trying to get using the NumberFormat, if you classify I will be able to help you further with this question.
This question already has answers here:
how to print a Double without commas
(10 answers)
Closed 7 years ago.
So my code is correctly outputting the compounded interest periodically, but it is putting my output with a comma. Ex: $1,000.00 I would like the answer to be: $1000.00.
Here is my code guys:
package certificatedeposit;
public class CertificateDeposit {
public static void main(String[] args) {
double PV = 1000.00;
System.out.printf("Enter annual rate: ");
java.util.Scanner in = new java.util.Scanner( System.in );
double rate = in.nextDouble( );
double rates = rate / 100 / 12;
System.out.printf("Enter CD term in months: ");
int months = in.nextInt( );
double product = ( 1 + rates);
double exp = Math.pow(product,months);
double fv = PV * exp;
System.out.printf("An initial investment of $1000.00 after "+months+" months at annual rate of %,.2f%% is $%,.2f \n", rate, fv);
}
}
I had changed the code for you but as #ajb said in comment, you are getting "," because you have used it while formatting string. For deep understanding read here
package certificatedeposit;
public class CertificateDeposit {
public static void main(String[] args) {
double PV = 1000.00;
System.out.printf("Enter annual rate: ");
java.util.Scanner in = new java.util.Scanner( System.in );
double rate = in.nextDouble( );
double rates = rate / 100 / 12;
System.out.printf("Enter CD term in months: ");
int months = in.nextInt( );
double product = ( 1 + rates);
double exp = Math.pow(product,months);
double fv = PV * exp;
System.out.printf("An initial investment of $1000.00 after "+months+" months at annual rate of %,.2f%% is $%.2f \n", rate, fv);
}
}
Remove the comma from the format string for variable fv:
System.out.printf("An initial investment of $1000.00 after "+months+" months at annual rate of %,.2f%% is $%.2f \n", rate, fv);
Also here is a discussion about using different (not only comma) symbols for grouping separator.
This question already has answers here:
Java: Literal percent sign in printf statement
(4 answers)
Closed 7 years ago.
How do I print a % sign in Java? I have tried "\%", which doesn't seem to work. Any ideas?
Bellow is the code corrected, as mentioned above you should use double % to escape %, i.e: %%
I have also added some new line characters to make the app look more neat.
import java.util.Scanner;
public class test
{
public static void main(String args[])
{
//A Simple Averaging Program
Scanner input = new Scanner(System.in);
//Declare variables:
double total = 0;
double counter = 0;
long mark;
double average;
int numOfPupils;
int totalMarks;
//Ask how many papers the teacher would like to average:
System.out.println("How many student's papers would you like to avarage?");
numOfPupils = input.nextInt();
//Ask how many marks were available to the student to earn:
System.out.println("How many marks were available to the student?");
totalMarks = input.nextInt();
//Repeat the amount of papers times:
while (counter < numOfPupils)
{
//Ask how many marks the student got:
System.out.printf("\nHow many marks did student number %s get? \nStudent %s scored: ", counter + 1, counter + 1);
mark = input.nextLong();
total += mark;
System.out.printf("Student %s scored: %s%%", counter + 1, ((100 / totalMarks) * mark));
counter++;
}
average = total / (counter);
System.out.printf("\nThe average was %s marks.", average);
input.close();
}
}
Off-topic but may need consideration, is that your code will fail in some cases, as you need to handle some invalid inputs.
I have the program working I just need help cutting off the extra numbers, Im not very skilled at using the printf statements when printing in Java. When I run it I get output like 1225.043 Here is what I have:
import java.util.Scanner;
public class Comparison {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
float amount;
double principal = 1000.00;
double rate;
System.out.println("Enter interest rate");
rate = keyboard.nextDouble();
System.out.println("Year" +" "+ "Amount on deposit");
for(int year = 1; year <= 10; ++year)
{
amount = (float) (principal * Math.pow(1.0 + rate, year));
System.out.println(year+ " "+ amount);
System.out.println();
}
}
}
Try
System.out.printf("%2d %.2f%n", year, amount);
Output:
Enter interest rate
0.1
Year Amount on deposit
1 1100.00
2 1210.00
3 1331.00
4 1464.10
5 1610.51
6 1771.56
7 1948.72
8 2143.59
9 2357.95
10 2593.74
I hope I'm posting in the right place.
I'm pretty new to Java (meaning this is only my third program besides 'hello world').
I have a tip calculator I'm working on for an assignment. I'm not getting an 'error' as such,
but the method for splitting the bill always seems to think each customer pays 'infinity'.
I have my program set up in two classes: tipCalc1 and tipCalc2 (no points for originality of course).
The program appears to run without issue besides the 'infinity' issue.
Here's what I have so far. Any assistance appreciated, thanks.
***TipCalc1 Class:***
import java.util.Scanner;
public class Tipcalc1
{
public static void main(String[] args)
{
System.out.println("Welcome to Tip Calculator! ");
TipCalc2 Calculator = new TipCalc2();
System.out.println("Please enter the bill amount: ");
TipCalc2.calBill();
System.out.println("What percentage would you like to tip?: ");
Calculator.percTip();
}
}
***And the tipCalc2 class which does the dirty work:***
import java.util.Scanner;
public class TipCalc2
{
static double bill;
double tip;
double total;
double split;
double splitPrompt;
double Y;
double N;
double billPerPerson;
static Scanner scan = new Scanner(System.in);
public static void calBill()
{
bill = scan.nextDouble();
}
public void percTip()
{
tip = scan.nextDouble();
if(tip<1)
{
total = bill * tip;
}
else total = bill * (tip/100);
System.out.println("Your total is: " + total);
Split();
}
public void Split()
{
System.out.println("Would you like to split the bill? ");
System.out.println("Enter 1 for YES or 0 for NO: ");
splitPrompt = scan.nextDouble();
if(splitPrompt == 0)
{
System.out.println("Your total is: " + total);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program");
}
if(splitPrompt == 1)
{
System.out.println("How many ways would you like to split the bill? ");
splitPrompt = scan.nextDouble();
billPerPerson = total / split;
System.out.println("Each person pays: " + billPerPerson);
System.out.println("Thankyou. Goodbye.");
System.out.println("End Program.");
}
else System.out.println("Invalid Entry");
}
}
The default value for split (because you have not initialized it with another value) is 0.0, therefore, when you do
billPerPerson = total / split;
you divide by 0.0, so you will get Infinity.
Notes:
Since your variable splitPrompt is double and computers doesn't store real values with a 100% accuracy, you shouldn't compare it with 0.0. Since this variable will store 0 or 1 for input, you can declare it as int, which will be accurate.
Try to follow Java naming conventions. Use mixedCase for methods/variables and use CamelCase for classes/interfaces.
In the method split(), you should use an if-else if-else structure:
if(splitPrompt == 0) {
...
}
else if(splitPrompt == 1) {
...
}
else {
...
}
Silly mistake.
Change
System.out.println("How many ways would you like to split the bill?
splitPrompt = scan.nextDouble();
to
System.out.println("How many ways would you like to split the bill?
split = scan.nextDouble();
since you never change split which, like all double variables, is initialized to 0.0.
Also, you should use ints where appropriate as not all of the numbers should be doubles. Or even better, use 'y' and 'n' chars.
Class TipCalc2
//Total = **bill** * (gets percentage in decimal 15 = 0.15) + **bill**
Line 18 needs to be:
total = bill * (tip / 100) + bill;
Line 36/37 needs to be:
split = splitPrompt = scan.nextInt();
billPerPerson = total / split;
//You're dividing billPerPerson = total by ZERO (split);
Line 36/37 original:
billPerPerson = total / split;