Strangest thing. I have this line
int i = Integer.parseInt("3",3);
But everytime i run it, i get a NumberFormatException.forInputString. Why? this is a simple base conversion. What is so special about the int 3 that breaks the conversion?
parseInt() expects a String as the first argument.
In base 3 there is no digit "3". Just "0" to "2". A decimal "3" is represented by "10" in base 3.
Integer.parseInt() expects a string to parse, not an integer. You want
int i = Integer.parseInt("3", 3);
You'll also run into the problem that 3 is not a digit in base three. As per the documentation, that will still throw a NumberFormatException.
Any character of the string is not a digit of the specified radix
If you want to parse base-10 to base-n String you can use something like :
System.out.println(Integer.toString(3, 2)); // print 11 -> String data type
Code above is to parse 3 in base 10 (integer) as binary (base-2) String.
Following code should parse base-2 String as base-10 integer value :
System.out.println(Integer.parseInt("11", 2)); // print 3 -> base-10 integer
Code above is to parse 11 binary to base-10 integer. Your code have error with this String format, for base-3 the string only consist 0, 1, 2.
Please note the difference how to use both method.
3 must be a numeric String to parse into an int rather than an int literal:
int i = Integer.parseInt("2", 3);
Furthermore, base-3 numbers cannot contain a 3 digit, as there's only 0, 1 and 2 available. Therefore I used 2 in the example code above.
3 simply does not exist as a digit in base 3...
0, 1, 2, 10, 11, 12, 20, 21, 22, 100
Integer.parseInt takes String as a signed decimal integer, and that integer must be less than and not equal radix value (base).
Integer.parseInt("X",x); //X mustn't contain x.
Related
Don't understand Java's syntax. How to convert: "%6d %7.1f %5.1f" to C# equivalent ?
I keep getting this print out in C#: %6d %7.1f %5.1f
Tried:
"{0:d6} {7:1f} {5:1f}"
But, ran into an exception.
Exception:
Unhandled Exception: System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
at System.String.Format(String format, Object arg0, Object arg1, Object arg2)
at experiment.Main(String[] args)
The Java code:
String.format("%6d %7.1f %5.1f", int, double, double/double);
It's obvious what values will be generated based on variable data types.
EDIT: I just looked at, Convert this line of Java code to C# code
C#
String.Format("{0:x2}", arrayOfByte[i]);
Java
String.format("%02x", arrayOfByte[i]);
PLEASE. PLEASE. PLEASE. DO not close this. Kindly. Please.
NOTE: Completely rewrote my original answer based on a (hopefully) better understanding of the Java format specifiers.
Based on my (Google-limited understanding), %6d, %7.1f and %5.1f correspond to the following:
An integer with up to 6 characters, padded if less than 6.
A float with up to 7 characters (including the decimal point and decimal portion) with a precision of 1.
A float with up to 5 characters (including the decimal point and decimal portion) with a precision of 1.
You can accomplish this with C#'s String.Format, like this:
var newString = String.Format("{0,6:d} {1,7:f1}, {2,5:f1}", 605, 20.5, 8.22);
This will result in the following string:
" 605 20.5 8.22"
The first digit in each placeholder group (defined by { and }) corresponds to the argument passed in after the string:
0 = 605
1 = 20.5
2 = 8.22
The second digit, after the , refers to the length of the string (including decimal points and decimal portions).
6 = 6 characters for the integer
7 = 7 characters for the float
5 = 5 characters for the float
The letters and numbers after the : are the format specifiers.
d = integer
f1 = floating with a precision of 1.
Which produces the string above, as follows:
{0,6:d} turns 605 into " 605" (3 leading spaces due to the 6 before the :)
{1,7:f1} turns 20.5 into " 20.5" (3 leading spaces due to the 7 before the :)
{2,5:f1} turns 8.22 into " 8.2" (1 leading space due to the 5 before the : and 1 decimal number due to the precision).
As I said earlier, check String.Format and Standard Numeric Format Strings for more information.
Starting from C# 6. you can use interpolation.
For your case you may wanted to try the following:
string formattedString = $"{0:d6} {7.1:f} {5.1:f}";
before C# 6 you can try the following:
string formattedString = String.Format("{0:d6} {1:f} {2:f}", 0, 7.1, 5.1);
I want to create a numerical representation of 5 letter codes. The codes may have 1-5 letters or digits.
The number must of course be unique. It is not absolutely necessairy that those numbers can be converted back to the ascii.
Thus I need digits from 0 to ZZZZZ
The resulting number size should be as small as possible.
I started with the following, but it's not quite what I want:
String a="ZZZZZZ";
for (int i = 0; i < a.length(); ++i) {
System.out.print(a.charAt(i)-'A'+1);
}
ZZZZZZ=262626262626
000000=-16-16-16-16-16-16
Start by enumerating all possible "digits" of your number:
Ten decimal digits 0 through 9
Twenty six letters A through Z
You have 36 possible "digits" for five positions, so the max number is 365=60,466,176. This number fits in an int.
You can make this number by calling Integer.parseInt, and passing a radix of 36:
System.out.println(Integer.parseInt("ABZXY", 36)); // 17355958
Demo.
Keep in mind that A134Z is already a number; it is only printed in Base-36 representation!
Albeit being just one sentence, the above should give you all you need to know to translate any 5-character string with 0-9 and A-Z into a number (and back).
Simplest solution - if letters are case insensitive is to use radix of 36 - full alphabet plus 10 digits. That way you get both functions for free - converting from string to long and from long to string like this:
long numericCode = Long.parseLong("zzzzz", 36); // gives 60466175
String stringCode = Long.toString(numericCode, 36); // gives "zzzzz"
You can treat the string as a number in base36 (where A=10, B=11 ... Z=35). This way, you will use exactly the numbers from 0 to 36^5-1, and each will be used exactly once.
This question already has answers here:
Converting Roman Numerals To Decimal
(30 answers)
Closed 8 years ago.
I'm a new programming student and my assignment is to convert the input of a Roman Numeral to it's integer value. Here is what I have been given:
Write a program that converts a Roman number such as MCMLXXVIII to its decimal number representation. This program must have 3 methods and a main method!
Write a method that takes input from the user and passes it to a conversion method.
Write a method that yields the numeric value of each of the letters (conversion method).
Write a method that outputs the number the user entered and the converted number.
Write a main method to test the 3 methods.
HINT: Use a single dimensional array!
Convert a string as follows:
• Look at the first two characters. If the first has a larger value than the second, then simply convert the first.
• Call the conversion method again for the substring starting with the second character.
• Add both values. o If the first one has a smaller value than the second, compute the difference and add to it the conversion of the tail.
Now I am struggling trying to figure out what to do for my conversion method. Here is what I have written so far:
public static String romanInput(String number) {
Scanner numberInput = new Scanner (System.in);
System.out.print("Enter a roman numeral: ");
String userInput = numberInput.next();
return userInput;
}
public static int numberConversion(int number) {
int romanConv = 0;
char[] romanChar = {1, 5, 10, 50, 100, 500, 1000};
for (int i = 0; i < romanChar.length; i++)
}
You could see that I have already written the method that takes the input from a user. I think I did this correctly. However, I don't know what to do for this conversion method. It says to use a single dimensional array so that's what I did over here:
char[] romanChar = {1, 5, 10, 50, 100, 500, 1000};
Those are supposed to be the values of I, V, X, L, C, D, and M. I'm really just confused as where to go from there and I would appreciate it if someone can help me out.
The Roman numeration is non-positional, meaning that the value of the digits does not depend on their position and you can ignore the latter. Then it suffices to add the values of all digits.
There is an exception anyway: if a digit immediately precedes a digit of a higher value, then it is subtracted instead of added.
So the processing is simply:
Clear an accumulator.
Read the digits from left to right. For new every digit, convert it to its value and add it to the accumulator. In the end the accumulator contains the number value.
To handle the exception, you can use the following trick:
Use a variable that holds the value of the previous digit (initially set to the value of M);
when the current digit has a higher value than the previous, you must correct the accumulator by subtracting twice the value of the previous.
Programmatically:
( Initialize )
Prv= 1000
Acc= 0
Loop:
( Accumulate )
Cur= Lookup(Digit[i])
Acc+= Cur
( Adjust for inversions )
if Prv < Cur -> Acc-= 2 * Prv
Prv= Cur
For instance, CXIX gives
Prv Cur Acc
C 1000 100 100
X 100 10 110
I 10 1 111
X 1 10 121-2*1 = 119
If I were you, I would begin by taking one baby step at a time. For example, if the only input I have to worry about is "I", then what? That is trivial of course.
Next, if the input is "II", then what? This suggests that I need to process the input one character at a time. Both the "I"s are equal to one each, and the result is the sum of the two. That means, I must have a "result" or some such variable, initialized to zero, and then for each character from the input string (I, then I), convert that to its numeric value (1, and then 1), add them up and return the value.
This logic works well for "III" also.
But then you face your first challenge with "IV". That is not trivial, specially if you are new to such an algorithm. Let me keep it aside, with a note that that is tough so will deal with this later.
The values "V", "VI", "VII", "VIII" all work fine with the above logic.
But then again I would be stuck with "IX". Similar to "IV" above. Maybe I have an idea about these two now, but then, maybe I'll still keep both these aside for the time being.
This works fine for "X", "XI", "XII", "XIII", and then again problem with "XIV".
I'll resist the temptation to solve the problems of "IV", "IX", "XIV" so that you can try them yourself; remember these are non-trivial, at least compared to what I have written above. Try it out.
So you see, incremental addition works well, but reduction is an unresolved problem.
Hope this helps.
I was playing a bit with numbers, and something interesting came upon me, which I don't quite understand.
public static void main(String[] args) {
int hexNumber = 0x7A;//decimal: 122 binary:0111 1010
int decNumber = 122;
int binNumber = 1111010;
System.out.println(hexNumber);//122
System.out.println(Integer.toString(hexNumber, 16)); //7a
System.out.println(Integer.toHexString(hexNumber)); //7a
System.out.println(Integer.toString(hexNumber, 2)); // 1111010
System.out.println(Integer.toBinaryString(hexNumber)); //1111010
System.out.println(hexNumber==binNumber);//false
System.out.println(hexNumber==decNumber);//true
System.out.println(decNumber==binNumber);//false
}
Why do I get "false" at #1 and #3? Doesn't change even if binNumber = 01111010;
Well, you can't directly store binary values in Java without any prefix.
binNumber isn't stored as the binary number 1111010; instead, it's stored as the decimal number 1111010.
This you have to store as int binNumber = Integer.parseInt("1111010", 2); or better yet int binNumber = 0b1111010;.
For octal:
int octalNo = 0177; //'0' is prefix
or
int octalNo = Integer.parseInt("0177", 8); //leading '0's are ignored
For hexadecimal:
int hexNo = 0x177; //'0x' is prefix
or
int hexNo = Integer.parseInt("0177", 16); //leading '0's are ignored
For more info, have a look at this.
You aren't creating the binary number as a binary one. You are creating it as a decimal one (base 10) that happens to only contain 0s and 1s.
To store 0111 1010 in Java 7 use the new binary literal (you can even use underscores for easier reading)
int binNumber = 0b0111_1010;
Because that's not the proper way to specify the binary number (and there is no such way in Java, apart from something like Integer.toBinaryString(122) which would give you a proper binary representation (returned as a String)).
Your number was interpreted as a "normal" decimal integer (if entered without leading 0) or as an integer in octal system (if entered with leading 0).
In Java versions before 7, you need to use this
int binNumber = Integer.parseInt("1111010", 2);
In 7 and up, you can use
int binNumber = 0b1111010;
With that change, your code works here (I get three true resuls).
The answer is clear. You have assigned to integers some diferent values.hexNumber is initialized to decimal value 122, even if the representation you use for that is hexadecimal. decNumber is initialized to decimal value 122, so when you compare hexNumber and decNumber you will get true because it's really the same value. Finally binNumber is initialized to the decimal value 1111010, so if you compare it with one of the other numbers you will get false.
I have 1 String variable in my Java code and it contain of large binary digit. How can I convert it
String binary2 = JTextArea.gettext(); // this is a String variable
Long binary3 = Long.parseLong(binary2);
System.out.print(Long.toOctalString(binary3));
You can get use of BigInteger class which is more appropriate to use in your solution. It has an overloaded toString() method which takes radix (in your case radix = 8).
String largeBinary = "10101010100000100111011010101";
String octalVersion = (new BigInteger(largeBinary,2)).toString(8);
Every three binary digits (0 or 1) represent exactly one octal digit (from 0 to 7).
So I think the algorithm is simple: iterate over every 3 subsequent characters and convert them to one octal digit:
"000" -> "0"
"001" -> "1"
"010" -> "2"
"011" -> "3"
...
"111" -> "7"
Extra care need to be taken in the beginning if the length of the string is not a multiply of 3. Example:
"1001001110"
"10|101|001|110"
2| 5| 1| 6
This approach does not require parsing the string and no extra memory. It can work on arbitrarily long input and is super fast
A long value can hold any number up to 2^63-1, which is sufficient for many applications. All you need to do is to provide the appropriate radix parameter to the parseLong(String string, int radix) method (and the toString(Long number, int radix) method).
long number = Long.parseLong(binaryString, 2);
String octalString = Long.toOctalString(number); // or Long.toString(number, 8);