I have written a program that takes a ASCII character input (it actually takes a String then I use charAt(0)) into a JTextField then displays its hex, binary, int, and octal values using g2d.drawString(). I want the ability to also put in "integer" values (again actually being Strings) and display the info. In order to separate the "integer" values from the "char" inputs, I want to be able to input char values as they are, and integers using the pattern #i. This way, I can use an if statement to check if the "integer" pattern is followed, otherwise (else) evaluate the input as a ascii "char". How can I check if a String follows this pattern?
Example:
char input:
3 //I'll evaluate this as the ascii character value of 3
int input:
3i //I'll evaluate this as the integer value of 3
Note: Integer inputs could be multiple digits.
Look at the Pattern class. You will be able to do what you want with this.
Something like this?
if (str.length() == 1) {
char ch = charAt(0);
// code here
} else if (str.endsWith("i")) {
int num = Integer.parseInt(str.substring(0, str.length() - 1));
// code here
} else {
throw new IllegalArgumentException("Bad input: " + str);
}
The parseInt() will throw NumberFormatException if value preceding the i is not valid. Since that is a subclass of IllegalArgumentException, the code above will throw IllegalArgumentException for any bad text.
Related
I'm trying to find a way to convert a char (Precondition is the char can only be '0' or '1') into an actual bit in Java. I'm not sure if Java has some built-in functionality for this, or if there is an algorithm that can be implemented to do so.
I need to implement the following class:
public void writeBit(char bit) {
//PRE:bit == '0' || bit == '1'
try {
} catch (IOException e) {
System.out.println(e);
}
}
I cannot change the method structure in any way. I am implementing Huffman Encoding and have an array of Strings that represent the encodings for every character within an input file. For example, 'A' or array[65] contains the String: "01011". So if I see the letter A in my file, I need to use writeBit to write out A's respective String to a binary file. Every time I reach 8 bits (one byte) I will call writeByte to send those 8 bits to the binary file, then reset some sort of counter variable to 0 and continue.
What I'm stuck on is how I am supposed to convert the char bit into an actual bit, so that it can be properly written out to a binary file.
Java does not have a primitive data type representing a single bit. On many hardware architectures, it is not even possible to access memory with that granularity.
When you say "an actual bit", then, I can only assume that you mean an integer value that is either 0 or 1, as opposed to char values '0' and '1'. There are numerous ways to perform such a conversion, among them:
byte the_bit = bit - '0';. This takes advantage of the fact that char is an integer type, and that the decimal digits zero and one are encoded in Java with consecutive character codes.
byte the_bit = (bit == '0') ? 0 : 1;. This just explicitly tests whether bit contains the value '0', evaluating to 0 if so or 1 if not.
It gets more complicated from there, for example:
byte the_bit = Byte.parseByte(String.valueOf(bit));. This converts the char to a string containing (only) that char, and then parses it as the string representation of a byte.
All of the above rely to one degree or another on the precondition given: that bit does not have any value other than '0' or '1'.
With that said, I think anything like this is probably the wrong approach for implementing a Huffman encoding, because Java Strings are an unlikely, very heavyweight, representation for the bit strings involved.
You can use Integer.parseInt(String s, int radix) or Integer.parseUnsignedInt(String s, int radix) with radix 2, to convert from a "binary digits string" to internal int java integer form.
public static void main(String[] args) {
int num = Integer.parseInt("101010", 2);
// print 42
System.out.println(num);
}
And reversely with method Integer.toBinaryString(int i) you can generate the binary string representation:
// print 101010
System.out.println(Integer.toBinaryString(42));
Similarly you can use Byte.parseByte(String s, int radix) to parse a byte:
public static void main(String[] args) {
byte num = Byte.parseByte("101010", 2);
// print 42
System.out.println(num);
}
I have a logic requirement, where I need to ensure that a hexadecimal digit string is presented in 8-digit format, even if the leading digits are zero. For example, the string corresponding to 0x3132 should be formatted as "0x00003132".
I tried this:
String key_ip = txt_key.getText();
int addhex = 0;
char [] ch = key_ip.toCharArray ();
StringBuilder builder = new StringBuilder();
for (char c : ch) {
int z = (int) c;
builder.append(Integer.toHexString(z).toUpperCase());
}
System.out.println("\ n (key) is:" + key_ip);
System.out.println("\ nkey in Hex:" + addhex + builder.toString());
, but it gave me an error. Can anyone explain how to fix or rewrite my code for this?
and I want to ask one more thing, if use code
Long.toHexString(blabla);
is it true to change the value "0x00" to "\0030" so that the output of 0 is 30
Evidently, you are receiving a String, converting its chars to their Unicode code values, and forming a String containing the hexadecimal representations of those code values. The problem you want to solve is to left-pad the result with '0' characters so that the total length is not less than eight. In effect, the only parts of the example code that are directly related to the problem itself are
int addhex = 0;
and
System.out.println("\ nkey in Hex:" + addhex + builder.toString());
. Everything else is just setup.
It should be clear, however, that that particular attempt cannot work, because all other considerations aside, you need something that adapts to the un-padded length of the digit string. That computation has no dependency on the length of the digit string at all.
Since you're already accumulating the digit string in a StringBuilder, it seems sensible to apply the needed changes to it, before reading out the result. There are several ways you could approach that, but a pretty simple one would be to just insert() zeroes one at a time until you reach the wanted length:
while (builder.length() < 8) {
builder.insert(0, '0'); // Inserts char '0' at position 0
}
I do suspect, however, that you may have interpreted the problem wrongly. The result you obtain from doing what you ask is ambiguous: in most cases where such padding is necessary, there are several input strings that could produce the same output. I am therefore inclined to guess that what is actually wanted is to pad the digits corresponding to each input character on a per-character basis, so that an input of "12" would yield the result "00310032". This would be motivated by the fact that Java char values are 16 bits wide, and it would produce a transformation that is reliably reversible. If that's what you really want, then you should be able to adapt the approach I've presented to achieve it (though in that case there are easier ways).
if use code
Long.toHexString(blabla);
is it true to change the value "0x00" to "\0030" so that the output of
0 is 30
The Unicode code value for the character '0', expressed in hexadecimal, is 30. Your method of conversion would produce that for the input string "0". Your method does not lend any special significance to the character '\' in its input.
i have learned that to convert charsequence to integer we can use this statement
String cs="123";
int number = Integer.parseInt(cs.toString());
what if
cs = "++-+--25";
will this statement still run and give answer -25 according to string given??
You are end up with a NumberFormatException since ++-+--25 is not a valid integer.
See the docs of parseInt()
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
So you are allowed to do
CharSequence cs = "-25"; //gives you -25
and
CharSequence cs = "+25"; //gives you 25
Otherwise ,take necessary steps to face the Exception :)
So know the char Sequence is a valid string just write a simple method to return true or false and then proceed further
public static boolean {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false; // no boss you entered a wrong format
}
return true; //valid integer
}
Then your code looks like
if(isInteger(cs.toString())){
int number = Integer.parseInt(cs.toString());
// proceed remaining
}else{
// No, Operation cannot be completed.Give proper input.
}
Answer to your question is code will run and throw Exception as "++-+--25" is not a valid int,
java.lang.NumberFormatException: For input string: "++-+--25"
You will get
java.lang.NumberFormatException: For input string: "++-+--25"
Tested example :
CharSequence cs = "++-+--25";
System.out.println("" + Integer.parseInt(cs.toString()));
This code must validate input data from the findActions() method:
try {
System.out.println(findActions(lookingArea.substring(0, right)));// always printing valid number string
Integer.parseInt(findActions(lookingArea.substring(0, right)));// checking for number format
}
catch(NumberFormatException exc) {
System.out.println(exc);
}
But I always have java.lang.NumberFormatException: For input string: "*number*"
that is so strange, because checking with System.out.println(findActions(lookingArea.substring(0, right)));,
I get *number* like 10.0
Integer.parseInt doesn't expect the . character. If you're sure it can be converted to an int, then do one of the following:
Eliminate the ".0" off the end of the string before parsing it, or
Call Double.parseDouble, and cast the result to int.
Quoting the linked Javadocs above:
The characters in the string must all be decimal digits, except that
the first character may be an ASCII minus sign '-' ('\u002D') to
indicate a negative value or an ASCII plus sign '+' ('\u002B') to
indicate a positive value.
10.0 is not an integer number. Instead, you can use:
int num = (int) Double.parseDouble(...);
One of the reason could be that your string is too long to convert into Integer type, So you can declare it as Long or Double based on the provided input.
Long l = Long.parseLong(str);
I need to put a constraint for negative values on string variable. For Eg :--
string zeroval = "0.0000"
String x = "";
if (x==null) || (x.equals(zeroval)) { // code which checks if string x has 0 or null value
x = "--" // replace it by --
}
similarly i want to add another piece of code which checks if String x contains any negative values (for eg : "-0.025") and replace it by --
The above String x should not contain null/zero/negative values
Please help
Note :- In order to add negative value check convert the string to float as i cannot use pattern matching technique for eg:- x.equals("-")
Is your input data always meant to contain valid numbers? If so, you could just use:
BigDecimal number = new BigDecimal(text);
if (number.compareTo(BigDecimal.ZERO) <= 0) {
text = "--";
}
This will validate that it really is a number as well as performing the check. Additionally:
It copes with other representations of 0, e.g. "0.00", "0", "+0"
It uses BigDecimal to avoid oddities in binary floating point representations (e.g. a very small positive value being seen as 0). Unlikely to be a problem, but fundamentally you've got decimal data, so you might as well parse it that way.
Convert it to Integer or double using wrapper class.
String number="12.3434"
if(Double.parseDouble(number)<0)
//do stuff here
You could check if the string starts with a "-":
if (x==null) || (x.equals(zeroval) || x.startsWith("-")) {
x = "--";
}
I can't help but feel you are doing something ill-advised by using Strings to represent numerical data.
You could use Double.parseDouble(String) or Float.parseFloat (String). These methods will help you get a double or a float, respectively.
After this, you can easily check if the value is negative.