Rounding numbers with 2 decimals [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Please don't report this question as 'already posted or reported' which is NOT the case, it might/should be but it's NOT. This is a extremely strange performance of JAVA. I also wonder a bit if the one who was responsible for digit-handling is still working for JAVA, cause he/she made a Mess of it!! A jungle of codes and formatting.
Anyway here my ghostly problem. (it's a part of the code but only the relevant part)
As you can see all variables (a,b,c and d) are double. But it systematically results in Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.String
Whatever I changed, tried and look about on the internet it keeps on refusing to work. But down below, an example found on Internet does work. But it's exactly the same!! Both variables are declared as doubleand both converted via the same method!!
case 2:
Hypotheek hypspa = new HypSpaar(UitvoerHypotheek.hs,UitvoerHypotheek.lt,UitvoerHypotheek.perc);
double a = hypspa.aflossing();
double b = hypspa.aflossing();
double c = hypspa.rente();
double d = (1+((float)UitvoerHypotheek.perc/100));
System.out.println("jaar" + " inleg " + " gespaard " + " rente " );
for (int t=1; t<=UitvoerHypotheek.lt; t++)
{
System.out.format( " " + "%.2f", b + " " + "%.2f", a + " " + "%.2f", c + " \n");
a = d*(a) + b;
}
java
public class test8 {
public static void main(String[] args) {
double num = 1.34567;
System.out.format("%.4f", num);
}
}

If you're trying for insert multiple doubles into a string, you mean something like this:
System.out.format(" %.2f %.2f %.2f \n", b, a, c);
What you had is passing strings as the arguments to format, and you can't use %f to insert a string argument.
System.out.format(" " + "%.2f", b + " " + "%.2f", a + " " + "%.2f", c + " \n");
^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
format string string arg 1 string arg 2 string arg 3

Use this
double num = 1.34567;
DecimalFormat df = new DecimalFormat("#.##");
df.format(num);
I would also suggest that you take the time to read through this https://stackoverflow.com/help/how-to-ask

Related

Strange result when trying to add a char after an integer and then print the result

I'm trying to create a simple calculator voor Ohm's law.
So the idea is that you can fill in 2 variables and then it will calculate the third variable.
When I was creating this program, I found a little problem and I don't understand how it happens and unfortunately I'm not able to find the answer.
I tried to print a String where the complete calculation is shown. So the 2 variables the user filled in and the answer. After the variable for Ohm ('R' in this example) the correct symbol should be printed aswell.
As shown in the example below, the only way I can add the symbol after the variable is by first adding an empty string(""). Otherwise the unicode wil be added to the variable?!
I've made a quick example to show my problem:
public class Main {
public static void main(String[] args) {
float R = 2.54f;
float U = 4.00f;
float I = R / U;
char ohm = '\u2126';
System.out.println(R + "" + ohm + " (R) / " + U + "V (U) = " + I + "A (I)");
System.out.println(R + ohm + " (R) / " + U + "V (U) = " + I + "A (I)");
}
}
Result in console:
2.54Ω (R) / 4.0V (U) = 0.635A (I)
8488.54 (R) / 4.0V (U) = 0.635A (I)
As you can see, the second print doesn't show the Ohm symbol, but adds a value to the variable 'R'. Hopefully I've made my question clear enough.
Thanks in advance.
R + ohm performs a numeric addition of a float and a char (which is an integral type). Therefore you see a float result instead of the String concatenation you expect. The float result you see is 8486 + 2.54 (since 8486 is the decimal value of the hexadecimal number 2126).
In your first println statement you avoid that by concatenating a String ("") to the float, which results in a String. Then the Ohm char is concatenated to that String.
You can also begin with the empty String to get the desired output:
System.out.println("" + R + ohm + " (R) / " + U + "V (U) = " + I + "A (I)");

How do i use the printf command with more than one string and arg?

I have written a object that creates a rectangle in java (eclipse), but when i try to print out the information about the rectangle I get a wired error.
This works fine, but is not to pleasant to lock at, since it returns a value with 14 digits after ","
System.out.println("Rectangle2\t Width: " + rectangle2.width + "\tHeight: " +
rectangle2.height + "\tArea: " + rectangle2.getArea() + "\tPerimiter: " + rectangle2.getPerimiter());
While this prints it with two digits after ",", which is what I'm trying to accomplish. But it only prints the first string and number and results in an error.
System.out.printf("Rectangle2\t Width: %.2f%n", rectangle2.width, "\tHeight: %.2f%n",
rectangle2.height + "\tArea: %.2f%n", rectangle2.getArea() + "\tPerimiter: %.2f%n", rectangle2.getPerimiter());
If i only use "," instead of "+" the error don't come up, but it still only prints the first string and number. How do I print it with %.2f%n without most of it disappearing?
The first parameter of printf is the format String and all the other parameters are the arguments to format the String.
System.out.printf("Rectangle2\t Width: %.2f%n\tHeight: %.2f%n\tArea: %.2f%n\tPerimiter: %.2f%n", rectangle2.width,rectangle2.height, rectangle2.getArea(),rectangle2.getPerimiter());

Love letter- using arrays to print message

I've been asked to create a program that stores series of suitable nouns, adjectives and verbs in arrays. These must be set up at the start of program run. Rather than ask the user, each time it generates letter it just chooses words at random from the appropriate array. The arrays are passed to methods that represent the templates.
I'm new to java, and this is what I have managed to get done below, however shows errors saying void cannot be converted to string for each print message part. I would be glad if someone can help me approach this simple question which i'm struggling on, I don't know if I am doing it correctly.
Any help would be much appreciated.
public static void arrays()
{
String []noun = {"face", "eyes", "tender", "lips", "ears", "roses"};
Random random = new Random();
int rand1 = random.nextInt(noun.length);
String []verb = {"enchant", "dazzle", "cuddle" , "lure", "desire", "dream" };
Random random2 = new Random();
int rand2 = random2.nextInt(verb.length);
String []adjective = { "Alluring", "Angelic", "Adoring", "Appealing", "Attractive", "beautiful"};
Random random3 = new Random();
int rand3 = random3.nextInt(adjective.length);
printmessage (noun[rand1], verb[rand2], adjective[rand3]);
}
// END arrays
public static void printmessage(String noun, String verb, String adjective)
{
System.out.println("I would love to " + verb + " " + adjective + " " + noun + "\n");
System.out.println("Your are my " + noun + " " + adjective + " " + verb + "\n");
System.out.println("you always look great in that " + noun + " ,as you always do, since your so " + adjective + "\n");
System.out.println("I get butterflies when I see you in" + noun + " , you make me " + verb + " , in your " + adjective + " world" + "\n");
}
} // END class loveletter
You've got some issues here, so let's walk through them.
First, the conceptual issue. You shouldn't need to return anything from your printmessage method, as all you're doing is showing a message dialog.
Next, you don't do anything with those four result variables, and they would only last within the scope of that method. That's to say, not very long. I don't think you need them.
Next, the technical issues:
One return is all it takes for the code execution to halt. If it were valid code, you would only get back result1. Since we discussed earlier that you don't need to return anything from this method, remove the superfluous returns.
JOptionPane#showMessageDialog returns void; that is to say, it returns nothing. You can't assign a value of its return type to a variable, so the variables do you absolutely no good. Remove the assignment and declarations.
Don't forget to change the return type of your method to void instead of String.
Clean up the call in arrays() so that it only calls printmessage at the end, and doesn't do anything else after that.
I leave the logical errors (I did notice some funky string concatenation and grammatical errors in there) as an exercise to the reader.

Java System.out.println syntax help for multiple variables [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm new to java and trying to print the values of multiple variables.But the quotes inside the System.out.println confusing me.Can anybody explain the following syntax?
Why "+ b1.cc" is outside the quotes ?
My code:
System.out.println("Bike data " + b1.brand + " " + b1.color + " " + b1.cc);
Let's say you have:
String one = "1";
String two = "2";
String three = "3";
System.out.println("one: " + stringOne + " and two: " + stringTwo + " and also a three: " + stringThree);
Will print
one: 1 and two: 2 and also a three: 3
It is called concatenation. I.e. you "create a new String".
Look at this answer too for mor information.
In you actual code " " will just add a white space between the values of your variables.
I think you need to learn about string concatenation in Java. You can call a method to concatenate (join together) two strings, but you can also use the + operator.
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end.
You can also use the concat() method with string literals, as in:
"My name is ".concat("Rumplestiltskin");
Strings are more commonly concatenated with the + operator, as in
"Hello," + " world" + "!"
which results in
"Hello, world!"
The + operator is widely used in print statements. For example:
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
which prints
Dot saw I was Tod
Such a concatenation can be a mixture of any objects. For each object that is not a String, its toString() method is called to convert it to a String.
You have presented an example of String concatenation, equally valid would be building a String reference separately like,
String str = "Bike data " + b1.brand + " " + b1.color + " " + b1.cc;
System.out.println(str);
Java also supports formatted printing. Assuming those fields are all String(s) you could use
System.out.printf("Bike data %s %s %s", b1.brand, b1.color, b1.cc);
or String.format()
String str = String.format("Bike data %s %s %s", b1.brand, b1.color, b1.cc);
The quotes create a String object for the JVM to use. The variables:
b1.brand
b1.color
b1.cc
will return a String object already so the quotes aren't necessary. If, for instance, b1.color was in quotes, it would print specifically b1.color and not what the variable holds.

ToString () in java Can't make a \t [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So I have a to string method and I want to print an Arraylist with a tab after each one
public String toString() {
return plate + " " + year + " " + mfg + " " + style + " " + color + "\\t";
}
This is where I'm calling
System.out.println(resultList.toString());
And I get result all in one line with [ ].
Use "\t" not "\\t". The latter outputs a literal \ followed by a t.
However, this is a little bit of a code smell. You generally shouldn't be doing output formatting like this in toString(), it may be OK for your simple use case but if you make a habit out of it it can cause issues and confusion in larger applications. At minimum, consider the tab to be part of your UI, and keep it at a slightly higher level, e.g.:
for (Result r : resultList) {
System.out.println(r + "\t");
}
Even better, consider doing all formatting at a higher level rather than in toString(), e.g.:
for (Result r : resultList) {
System.out.println(r.getPlate() + " " + r.getYear() + " " +
r.getMfg() + " " + r.getStyle() + " " +
r.getColor() + "\t");
}
Your usage of toString() is certainly convenient and may make sense for your application, and it isn't inherently evil, but just be aware of what you are doing. Generally (but certainly not always), toString() is used for debugging, not formatting of composite objects.
You need to unescape the Tab. Change \\t to \t
Your version has Java escaping the \, so \\ produces the character literal \ which goes adjacent to the following t. You want to escape the t, not the \, so write \t which produces a tab character.
If you're looking to write every result on a new line, then you need to replace \t with the newline character \n.

Categories