Casting a specific element of an array - java - java

I have an array as:
String letters [] = {a, b, c, d, e};
Can I cast a specific element let's say "a" ? I want to get its ascii value, so I did this but it is not working:
for (int i = 0; i < letters.length; i++) {
Integer iDecimal = (int) a[0]; // the a[0] is wrong!!
System.out.print(iDecimal);
}
Any ideas about how to cast in such cases?

You are trying to cast a[0] which doesn't exist, to access your array you need to do letters[0] and then try working with it. I suggest changing type of your array to char and then casting it, you can't do that with String.

Declare the array as object array, but be aware that this is bad coding style, since you are mixing different types in one array.
Object letters [] = {5, "b", 'c'};
The object array contains an integer, a string, and a character you may then iterate over the array and test what object type you have.
The integer element is autoboxed to an Integer-Object.
But again i would not recommend doing so, since element testing is expensive.
for (int i = 0; i < letters.length; i++) {
if (a[i]) instanceof Integer)
Integer iDecimal = (Integer) a[i];
}

Assuming you want just the ASCII code for the first character in each string in your array, then you can can access that char then cast it to an int.
for (int i = 0; i < letters.length; i++) {
int iChar = (int) letters[i][0];
System.out.print(iChar);
}
letters[i] is the ith string in the letters array.
letters[i][0] is the first character of the ith string in the letters array, and will be of type char.
(int)letters[i][0] is the integer value equivalent to the first character of the ith string in the letters array.
Strictly this will give the first UTF-16 word in the string, but for values <127 it will be the same as the ASCII value.
ints are not decimal values, so don't call them decimals. The BigDecimal type is used for decimal values.

Related

Java type error between array element and charAt variable

I have created an integer array where the elements are the indexes of the characters of a string that I want to modify via reverse order.
For example,
string: text = "java is fun"
array: array = [0, 6, 8, 9]
Wanting to reverse the order the characters: 'j' 's' 'f' 'u'
Expected output = "uava if sjn"
I'm trying to use a for loop to run through array and modify the characters at that index, but there seems to be a type error, where text.charAt(array[j]) is expecting a variable but is receiving a value instead. unexpected type required: variable found: value
Is there another way to go about this?
Here is my code:
for (int j = 0; j < array.length/2; j++)
{
int el = array[j];
text.charAt(el) = text.charAt(array.length - j -1);
text.charAt(array.length - j -1) = el;
}
You cannot set a new value to a position with text.chatAt(i), with this you can only read values.
Take a look at text.toCharArray() and after changing with for loop String.copyValueOf(charArray)

Why can't I see the contents in Java char array neither in eclipse console nor in the debugger?

I not able to print char array to eclipse console or see the array contents while debugging in eclipse. I have written a program to return 1st non-repeating character index from a string using arrays. The program works & is very straightforward, but I find it very amusing that I cannot see the contents of the char array while I manipulate/debug the program. The SOP statement prints null OR \u0000. How can I see the actual contents of array 'a' in the below program ?
public static int getFirstNPCv2 (String s) {
char a[] = new char[26];
s=s.toLowerCase();
for (char c : s.toCharArray()){
a[c - 'a']++;
//System.out.println(a[c - 'a']);
}
System.out.println(a);
for (char c : s.toCharArray()){
if(a[c - 'a'] == 1){
return s.indexOf(c);
}
}
return -1;
}
getFirstNPCv2("titanic") returns 3 which is correct, but why can't I see the contents of array 'a'
This is because you don't hold any meaningful characters in your char array.
You are actually holding numbers in your char array. You created new char array and initial value of its elements is 0.
char a[] = new char[26];
Later on you will increment some elements of this array if they match index of character that is contained in your input string:
for (char c : s.toCharArray()){
a[c - 'a']++;
//System.out.println(a[c - 'a']);
}
Still, your char array doesn't hold any meaningful characters. It will have elements with values of 0,1,2,3... depending on your input string, and those values don't represent any readable letter or number. Still this doesn't prevent you from printing values stored in char array a. You can print them this way:
for(int i = 0; i<a.length; i++)
{
int b = a[i];
System.out.print(b);
}
I think for your approach you should have used array of int. Happy coding.
This is because you declared a as an array of characters and assign numeric values to each element.
In your case, all characters within the array have a value 0, 1 or 2.
These are non-printable characters.
Declare it as int a[] = new int[26];
Furthermore, instead of System.out.println(a), you should use System.out.println(Arrays.toString(a)).

converting char array of particular length into a string

i need to convert char array into string , the problem in doing this is......i need to convert the character in char array of particular length say k to string. ie, char array is "b" .b takes value dynamically.....for instance take as "p,a,p,e,r,s" now k value also dynamic ,for this word "k=5" ,and then only 4 characters in char array "b" should be converted into string...ie the string should print as "paper"........
the code what i have now is
for(int c=0;c<=k;c++)
{
System.out.print(b[c]);
}
str=new String(b);
System.out.println(str);
where b[c] prints correct value(in char array) as "paper". While converting to string str (in program) it prints as "papers" itself....can anyone give me solution for this?
You can use a different constructor of String that lets you specify the array along with the start point and number of characters to use.
In your case, you would try:
str = new String( b, 0, k );
char newArr[] = new char[k];
for (int i = 0; i < k; i++) {
newArr[i] = b[i];
System.out.print(b[i]); // print until the kth index
}
return new String(newArr);

(Java) Convert a string of numbers to an array of ints

I'm trying to convert a string filled with 16 digits into an array of ints where each index holds the digit of its respective index in the string. I'm writing a program where I need to do math on individual ints in the string, but all of the methods I've tried don't seem to work. I can't split by a character, either, because the user is inputting the number.
Here's what I have tried.
//Directly converting from char to int
//(returns different values like 49 instead of 1?)
//I also tried converting to an array of char, which worked,
//but then when I converted
//the array of char to an array of ints, it still gave me weird numbers.
for (int count = 0; count <=15; count++)
{
intArray[count] = UserInput.charAt(count);
}
//Converting the string to an int and then using division to grab each digit,
//but it throws the following error (perhaps it's too long?):
// "java.lang.NumberFormatException: For input string: "1234567890123456""
int varX = Integer.parseInt(UserInput);
int varY = 1;
for (count=0; count<=15; count++)
{
intArray[count]= (varX / varY * 10);
}
Any idea what I should do?
how about this:
for (int count = 0; count < userInput.length; ++count)
intArray[count] = userInput.charAt(count)-'0';
I think that the thing that is a bit confusing here is that ints and chars can be interpited as eachother. The int value for the character '1' is actually 49.
Here is a solution:
for (int i = 0; i < 16; i++) {
intArray[i] = Integer.valueOf(userInput.substring(i, i + 1));
}
The substring method returns a part of the string as another string, not a character, and this can be parsed to an int.
Some tips:
I changed <= 15 to < 16. This is the convetion and will tell you how many loop interations you will actually go throug (16)
I changed "count" to "i". Another convention...

Casting an array of chars to ints on a hashtable

This is a question regarding casting of types in Java.
public int hashFunction(String D){
char[] Thing = D.toCharArray();
for(int i=0; i < Thing.length; i++){
index =+(int)Thing.length;
}
return index % tablesize;
}
Now how does the code work such that each content of the char array is now cast to a type int?
Java will allow you to assign chars to ints, since int has a larger domain than char. This is known as widening:
char c = 'a';
int i = c; // compiles just fine
You probably want to access each element in Thing, right? Use an enhanced for loop:
for(char c : Thing) {
// do something with c
}

Categories

Resources