Say I have a string phone = "1-800-test"
I need to convert the letters to numbers.
Doing something like this doesn't work (note I'm looping it of course):
phone = phone.replace(phone.charAt(9), (char) getNumber(phone.charAt(9)));
Note that getNumber() is a method that takes a letter and returns a number:
int getNumber(char uppercaseLetter)
Anyway, I get some weird output with the letter replaced by a weird square.
How should I replace the letters with numbers?
(char) 1 is not what you need. You need '1'.
The good way to do that is to create a Map<Character, Character>, pre-populate it: map.put('t', '8'), etc for all letters, and then
for (...) {
Character letter = phone.charAt(i);
Character digit = map.get(Character.toLowerCase(letter));
if (digit != null) {
phone = phone.replace(letter, digit);
}
}
A trivial solution would be to just have one line for each character:
phone = phone.replace('a', '2');
phone = phone.replace('b', '2');
//etc..
(or, for better performance, utilize StringBuilder's replace(..) and indexOf(..))
Doing (char)1 gives you the ASCII character represented by 1 so you get the weird square.
You can just use '1' to instead. If you insist on converting integers to ASCII, just add 48 (since that is where the digits start in the ascii). i.e. (char)48 is '0', (char)49 is '1' and so on. That doesn't seem necessary for me though.
The exact answer to your question, is use:
phone = phone.replace(phone.charAt(9), (char)(48+getNumber(phone.charAt(9))));
But it is NOT recommended...
Related
I am working on the problem to find the next greatest number with the same set of digits.
For this I take a integer value input from the user and I want to convert to char array or int array so that I can access individual digits.
But when I take
int value=09 as the input and convert to char array it gives only 9 as it considers it to be octal value. How can I overcome this ?
it is not possible in java to take the int values with leading zeros.
so for the value with leading zeros take it in string format.
but we can insert zeros
int n=7;
String str=String.format("%04d", n); //4 denotes the size of the string
System.out.println(str); // o/p->0007
It is not possible convert a 09 int value to a String of 9 since the value 09 can not be stored in an int.
int is not capable of storing trailing zeros.
Take this sample.
int foo = Integer.valueOf("09");
System.out.println(foo);
Output
9
So to solve your problem you should get a String from the user, validate it and parse it to an Integer[].
Solution
public Integer[] parseToInteger(String number) {
return Arrays.asList(number.toCharArray())
.stream()
.map(c -> Integer.valueOf(c.toString()))
.toArray(size -> new Integer[size]);
}
Now you have an Array of Integer.
Since leading 0's are dropped from integers there is no reason to support assigning such a value to an int.
If I want to convert 9 to '9' I usually just add '0' to it.
You can also do the following:
char c = Character.forDigit(9,10);
If you have a string of characters, you can do the following:
String str = "09";
List<Character> chrs =
str.chars().mapToObj(a -> Character.valueOf((char) a))
.collect(Collectors.toList());
System.out.println(chrs);
Prints
[0,9]
You are asking how to parse a number starting with a leading zero, but I get the feeling that you are actually on the worng track given the problem you are trying to resolve. So let's take one step backward, and lets make sure I understand your problem correctly.
You say that you have to find the "next greatest number with the same set of digits". So you are playing "Scrabble" with digits, trying to find the smalest number composed with the same digits that is strictly greater to the original number. For example, given the input "09", you would output "90", and for "123", you would output "132". Is that right? Let assume so.
Now, the real challenge here is how to determine the smalest number composed with thise digits that is stricly greater to the original number. Actually, there's a few possible strategies:
Enumerate all possible permutations of those digits, then filter out those that are not strictly greater to the original number, and then, among the remaining values, find the smallest value. That would be a very innefficient strategy, requiring both disproportionate memory and processing power. Please, don't consider this seriously (that is, unless you are actually coding for a Quantum Computer ;) ).
Set a variable to the initial number, then iteratively increment that variable by one until you eventually get a number that is composed of the same digits as the original values. That one might look simple to implement, but it actually hides some complexities (i.e. determining that two numbers are composed from the same digits is not trivial, special handling would be required to avoid endless loop if the initial number is actually the greatest value that can be formed with those digits). Anyway, this strategy would also be rather innefficient, requiring considerable processing power.
Iterate over the digits themselves, and determine exactly which digits have to be swapped/reordered to get the next number. This is actually very simple to implement (I just wrote it in less that 5 minutes), but require some thinking first. The algorithm is O(n log n), where n is the length of the number (in digits). Take a sheet of paper, write example numbers in columns, and try to understand the logic behind it. This is definitely the way to go.
All three strategies have one thing in common: they all require that you work (at some point at least) with digits rather than with the number itself. In the last strategy, you actually never need the actual value itself. You are simply playing Scrabble, with digits rather than letters.
So assuming you indeed want to implement strategy 3, here is what your main method might looks like (I wont expand more on this one, comments should be far enough):
public static void main(String[] args) {
// Read input number and parse it into an array of digit
String inputText = readLineFromUser();
int[] inputDigits = parseToDigits(inputText);
// Determine the next greater number
int[] outputDigits = findNextGreaterNumber(inputDigits);
// Output the resulting value
String outputText = joinDigits(outputDigits);
println(outputText);
}
So here's the point of all this discussion: the parseToDigits method takes a String and return an array of digits (I used int here to keep things simpler, but byte would actually have been enough). So basically, you want to take the characters of the input string, and convert that array to an array of integer, with each position in the output containing the value of the corresponding digit in the input. This can be written in various ways in Java, but I think the most simple would be with a simple for loop:
public static int[] parseToDigits(String input) {
char[] chars = input.toCharArray();
int[] digits = new int[chars.length];
for (int i = 0 ; i < chars.length ; i++)
digits[i] = Character.forDigit(chars[i], 10);
return digits;
}
Note that Character.forDigit(digit, radix) returns the value of character digit in base radix; if digit is not valid for the given base, forDigit returns 0. For simplicity, I'm skipping proper validation checking here. One could consider calling Character.isDigit(digit, radix) first to determine if a digit is acceptable, throwing an exception if it is not.
As to the opposite opperation, joinDigits, it would looks like:
public static String joinDigits(int[] digits) {
char[] chars = new char[digits.length];
for (int i = 0 ; i < digits.length ; i++)
chars[i] = Character.digit(digits[i], 10);
return new String(chars);
}
Hope that helps.
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.
OK so I am writing a program that compares the number entered by a user to a computer generated number. Each number is 3 digits. What I'd like to know how to do is compare these integers. So for example if the last two digits of the three digit numbers are the same it will run a block of code. I'm not completely sure how to go about this. Any youtube videos or any links would be much appreciated. I would rather understand than get an answer to my code.
The fastet way would be: Convert the Integer to a String and then split the string at each char. Then you have an Char Array with each digit and you can compare them like whatever you want.
int number = 324;
String number_string = String.valueOf(number); //converts integer to string
char[] digits = number_string.toCharArray(); //converts string to char array
if(digits[2] == 4){ //checks if 3rd digit of the char array is 4
//do something
}
You can get last two digit by modulo(%) operator.when you modulo three digit number by 100 it return last two digit and compare these digit in if condition like,
int num=154; //number of three digit
int rem=num%100;//modulo by 100 return remainder
if(rem==54){ //checking condition
//code
}
else{
//code
}
I suppose that the number entered is a String so first you want to convert it to an integer.
String value = .... <whatever read from the user>
int number = Integer.parseInt(value)
Then, if you like to get information on some of the digits, use modulus, ie:
number%10
will give you the most right integer (ie 127%10 is 7)
number%100
will give you 2 digits (ie 626%100 is 26)
I'm learning JAVA and recently I had the same problem with a few training tasks.
I have a some numbers and some of them are starting with 0. I found out that these numbers are octal which means it won't be the number I wanted or it gives me an error (because of the "8" or the "9" because they are not octal digits) after I read it as an int or long...
Until now I only had to work with two digit numbers like 14 or 05.
I treated them as Strings and converted them into numbers with a function that checks all of the String numbers and convert them to numbers like this
String numStr = "02";
if(numStr.startsWith("0")) {
int num = getNumericValue(numStr.charAt(1));
} else {
int num = Integer.parseInt(numStr);
}
Now I have an unkown lot of number with an unknown number of digits (so maybe more than 2). I know that if I want I can use a loop and .substring(), but there must be an easier way.
Is there any way to simply ignore the zeros somehow?
Edit:
Until now I always edited the numbers I had to work with to be Strings because I couldn't find an easier way to solve the problem. When I had 0010 27 09 I had to declare it like:
String[] numbers = {"0010", "27", "09"};
Because if I declare it like this:
int[] numbers = {0010, 27, 09};
numbers[0] will be 8 instead of 10 and numbers[2] will give me an error
Actually I don't want to work with Strings. What I actually want is to read numbers starting with zero as numbers (eg.: int or long) but I want them to be decimal. The problem is that I have a lot of number from a source. I copied them into the code and edited it to be a declaration of an array. But I don't want to edit them to be Strings just to delete the zeros and make them numbers again.
I'm not quite sure what you want to achieve. Do you want to be able to read an Integer, given as String in a 8-based format (Case 1)? Or do you want to read such a String and interpret it as 10-based though it is 8-based (Case 2)?
Or do you simply want to know how to create such an Integer without manually converting it (Case 3)?
Case 1:
String input = "0235";
// Cut the indicator 0
input = input.substring(1);
// Interpret the string as 8-based integer.
Integer number = Integer.parseInt(input, 8);
Case 2:
String input = "0235";
// Cut the indicator 0
input = input.substring(1);
// Interpret the string as 10-based integer (default).
Integer number = Integer.parseInt(input);
Case 3:
// Java interprets this as octal number
int octal = 0235;
// Java interprets this as hexadecimal number
int hexa = 0x235
// Java interprets this as decimal number
int decimal = 235
You can expand Case 1 to a intelligent method by reacting to the indicator:
public Integer convert(final String input) {
String hexaIndicator = input.substring(0, 2);
if (hexaIndicator.equals("0x")) {
return Integer.parseInt(input.substring(2), 16);
} else {
String octaIndicator = input.substring(0, 1);
if (octaIndicator.equals("0")) {
return Integer.parseInt(input.substring(1), 8);
} else {
return Integer.parseInt(input);
}
}
}
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.