ToString () in java Can't make a \t [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 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.

Related

Rounding numbers with 2 decimals [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 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

Intellij Idea Language injection for string - error 'class' or 'interface' expected [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want add syntax highlight to string. I do next.
#Language("Java")
String text = "x != null";
But IntelliJ Idea highlight string error underline and write.
'class' or 'interface' expected. How I can to improve this?
When you inject a language in IntelliJ, you must follow the rules of that language.
Obviously in Java you cannot have such a statement in isolation, instead it must be contained inside a class or a method, as property / local variable / control block.
#Language("Java")
final String test = "class Test { "
+ " private final String myProp = \"It works!\";"
+ ""
+ " public void myMethod() {"
+ " boolean i = false;"
+ " "
+ " if (i) {"
+ " /* My comment */"
+ " }"
+ " }"
+ "}";

java string format, replace ""

I want to ask what the "%" + something + "" does in java? And can't we just use "=" instead of replacing " " with "="?
bar = String.format("%" + percentage +"s", " ").replace(" ", "=")
Yes. It is possible to write directly like this.
bar = String.format("%" + percentage +"s", "=");
That depends a bit on what percentage is; if it is (as I assume) an int, your code just prints "=" to the screen "percentage" times
int percentage = 20;
System.out.println(String.format("%" + percentage +"s", " ").replace(" ", "="));
//prints ====================
If that is the intention, you can't just leave the replace part out - or more specifically: it won't give you the same result:
System.out.println(String.format("%" + percentage +"s", "="));
//prints =
Explanation:
The format("%" + percentage +"s", ...) brings the second parameter to the length you have given (in this case percentage). If the length is shorter than the second parameter, it will add spaces on the left until the desired length is reached.
The first version uses that as a "trick" and replaces the spaces generated afterwards with a "=".
The second version just says: take this "=" and add spaces on the left until it has reached the desired length.

Java String formatting a line with different variable types

I need to put for example 5 spaces after the first variable
2 spaces_go_here 300 batch ordered (due on day 7)
this is the format of the line and it consists of an Integer + Integer + String
I've tried the following but without success.
System.out.printf("%-5d%d%s",i + " " + testProduct.getQuantity() + " batch");
Although printf("%-5s%s",.. works if I'm trying to put spaces in between two Strings
The arguments to the Variadic function PrintStream.printf(String, Object...) are comma separated, this
System.out.printf("%-5d%d%s",i + " " + testProduct.getQuantity() + " batch");
should be something like
System.out.printf("%-5d%d%s",i, testProduct.getQuantity()," batch");
Or
System.out.printf("%-5d%d batch",i, testProduct.getQuantity());

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.

Categories