Java: Easier pretty printing? - java

At the end of my computations, I print results:
System.out.println("\nTree\t\tOdds of being by the sought author");
for (ParseTree pt : testTrees) {
conditionalProbs = reg.classify(pt.features());
System.out.printf("%s\t\t%f", pt.toString(), conditionalProbs[1]);
System.out.println();
}
This produces, for instance:
Tree Odds of being by the sought author
K and Burstner 0.000000
how is babby formed answer 0.005170
Mary is in heat 0.999988
Prelim 1.000000
Just putting two \t in there is sort of clumsy - the columns don't really line up. I'd rather have an output like this:
Tree Odds of being by the sought author
K and Burstner 0.000000
how is babby formed answer 0.005170
Mary is in heat 0.999988
Prelim 1.000000
(note: I'm having trouble making the SO text editor line up those columns perfectly, but hopefully you get the idea.)
Is there an easy way to do this, or must I write a method to try to figure it out based on the length of the string in the "Tree" column?

You're looking for field lengths. Try using this:
printf ("%-32s %f\n", pt.toString(), conditionalProbs[1])
The -32 tells you that the string should be left justified, but with a field length of 32 characters (adjust to your liking, I picked 32 as it is a multiple of 8, which is a normal tab stop on a terminal). Using the same on the header, but with %s instead of %f will make that one line up nicely too.

What you need is the amazing yet free format().
It works by letting you specify placeholders in a template string; it produces a combination of template and values as output.
Example:
System.out.format("%-25s %9.7f%n", "K and Burstner", 0.055170);
%s is a placeholder for Strings;
%25s means blank-pad any given String to 25 characters.
%-25s means left-justify the String in the field, i.e. pad to the right of the string.
%9.7f means output a floating-point number with 9 places in all and 7 to the right of the decimal.
%n is necessary to "do" a line termination, which is what you're otherwise missing when you go from System.out.println() to System.out.format().
Alternatively, you can use
String outputString = String.format("format-string", arg1, arg2...);
to create an output String, and then use
System.out.println(outputString);
as before to print it.

How about
System.out.printf("%-30s %f\n", pt.toString(), conditionalProbs[1]);
See the docs for more information on the Formatter mini-language.

http://java.sun.com/j2se/1.5.0/docs/api/java/text/MessageFormat.html

Using j-text-utils you may print to console a table like:
And it as simple as:
TextTable tt = new TextTable(columnNames, data);
tt.printTable();
The API also allows sorting and row numbering ...

Perhaps java.io.PrintStream's printf and/or format method is what you are looking for...

Related

Java: Limiting decimals from a double in output without e.g. %5.2d

I'm very (read: extremely) new to java and was going to make a table with 5 columns print out for an assignement.
The two first columns are strings, third one an int, fourth a double and fifth an int. It is three rows in total that are affected by this.
I formatted it with printf and:
System.out.printf(Locale.ENGLISH, "%s%10s%14d%20.2f%12d\n", stringOne,
stringTwo, firstInt, stupidDouble, secondInt);
and
"%s\t%s\t\t%d\t\t%2.4f\t\t%d\n" (with the format and stuff above as well ofc).
But the teacher didn't want me to "hard code" the layout since it's part of learning special commands (like \t) and thus wanted me to change it and adress it in the variable itself instead.
I've been trying everything I can think of but can't get it to skip the last decimals, which are unneccesary 0's.
I wish I could've just used the numbers as a string instead, but I need it to calculate the last int with:
static int lastInt = (int) Math.round ( stupidDouble - firstInt )
What I suspect that my teacher is looking for me to do is tabs all the way like:
"%s\t%s\t\t%d\t\t%f\t\t%d\n"
But I need to double to be e.g. 1.2345 instead of 1.234500.
If it makes any difference, it's 3 different doubles (3 different rows in the table); one with 2 decimals, one with 4 and one with 5.
It would more or less save my weekend if someone could help me with this. The simplest possible solution would be much appreciated. <3

Deeplearning4j: LSTM example for review sentiment analysis

I am looking through the example of deeplearning 4j for classifying movie reviews according to their sentiment.
ReviewExample
At line 124-142 the N-dimensional arrays are created and I am kind of unsure what is happening at these lines:
Line 132:
features.put(new INDArrayIndex[]{NDArrayIndex.point(i),
NDArrayIndex.all(), NDArrayIndex.point(j)}, vector);
I can image that .point(x) and .point(j) address the cell in the array, but what exactly does the NDArrayIndex.all() call do here?
While building the feature array is more or less ok what is happening there I get totally confused by the label mask and this lastIdx variable
Line 138 - 142
int idx = (positive[i] ? 0 : 1);
int lastIdx = Math.min(tokens.size(),maxLength);
labels.putScalar(new int[]{i,idx,lastIdx-1},1.0); //Set label: [0,1] for negative, [1,0] for positive
labelsMask.putScalar(new int[]{i,lastIdx-1},1.0); //Specify that an output exists at the final time step for this example
The label array itself is addressed by i, idx e.g. column/row that is set to 1.0 - but I don't really get how this time-step information fits in? Is this conventional that the last parameter has to mark the last entry?
Then why does the labelsMask use only i and not i, idx ?
Thanks for explanations or pointer that help to clarify some of my questions
It's an index per dimension. All() is an indicator (use this whole dimension). See the nd4j user guide:
http://nd4j.org/userguide
As for the 1. That 1 is meant to be the class for the label there. It's a text classification problem: Take the window from the text and word vectors and have the class be predicted from that.
As for the label mask: The prediction of a neural net happens at the end of a sequence. See:
http://deeplearning4j.org/usingrnns
write a test and you will know it.
val features = Nd4j.zeros(2, 2, 3)
val toPut = Nd4j.ones(2)
features.put(Array[INDArrayIndex](NDArrayIndex.point(0), NDArrayIndex.all, NDArrayIndex.point(1)), toPut)
the result is
[[[0.00, 1.00, 0.00],
[0.00, 1.00, 0.00]],
[[0.00, 0.00, 0.00],
[0.00, 0.00, 0.00]]]
it will put the 'toPut' vector to the features.

HashMap- java program issues

Rather than explaining some big problem, I'll skip all that and list the small loop I am struggling with. Anyways, I have to print the key of a map, so I am using a special way to print the key by switching the value and the key around.
for (int i = 0; i < elementData.length; i++){
System.out.print("[" + i + "]");
for (Entry<HashEntry<E>, Integer> entry : foob.entrySet()){
if (entry.getValue().equals(i)){
System.out.print(entry.getKey().toString());
}
}
}
This is my goal: Print [0][1][2][3] like that all the way to 20. Along with that, 9 numbers will go in between those numbers in parens randomly, based on my program.
Here is my result:
[0][1]HashSet$HashEntry#7d4991ad[2][3][4]HashSet$HashEntry#4554617cHashSet$HashEntry#28d93b30[5][6][7][8][9]HashSet$HashEntry#232204a1[10][11]
So there's just some trick to make it not print all this machine language looking stuff. Anyways, what do I have to do? Looks like 1 thing was supposed to come after [1], 2 things after [4], something after [9], and so on.
Thanks!
So there's just some trick to make it not print all this machine language looking stuff?
Yea.
Don't try to print an instance of a class that doesn't override Object.toString(). That "machine language looking stuff" is simply the output of Object.toString().
However, I suspect that your real code is doing this:
if (entry.getValue().equals(i)){
System.out.print(entry.toString());
}
because "HashSet$HashEntry#7d4991ad" looks like the output you would get if you printed a HashSet.HashEntry object. (The other possibility is that you have used HashSet.HashEntry objects as keys in your Map.)

Having issue with a very simple java program, not displaying proper result

here is my code that isn't working:
Scanner hello = new Scanner (System.in);
double a = 10;
double c;
System.out.print("Enter the value: ");
c = hello.nextDouble();
double f = a + c;
System.out.printf("The sum of 10 plus user entry is : ", a+c);
No syntax error whatsoever, no error displayed, this is the result :
Enter the value: 100
The sum of 10 plus user entry is :
So there is no result in the second line,,, for the command ( a+c ) as in program. But if i use a ' %.2f ' before ( a+c ) command, it works fine,,
like :
System.out.printf("The sum of 10 plus user entry is : %.2f", a+c);
I tried to search about the '%.2f' but got to know it is used just to ascertain that the following number is to be displayed as a number with two decimal places. (kinda round off thing, i guess)..
I'm totally a rookie at Java. Started studying it at college right now. Was just curious to know about this concept and reason behind why this program worked only with the '%.2f' typed in it, and not without it, although it showed no error. Will be great if someone can answer it. thanks :-)
Java's System.out.printf() method doesn't append information; it substitutes it. The '%.2f' means: "Replace this with the next argument, and convert it to a floating-point number 2 places precise." Removing the '%.2f' would mean that a+c would have nowhere to go, and printf() would discard it.
Since Java's System.out.printf() method is actually based on the printf() from C/C++, you might want to check out this guide.
You are using the wrong function.
You should be using
System.out.println(myString)
Or
System.out.print(myString)
You would format your code as
System.out.println(myExplinationString + a+c)
System.out is an instance of java.io.PrintStream class that is provided as a static field of the System class. printf(String format, Object... args) is one of the methods of the PrintStream class, check this Oracle tutorial on formatting numbers. In brief, the first argument is a format string that may contain plain text and format specifiers, e.g. %.2f, that are applied to the next argument(s). All format specifiers are explained in the description of the java.util.Formatter class. Note, that double value is autoboxed to Double.

small java problem

Sorry if my question sounds dumb. But some time small things create big problem for you and take your whole time to solve it. But thanks to stackoverflow where i can get GURU advices. :)
So here is my problem. i search for a word in a string and put 0 where that word occur.
For example : search word is DOG and i have string "never ever let dog bite you" so the string
would be 000100 . Now when I try to convert this string into INT it produce result 100 :( which is bad. I also can not use int array i can only use string as i am concatinating it, also using somewhere else too in program.
Now i am sure you are wondering why i want to convert it into INT. So here my answer. I am using 3 words from each string to make this kind of binary string. So lets say i used three search queries like ( dog, dog, ever ) so all three strings would be
000100
000100
010000
Then I want to SUM them it should produce result like this "010200" while it produce result "10200" which is wrong. :(
Thanks in advance
Of course the int representation won't retain leading zeros. But you can easily convert back to a String after summing and pad the zeros on the left yourself - just store the maximum length of any string (assuming they can have different lengths). Or if you wanted to get even fancier you could use NumberFormat, but you might find this to be overkill for your needs.
Also, be careful - you will get some unexpected results with this code if any word appears in 10 or more strings.
Looks like you might want to investigate java.util.BitSet.
You could prefix your value with a '1', that would preserve your leading 0's. You can then take that prefix into account you do your sum in the end.
That all is assuming you work through your 10 overflow issue that was mentioned in another comment.
Could you store it as a character array instead? Your using an int, which is fine, but your really not wanting an int - you want each position in the int to represent words in a string, and you turn them on or off (1 or 0). Seems like storing them in a character array would make more sense.

Categories

Resources