Using spaces between specifiers - java

I've recently started learning JAVA. I am currently working on a few daily exercises, related to stdout and formatting.
Exercise:
Each line of output must have 2 columns
1st column: string left justified to 15 characters
2nd column: integer expressed in three digits
I finally figured out a way and came up with:
System.out.format("%-15s %03d %n",s1 , x );
But when I ran the program there was an error.
Later when I removed the spaces between specifiers i.e.
System.out.format("%-15s%03d%n",s1 , x );
The code seemed to work.
Just wanted to know what difference does it make when space is not added.

The added space(s) within the format string would be literal whitespaces. This means that you will get your 15 spaces from the beginning of the supplied string plus one whitespace which therefore makes a total spacing of 16. The same applies to the numerical value added to the output. The space after %03d would add an additional whitespace after the numerical value. Knowing this you can apply it to an example:
String s1 = "My Name";
int x = 61;
System.out.format("%-15s %03d %n", s1, x ); // Spaces in format.
System.out.format("%-15s%03d%n", s1, x ); // No Spaces in format.
The output will be:
My Name 061
My Name 061
Whereas:
My Name 061
^^^^^^^^^^^^^^^^^^^^
| 16 ||4 |
My Name 061
^^^^^^^^^^^^^^^^^^
| 15 ||3|
This format (either way) will not generate an error. What will generate and error is if any one or both of the supplied variables to the format() method are of the wrong Data Type. Is the variable s1 declared as a String and is the variable x declared as an decimal integer (int)? If not then you can end up with a IllegalFormatConversionException. See Here for proper Converter Tags to use with the format() method.

Related

JavaFX string to unicode entity conversion [duplicate]

This question already has answers here:
Creating Unicode character from its number
(13 answers)
Closed 13 days ago.
I have to read a string from a file and display the corresponding unicode representation in a Text field on my application.
For example I read the string "e13a" from the file and i'd like to display the corresponding "\ue13a" character in the Text field.
Is there a way to obtain the desired behaviour?
I already tried escaping the string directly in the file but I always obtain the raw string instead of the unicode representation
tl;dr
Character.toString( Integer.parseInt( "e13a" , 16 ) )
See this code run at Ideone.com.

Code point
Parse your input string as a hexadecimal number, base 16. Convert to a decimal number, base 10.
That number represents a code point, the number permanently assigned to each of the over 144,000 characters defined in Unicode. Code points range from zero to just over one million, with most of that range unassigned.
String input = "e13a" ;
int codePoint = Integer.parseInt( input , 16 ) ;
Instantiate a String object whose content is the character identified by that code point.
String output = Character.toString( codePoint ) ;

Avoid char
The char type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most characters.
To work with individual characters, use code point integers as seen above.
I posted the question after a lot of trying and searching.
Shortly after posting I found a more trivial solution than I expected:
The converted string is:
String converted = String.valueOf((char) Integer.parseInt(unicodeString,16));
where "unicodeString" is the string I read from the file.

How can i use printf in java to to print formatted output

I'm trying to format my output with System.out.printf(); function in java .
the output format is like this :
In each line of output there should be two columns:
The first column contains the String and is left justified using exactly characters.
The second column contains the integer, expressed in exactly digits; if the original input has less than three digits, you must pad your output's leading digits with zeroes.
================================
java 100
cpp 065
python 050
================================
Use String's format to format strings the way "sprintf" does in C.
From that reference, adapting to your need:
Padding left with zeros:
String.format("|%03d|", 93); // prints: |093|
String of spefiied length (involves max and min)
String.format("|%-15.15s|", "Hello World"); |Hello World |
You want left justified so "-N" instead of N for first value
Java 8's official format reference: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#format-java.lang.String-java.lang.Object...-
And format string documentation: https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax

Java Extract multiple values from String

As part of a calulator program I am writing, I am required to have the user input all the parameters in one string and I need to extract the corresponding values from it.
For example the user enters "3 5 *" he'll get "15" back.
So the program I need to write will take '3' and assign that to double input1, '5' to double input2, and '*' to char operator. How do I get java to assign parts of a string to different members.
I was thinking of maybe splitting the user's string into multiple strings and parsing the values out but I don't know how effective that would be. Thanks in advance.
You will need to consider the order of operations if you have more then one operation. IE (3 4 +) 3 *. A common method for this would be to use a stack. Push the values onto the stack and perform the operation on the values you pop following the operation itself. For parsing simply split on the space ' '. However if you have more complex expressions consider a post order traversal, or stack implementation.
This question has already been answered here: Evaluating a math expression given in string form
I gave a very simple breakdown in my answer here as well: Calculating String-inputed numerical expressions?
You can use the StringTokenizer to split the string wherever it finds a space.
String s = "3 5 *";
StringTokenizer st = new StringTokenizer(s);
You can check if there are more tokens via st.hasMoreTokens().
You can use the token aka string via st.nextToken() (it returns a string).
You can also cast each "string" such as the "3" into a double via:
String firstNumString = "3";
Double first = Double.parseDouble(firstNumString);
This results in the Double variable 'first' containing the number 3.

Confusion Decoding Using Format and Printf

I am very new to String formatting using format() and printf methods. I have read the tutorial on Oracle site but finding it very confusing. So decided to try some examples. I got this sample and
have understood the output as 124.00
public class TestStringFormatter {
public static void main(String[] args){
/* I do understand % - denotes start of instruction
, is the flag
6 - denotes width
2 - Denotes precision
f - Type */
String s = String.format("%,6.2f",124.000) ;
System.out.printf(s);
}
}
What i am not able to understand is , is the flag and how it is used in this formatting?
Can someone explain the use of flag "," in this example.
The comma flag indicates that commas will be used to separate thousands, at least in the US. In other countries, it will use separators that make more sense in those countries. For example, formatting 123 with the comma flag will yield 123, and formatting 123456789 with the comma flag will yield 123,456,789.

Java String split is not working

Java Experts ,
Please look into the below split command code and let me know why last two nulls are not captured.
String test = "1,O1,,,,0.0000,0.0000,,";
String[] splittest = test.split(",");
System.out.println("length -"+splittest.length);
for (String string : splittest) {
System.out.println("value"+string);
}
The result iam getting
length -7
value1
valueO1
value
value
value
value0.0000
value0.0000
surprisingly the length is 7 where as it should be 9 and also as you can see values after 0.0000 ie two last nulls are not coming . Lets say now if i change the string test
"1,O1,,,,0.0000,0.0000,0,0"
String test = "1,O1,,,,0.0000,0.0000,0,0";
String[] splittest = test.split(",");
System.out.println("length -"+splittest.length);
for (String string : splittest) {
System.out.println("value"+string);
}
I am getting correctly
length -9
value1
valueO1
value
value
value
value0.0000
value0.0000
value0
value0
I don't think iam doing wrong . Is it a bug ? JAVA Version - jdk1.6.0_31
It behaves as specified in the javadoc:
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
If you want to keep the trailing blank strings, you can use the 2 argument split method with a negative limit:
String[] splittest = test.split(",", -1);
If the limit is non-positive then the pattern will be applied as many times as possible and the array can have any length.
split silently discards trailing separators, as specified in the Javadoc.
In general, the behavior of split is kind of weird. Consider using Guava's Splitter instead, which has somewhat more predictable and customizable behavior. (Disclosure: I contribute to Guava.)
Splitter.on(',').split("1,O1,,,,0.0000,0.0000,,");
// returns [1, O1, , , , 0.0000, 0.0000, , ]
Splitter.on(',').omitEmptyStrings()
.split("1,O1,,,,0.0000,0.0000,,");
// returns [1, O1, 0.0000, 0.0000]
As mentioned above, test.split(","); will ignore trailing blank strings. You could use the two parameter method with a large second argument. However, the API also states
If n is non-positive then the pattern will be applied as many times
as possible and the array can have any length.
where n is the second argument. So if you want all the trailing strings, I would recommend
test.split(",", -1);

Categories