So in the following set of code I don't understand why "%.1f" will not round y to 1 decimal, I get the following when running the program:
123 F = Exception in thread "main"
java.util.IllegalFormatConversionException: f != java.lang.String
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4045)
at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2761)
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2708)
at java.util.Formatter.format(Formatter.java:2488)
at java.io.PrintStream.format(PrintStream.java:970)
at java.io.PrintStream.printf(PrintStream.java:871)
at Check03A.main(Check03A.java:17)
I also tried Math.round(y * 10) / 10 but it gives me for example 29.0 instead of 28.9
import java.util.*;
import java.io.*;
import java.lang.*;
import type.lib.*;
public class Check03A
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
PrintStream print = new PrintStream(System.out);
print.println("Enter the temperature in Fahrenheit");
int x = scan.nextInt();
int y = 5 * (x - 32) / 9;
print.printf(x + " F = " + "%.1f", y + " C");
}
}
The problem is here:
print.printf(x + " F = " + "%.1f", y + " C");
There are two arguments to this method:
x + " F = " + "%.1f" (the format string),
y + "C" (the argument)
Condensing the first argument, the statement becomes:
print.printf(x + "F = %.1f", y + "C");
The problem: y + "C". Why? Well, one argument of the + operator is a String; therefore, this + becomes a string concatenation operator and what the argument will ultimately be is String.valueOf(y) + "C".
But the format specification in the format string is%.1f, which expects a float or double, or their boxed equivalents. It does not know how to handle a String argument.
Hence the error.
There is also the problem that you are doing an integer division, but this is not the topic of this question. Provided that all numeric problems are solved, your printing statement will ultimately be:
print.printf("%.1f F = %.1f C", x, y);
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
PrintStream print = new PrintStream(System.out);
print.println("Enter the temperature in Fahrenheit");
int x = scan.nextInt();
//change it
float y = 5 * (x - 32) / 9;
print.printf(x + " F = " + "%.1f", y).print(" C");
}
Make y as float if you want to use %f
float y = 5 * (x - 32) / 9;
print.printf(x + " F = " + "%.1f", y ).print("C");
Related
I'm getting a weird output from running this simple java program.
The output is: 0 4 2 -6
Why does the x++ print 0, it should be printing 4.
import java.util.*;
import java.io.*;
public class Java1 {
public static void main(String[] args) throws IOException {
int x = 4;
int y = -5;
System.out.println(x++ + " " + func(x++, y) + " " + --y);
}
public static int func(int work, int y) {
int z = work + y;
work++;
y++;
System.out.print(z + " ");
return z + work + y;
}
}
Okay, here is what's going on: First x++ is evaluated, returning 4 (which is later printed) and leaving x at 5. Then x++ is evaluated again, passing 5 to func. Then func is evaluated with 5 and -5 parameters. In here z is 0 (5 + (-5) = 0) which is then printed (BEFORE the println in the main method. func then returns 2 (0 + 6 + (-4)) which is also added to the string. Finally --y results in -6. Now the println in the main method prints its string (4 2 -6).
func(x++, y) is executed first, so 0 comes from System.out.print(z + " "); in func.
System.out.print(z + " ");
is executed before
System.out.println(x++ + " " + func(x++, y) + " " + --y);
So the 0 comes from z, not x.
I have mentioned the flow of points from 0 to 7 in the comments
public static void main(String[] args) throws IOException {
int x = 4;
int y = -5;
System.out.println(x++ + " " + func(x++, y) + " " + --y);
// thus 0]4 6]2 (value returned as z) 7] localvalue of --y as -6
}
//1] x++ makes x as 5 when it is passed to func()
public static int func(int work, int y) {
int z = work + y;
//2] z = 5 + -5 = 0
work++;
//3] work which was x as 5 is now 6
y++;
//4] y will be -4 now
System.out.print(z + " ");
return z + work + y;
//5] z = 0 + 6 + -4 = 2 and is returned to func() caller
}
import java.util.*;
import java.io.IOException;
public class Java1
{
public static void main(String args[])
{
int x = 4;
int y = -5;
System.out.println("x = "+ (x++ ) +" func = "+ (func(x++, y) ) + " y = "+ --y);
}
public static int func(int work, int y)
{
int z = work + y;// 5+-5 = 0
work++; //6
y++; //-4
System.out.print("Z = " + z + " ");//0
return z + work + y; //0 + 6+-4 = 2
}
}
OUTPUT :
Z = 0 x = 4 func = 2 y = -6
Here the func() is executed first and hence the value of variable z is printed as 0 and then the x++ value is printed as 4.
My task is to write a program that displays a table of 20 temperature conversions from Fahrenheit to Celcius and to increment he value in 3 degrees.
This is what I made
public class FahrenheitToCelsius {
public static void main(String[] args) {
for(int f = 20; f < 78; f = f+3) {
System.out.println(f + " degrees Fahrenheit is " + (5/9) * (f-32) + " degrees celsius ");
}
}
}
Yet when I print it is keeps saying the degrees is 0 for all of them, do I have my order of operations wrong or something?
You are working with int so (5/9) * (f-32) evaluates to 0 * (f-32) because integer maths stays integer and 5/9 as an integer is zero. 5.0/9.0 = 0.55555555 which, when converted to an int becomes 0.
Switch to using float.
for (float f = 20; f < 78; f = f + 3) {
System.out.println(f + " degrees Fahrenheit is " + (5.0 / 9.0) * (f - 32) + " degrees celsius ");
}
This question already has an answer here:
Java Division error
(1 answer)
Closed 7 years ago.
I was trying to create a probability calculator for fun, but for some reason, java gets the incorrect answer when I divide two numbers. Here is my code....
import javax.swing.JOptionPane;
public class ProbabilityCalculator {
public static void main(String args[]) {
String a = JOptionPane.showInputDialog("One out of.....");
int x = Integer.parseInt(a);
int numLoops = 1000;
int y = 0;
int n = 0;
for (int i = 0; i < numLoops; i++) {
int result = (int) (Math.random() * x + 1);
int result2 = (int) (Math.random() * x + 1);
if (result == result2)
y++;
else
n++;
}
System.out.println(y);
System.out.println(numLoops);
System.out.println(y/numLoops);
double d = (y/numLoops) * 100; //get it? double d??
JOptionPane.showMessageDialog(null, "Out of " + numLoops + " trials, "
+ y + " times it worked, while " + n + " times it didn't.");
JOptionPane.showMessageDialog(null, "Your percentage was " + d
+ "%.");
System.exit(0);
}
}
When I ran this code one time, y was 514, numLoops was 1000, but d would be 0, when d is supposed to be 51.4 (514 / 1000 * 100). Why is this happening?
y/numLoops will be an integer since both arguments are ints. Try (double)y/numLoops or y/(double)numLoops instead.
If you decompose double d = (y/numLoops) * 100; you'll get something similar to those steps:
int r = y/numLoops; - according to the spec an operation having two integer operands will have an int result.
double d = r * 100 here r will be 0 due to being int.
This question already has answers here:
Division of integers in Java [duplicate]
(7 answers)
Closed 8 years ago.
I am new to Java and am trying to make a program run to solve and display
the output of the equations. I have tried changing the places of the
parenthesis, and putting equations in other parts of the code but I either get 0
as the output or wrong answers. Any words of wisdom would be greatly
appreciated.
import java.util.*;
import static java.lang.Math.*;
public class JFirstTest
{
public static void main(String[] args)
{
// Declare variables and equations
int W, X, Y, Z;
W = 10;
X = 20;
Y = 30;
Z = 40;
int FormulaOne = (W + X) / (Y + Z);
int FormulaTwo = (X + ( Y / W)) / Z;
int FormulaThree = X * (W - Y)/ (X * Y - Z);
// System.out.println formulas
System.out.println("\n\tWhen W=" + W + " X=" + X + " Y=" + Y + " Z=" + Z + " then FormulaOne = " + FormulaOne);
System.out.println("\n\tWhen W=" + W + " X=" + X + " Y=" + Y + " Z=" + Z + " then FormulaTwo = " + FormulaTwo);
System.out.println("\n\tWhen W=" + W + " X=" + X + " Y=" + Y + " Z=" + Z + " then FormulaThree = " + FormulaThree);
System.out.println("\n");
Update: This has been marked as Duplicate, however, I did searches before I
posted this question and the answers eluded me...Also changed int to double
and now it works fine.
Dividing integer by integer will result in integer, and round down (truncate). So, dividing smaller number by larger will result in zero, so you may want to consider changing type of variables to float / double.
Think of it this way... if an int (integer) is a whole number, then if you divide, for example, 10 by 20, then your program is just going to give you back 0 because 0.5 is not an integer (so it rounds down).
What primitive data type would you use to account for any decimals?
Answer: Double
I'm having trouble getting the number of digits to the left of the decimal place. I've got the digits to the right of the decimal point working and able to print out but not to the left. Can anyone help?
import java.lang.Math;
import java.util.Scanner;
import java.text.DecimalFormat;
public class FormulaCalculation
{
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
double x;
//Prompt user for value.
System.out.print("Enter a value for x: ");
x = userInput.nextDouble();
double result = (Math.sqrt(7 * Math.pow(x, 4) - 5 * Math.pow(x, 2) + Math.abs(98 * x)) + 13) * (3 * Math.pow(x, 5) + 4 * Math.pow(x, 3) + 1);
String resultString = Double.toString(result);
int integerPlaces = resultString.indexOf('.');
int digitsLeft = resultString.length();
int digitsRight = resultString.length() - integerPlaces - 1;
//Output
System.out.println("Result: " + result);
System.out.println("# digits to left of the decimal point: " + digitsLeft);
System.out.println("# digits to right of the decimal point: " + digitsRight);
System.out.println("Formatted Result: ");
}
}
Either print integerPlaces (which is the number you seek) or assign it to digitsLeft. Something like this,
int integerPlaces = resultString.indexOf('.');
int digitsLeft = integerPlaces; // <-- from 0 to the '.'
// resultString.length();
int digitsRight = resultString.length() - integerPlaces - 1;
or eliminate digitsLeft altogether,
System.out.println("# digits to left of the decimal point: " + integerPlaces);