Using 'printf' in Java - java

I am having problems implementing the printf method into my code. I started my first Java course this week and am trying to get ahead of the class. Essentially, I am to create an output of ASCII characters, hexadecimal numbers, and their decimal equivalents, up to 127 entries. The number of rows created in the output is chosen by user input. This is the code I have so far:
package lab1;
import java.util.Scanner;
public class Lab1 {
public static void main(String[] args) {
//declare
Scanner scan = new Scanner(System.in);
//prompt the user to enter an integer, num defines the # of rows displayed in output
System.out.print("How many groups? ");
int num = scan.nextInt();
//print ascii, then hex value, then dec value
for (int c = 0; c < 128; c++) {
String hex = Integer.toString(c , 16);
String output = (char)c + " " + hex + " " + c;
System.out.println(output);
/*
//print the output with printf to create the columns
//character (c), string(s), decimal integer(d)
System.out.printf("%-2c %-2s %-2d", output);
*/
}
}
}
I would have posted an image here showing what the final result should look like but I need 10 reputation. I am able to email a copy to you privately though.
I hope you can help me understand how to accomplish this, or direct me to a resource where I am able to learn myself.
Thanks!

You need to pass the same number of arguments as you have flags in your printf.
for (int c = 0; c < 128; c++) {
// String hex = Integer.toString(c , 16); - No need for this anymore.
// Print the output with printf to create the columns
// character (c), string(s), decimal integer(d)
System.out.printf("%-2c 0x%-2X %-2d%n", (char)c, c, c);
}
With 0x%-2X, you can print out uppercase Hex values. I added 0x as a prefix to specify the base.
Example output:
...
A 0x41 65
B 0x42 66
C 0x43 67
D 0x44 68
E 0x45 69
F 0x46 70
G 0x47 71
H 0x48 72
I 0x49 73
J 0x4A 74
K 0x4B 75
L 0x4C 76
M 0x4D 77
N 0x4E 78
O 0x4F 79
P 0x50 80
Q 0x51 81
R 0x52 82
S 0x53 83
T 0x54 84
U 0x55 85
V 0x56 86
W 0x57 87
X 0x58 88
Y 0x59 89
Z 0x5A 90
...

You don't actually need to pass multiple arguments.
for (int c = 0; c < 128; c++) {
// Print ASCII, then hex, then dec
System.out.printf("%1$-2c %1$-2x %1$-2d%n", c);
}
See the docs here: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html

The problem is you need three arguments for you printf, one each for char, String and decimal. Since you are passing only one variable (which is of type String) it gets confused. Remember, concatenating everything in one String(output) makes all a type String.

You need each tag to correspond with a variable, and your tags need to be formatted correctly.
To print an ascii, hex, and decimal value, your printf statement should look something like this:
System.out.printf("%-2c - %-2x - %-2f", someChar, someHex, someFloat);
where someChar is a char, someHex is an int whose hex value you wish to display, and someFloat is the float/double value you wish to display.
For more information on format strings in Java see: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html

Related

Array of Bytes (as hex) conversion to Int issue. (Kotlin/Java)

I'm looking at parsing information from a temp/humidity sensor that was provided with the following instructions;
There are 6 bytes.
Temperature positive/negative: 0 means positive (+) and 1 means negative (-)
Integer part of temperature. Show in Hexadecimal.
Decimal part of temperature. Show in Hexadecimal.
Reserved byte. Ignore it.
Integer part of humidity. Show in Hexadecimal.
Decimal part of humidity. Show in Hexadecimal.
For example: 00 14 05 22 32 08 means +20.5C 50.8% & 01 08 09 00 14 05
means -8.9C 20.5%
as each byte is in hex & i need to covert this to an Int I followed this approach - Java code To convert byte to Hexadecimal but the values I get when validating their example don't make sense.In Kotlin I do;
val example = byteArrayOf(0, 14, 5, 22, 32, 8)
example.map { Integer.parseInt(String.format("%02X ", it),16)}
First Example output is;
0 = "00 "
1 = "08 "
2 = "09 "
3 = "00 "
4 = "0E "
5 = "05 "
Second Example output;
0 = "00 "
1 = "0E "
2 = "05 "
3 = "16 "
4 = "20 "
5 = "08 "
What am I doing wrong? I'm starting to think the manufactures instructions could be 'misleading'
A key thing you are missing here is that when passing in the it parameter to String#format, that value is a decimal int, not a hexadecimal int.
You instead want to map the value in the array directly to a string, then get its decimal value:
byte it = 14;
int x = Integer.parseInt(String.valueOf(it), 16);
System.out.println(x); // This will print 20
This should get you the expected result.
Note, your problem is slightly confusing because the numbers in your byte array are decimal numbers...already in their hex 'format'. There are a few ways this confusion can be fixed (assuming you have control of the array's type and/or contents):
Use String instead of byte
String it = "14";
int x = Integer.parseInt(it, 16);
System.out.println(x); // This will print 20
Store the values as hex and still convert (i.e., putting a 0x in front of each number)
byte it = 0x14;
int x = Integer.parseInt(String.format("%02X", it), 16);
System.out.println(x); // This will print 20
Store the values as hex and don't convert, because there is no need
byte it = 0x14;
System.out.println(it); // This will print 20
If you go with the second bullet, though convoluted, what you have right now should work, but the third option would be best if you are hardcoding in the byte array's values.

Convert USB keyboard data from byte array to String USB4Java

I am reading a USB Keyboard (QR Code scanner) input using usb4java.
My code snippet looks like this:
byte[] data = new byte[16];
UsbPipe usbPipe = usbEndpoint.getUsbPipe();
if (usbPipe != null) {
if (!usbPipe.isOpen()) {
usbPipe.open();
}
if (usbPipe.isOpen()) {
UsbIrp usbIrp = usbPipe.createUsbIrp();
usbIrp.setData(data);
I have two questions:
1] On pressing A, byte array data is 2,0,0,0,0,0,0,0,2,0,4,0,0,0,0,0
On pressing AB, byte aray data is 2,0,0,0,0,0,0,0,2,0,4,0,0,0,0,0,2,0,5,0,0,0,0,0
How to convert it into character in java? i.e. get A or AB after conversion.
2] Currently, I am passing fixed size of byte array in above code snippet. For example, if I am expecting 1 char, I am passing 16 as size of byte array, for 2 characters 24 as size and so on. Is there any other elegant solution for making it dynamic?
PS: My byte array converter snippet:
StringBuffer sb = new StringBuffer();
for (byte b : data) {
sb.append(b);
sb.append(",");
}
String byteString = sb.toString();
return byteString;
Thanks for any help
EDIT 1: Full source code here: http://tpcg.io/zt3WfM
Based on the documentation the format should be:
22 00 04 00 00 00 00 00
Offset Size Description
0 Byte Modifier keys status.
1 Byte Reserved field.
2 Byte Keypress #1.
3 Byte Keypress #2.
4 Byte Keypress #3.
5 Byte Keypress #4.
6 Byte Keypress #5.
7 Byte Keypress #6.
Based on the ASCII codes
// 'A' is 0x65
byte codeA = 0x04; // The code for A key
cahr a = 0x61 + codeA ;
byte codeX = 0x1B; // The code for X key
char x = 0x61 + code; // x == 'X'
System.out.println(a);
System.out.println(x);
Or you can use a Map(0x04, 'A')

Why am i getting 3 bytes instead 1 byte after hexadecimal/string/byte conversion in java?

I have this program:
String hexadecimal = "AF";
byte decimal[] = new byte[hexadecimal.length()/2];
int j = 0;
for ( int i = 0; i < decimal.length; i++)
{
decimal[i] = (byte) Integer.parseInt(hexadecimal.substring(j,j+2),16); //Maybe the problem is this statement
j = j + 2;
}
String s = new String(decimal);
System.out.println("TOTAL LEN: " + s.length());
byte aux[] = s.getBytes();
System.out.println("TOTAL LEN: " + aux.length);
The first total is "1" and the second one is "3", i thought i would will get "1" in the second total. Why is happen this? My intention is generate another hexadecimal string with the same value as the original string (AF), but i am having this issue.
Regards!
P.D. Sorry for my english, let me know if i explained myself well.
Don't know what exactly you try to achieve. But find below what you are doing.
Integer.parseInt(hexadecimal.substring(j, j + 2), 16) returns 175
(byte) 175 is -81
new String(decimal) tries to create an String from this byte array related to your current character set (probably it's UTF-8)
As the byte array does not contain a valid representation of UTF-8 bytes the created String contains the "REPLACEMENT CHARACTER" for the Unicode codepoint U+FFFD. The UTF-8 byte representation for this codepoint is EF BF BD (or -17 -65 -67). That's why the second length is three.
Have a look here Wikipedia UTF-8. Any character with a codepoint <= 7F can be represented by a single byte. For all other characters the first byte must have the bits 7 and 6 set 11....... Which is not the case for the value -81 which is 10101111. There for this is not a valid codepoint and it's replaced with the "REPLACEMENT CHARACTER".

parse string in char format into an array list java

say for instance i have a string ie
"my dog did a Foo"
i want to pass each character into an array list and then perform operations according to certain indexes.
so i need to convert the characters to their decimal values in this case :-
"my dog did a Foo"
would translate to the following decimal representation:-
109 121 32 100 111 103 32 100 105 100 32 97 32 70 111 111
once this is done i need to send it to an array list and compile a string using the second number "121"
the last number "111" and another lets say "97" and will be doing calculations with those numbers.
so if these are parsed to an arraylist the index for the second number in this case "121" is index1,
the index for "111" in this case would be the index equal to the strings length.(the last char) which means we need to determine this index before.
and finally 97 which would be index 11.
how can i write a statement that will convert the string to decimal Char values, add each char to its own index in array list and then do calculations based on indexes? its been killing me for over a month!
the following code is terribly wrong but hopefully illustrates what i intend to do
if we use "i." to signify an index in the array.
k = 0;
private String lengthofstring = k;
while (k <= lengthofstring){
System.out.println(i.1+i.11 + "-" + i.lengthofstring);
k++
}
supposedly printing :-
218-111(or whichever is at the index equal to lengthofstring)
any help would be amazing
many thanks in advance for any help u can offer.
Having:
String inputString = "my dog did a Foo";
1. To convert a String to an array of chars:
In your case, maybe an ArrayList is not the best option. You could simply use a char array:
char[] allStringChars;
The String class already provides a method for that, or you can do this with some loop like the following algorithm:
declare allStringChars with the inputString size
declare i as 0
for each char on inputString do
copy the char at inputString[i] to the allStringChars[i]
increment i
end
To get a specific char from inputString, use inputString.chatAt(i) method.
2. Do operations on the values:
After to covert the inputString to a array of characters, your can obtain the integer value of any character:
int firstValue = allStringChars[0];
int lastValue = allStringChars[allStringChars.length - 1];
Hope it helps.
Some Suggestions:
you have a String so you can either covert to a array of type char one by one or use a
ready function toCharArray() from String class.
clearly, you need to define a dynamic array which shrinks and expands by itself.
Since, char type is cast-able to int you can cast each elements one by one and add them to
the list.
Since this is a homework so my code answer is :
In Java 8
Code:
String s = "my dog did a Foo" ;
List<String> listString = Arrays.asList(s.split(""));
IntStream.range(0, listString.size())
.map(i-> (int)listString.get(i).charAt(0))
.forEach(i -> System.out.print(" " + i));
Output:
109 121 32 100 111 103 32 100 105 100 32 97 32 70 111 111

Problem converting C/C++ unsigned char to JAVA

The problem with unsigned char.
I am reading a PPM image file which has data in ASCII/Extended ASCII.
For a character, eg. '†' ,
In JAVA, after reading it as char and typecasting into int its value is 8224.
In C/C++, after reading it as a unsigned char and typecasting into int its value is 160.
How would i read in JAVA so as to get value 160 ?
The followng C++
unsigned char ch1 ='†';
char ch2 = '†';
cout << (int) ch1 << "\n"; // prints 160
cout << (int) ch2 << "\n"; // prints -96
In Java,
char ch1 = '^';
char ch2 = '†';
System.out.println (" value : " + (int) ch1); // prints 94
System.out.println (" value :" + (byte) ch1); // prints 94
System.out.println (" value : " + (int) ch2); // prints 8224
System.out.println (" value :" + (byte) ch2); // prints 32
Following are some exceptions
8224 †
8226 •
8800 ≠
8482 ™
8710 ∆
8211 –
8221 ”
8216 ‘
9674 ◊
8260 ⁄
8249 ‹
8249 ‹
8734 ∞
8747 ∫
8364 €
8730 √
8804 ≤
Following are some good ones
94 ^
102 f
112 p
119 w
126 ~
196 Ä
122 z
197 Å
197 Å
Any help is appreciated
In C++ you are using "narrow" characters in some specific encoding that happens to define character '†' as 160. In other encodings 160 may mean something else, and character '†' may be missing altogether.
In Java, you are always dealing with Unicode. 8660 = 0x2020 = U+2020 "DAGGER".
To get "160", you need to convert your string to the same encoding you are using with C++. See String.getBytes(charset).
IIRC Java uses a 16-bit representation for chars (UNICODE?) and C++ normally doesn't unless you use wchars.
I think you'd be better off trying to get C++ to use the UNICODE characters that Java uses rather than the other way around.
If you write out the unsigned char 160 in C++ as a single byte, and use InputStream.read() you will get 160. Which character this means depends on the assumed encoding but the value 160 is unchanged.

Categories