Java error: char cannot be dereferenced - java

Here is what the teacher asked me to do:
Enter a phone number (set up a string-type object for the phone number)
example:
(703) 323-3000
Display the phone number, using a format like the following:
Example 1:
The phone number you entered is 703-323-3000.
Display the content of the array that holds the count for each digit in the string. Use a format similar to the following:
Example:
Digit 0 showed up 4 times.
Digit 1 showed up 0 times.
Digit 2 showed up 1 times.
Digit 3 showed up 4 times.
Digit 4 showed up 0 times.
Digit 5 showed up 0 times.
Digit 6 showed up 0 times.
Digit 7 showed up 1 times.
Digit 8 showed up 0 times.
Digit 9 showed up 0 times
The teacher also provided us with an algorithm as a hint:
set up an integer array of size 10
initialize each element to zero
input string of phone number
set SIZE = length of the string
set up a loop to iterate SIZE times
{
get next character
update array appropriately
(for example: if the character is '7' then increment array[7] by 1.
}
Display BOTH using appropriate messages:
the original phone number
contents of the array (using a loop).
Here is My code but it shows the error I mentioned when i use the equals() method, and displays a wrong answer if i use ==. Please Help.
public class Phones
{
public static void main(String[] args)
{
int Num[] = {0,0,0,0,0,0,0,0,0,0};
String Phone = "703-323-3000";
int SIZE = Phone.length() - 1;
for(int count=0; count<= SIZE; count++)
{
for(int counter = 0; counter <= SIZE; counter++)
{
if(Phone.charAt(counter).equals(count))
Num[count]++;
}
System.out.println("Digit " + count + " showed up " + Num[count] + " times");
}
}
}
This is my first time on this site, so sorry in advance if this is too long or incomprehensible. Thank you.

The reason you get the wrong answer with == is that you're comparing a char with an int incorrectly. In short, you're comparing counter with the unicode value of the characters, rather than with the number that the character represents. (For "normal" characters like letters, numbers and simple punctuation, the unicode values are the same as the ASCII values.)
The char '0' does not have an int value 0 -- it has the unicode value for the char 0, which is 0x0030 (aka 48 in base 10 -- the 0x format shows it in hex). By comparing the char the way you're doing, the first comparison will only be true if the char is the so-called "null char" 0x0000 (not to be confused with null, which is a null reference!), which won't happen for any sort of "normal" input.
Instead, you need a way to compare chars with ints. The easiest way to do this is to subtract the '0' char's value from the current char:
int charDistanceFromZero = Phone.charAt(counter) - '0';
If that distance is less than 0 or greater than 9, you have a char that's not a number. Otherwise, charDistanceFromZero is the offset you need into the array.
This works because the characters for the number digits start at 0 and are sequential from there. Try computing charDistanceFromZero for a few of them to get a feel for how it works out for getting the array index.

charAt will return a value of type char, which is the reason why you cannot do .equals(...).
Also, the characters representing the digits are in ['0' .. '9'], which isn't the same as the interval [0 .. 9]. You need to translate the range by subtracting '0'.

The reason for your error is that charAt returns a char, which is a primitive type. You need to have an object, not a primitive, in order to be able to call a method, such as .equals. Moreover, when you tried to use == in place of .equals, you were comparing a char to an int value. It's all right to do this, so long as you remember that the int value of a character is its encoded value, so 48 for '0', 49 for '1' and so on.
To solve this problem, it's best to use the methods that come for free in Java's Character class; notably isDigit, which determines whether a character is a digit, and getNumericValue, which converts a character to the number that it represents.
It's also possible to dispense with the outer loop entirely, since once you've converted each digit character to its numeric value, you already have the index in the array that you want to increment. So here is a much cleaner solution, that does not use nested loops at all.
public class Phones{
public static void main(String[] args){
int counters[] = new int[10];
String phone = "703-323-3000";
for (char eachCharacter : phone.toCharArray()) {
if (Character.isDigit(eachCharacter)) {
int digit = Character.getNumericValue(eachCharacter);
counters[digit]++;
}
}
for(int digit = 0; digit < 10; digit++) {
if (counters[digit] != 0) {
System.out.format("Digit %d showed up %d times.%n", digit, counters[digit]);
}
}
}
}
Here, the first loop traverses your input string, incrementing the array index corresponding to each digit in the string. The second loop just prints out the counts that it's found.

Other answers are fine... But to reduce ambiguity in code I generally just send the string into a char array before doing any control flows... And as noted, 'Zero' is at Unicode Code Point 48 so you need to subtract that value from the character index.
char[] number = "212-555-1212".toCharArray();
for(int i = 0; i < numbers.length; i++) {
// do something groovy with numbers[i] - 48
}
So for this solution you might do something like this....
String phone = "212-555-1212".replaceAll( "[^\\d]", "" );
int[] nums = new int[phone.length()];
int[] queue = new int[phone.length()];
for(int i = 0; i < nums.length; i++) {
nums[i] = phone.toCharArray()[i] - 48;
for(int num : nums) {
if( nums[i] == num ) {
queue[i] += 1;
}
}
System.out.println( "Number: " + nums[i] + " Appeared: " + queue[i] + " times." );
}

Related

Count of random numbers from a string java

This is a homework problem with a rule that we cant use arrays.
I have to make a program that will generate ten random numbers , append it to a string with a comma after each number.
I then have to give a count of each random number and remove the highest frequency number from the string.
The only issue i cannot solve is how to give a count of each number.
Lets say the string is "1,1,2,4,5,6,6,2,1,1" or "1124566211" with the commas removed.
How can I go about an output something like
1 = 4
2 = 2
4 = 1
5 = 1
6 = 2
Removing all numbers of max frequency
245662
Where the left side is the number and the right is the count.
EDIT: Range is 1 between 10, exclusing 10. It is testing the frequency of each digit i.e. how many times does 1 appear, how many times does 2 appear etc. Also its due tonight and my prof doesnt answer that fast :/
I would use a HashMap. A string representation of the num will be used as the key and you will have an Integer value representing the frequency it occurs.
Loop through the string of nums and put them to the HashMap, if the num already exists in the map, update the value to be the (current value + 1).
Then you can iterate through this map and keep track of the current max, at the end of this process you can find out which nums appear most frequently.
Note: HashMap uses Arrays under the covers, so clarify with your teacher if this is acceptable...
Start with an empty string and append as you go, check frequency with regex. IDK what else to tell you. But yeah, considering that a string is pretty much just an array of characters it's kinda dumb.
You can first say that the most common integer is 0, then compare it with the others one by one, replacing the oldest one with the newest one if it written more times, finally you just rewritte the string without the most written number.
Not the most efficient and clean method, but it works as an example!
String Text = "1124566211"; // Here you define the string to check
int maxNumber = 0;
int maxNumberQuantity = 0; // You define the counters for the digit and the amount of times repeated
//You define the loop and check for every integer from 0 to 9
int textLength = Text.length();
for(int i = 0; i < 10; i ++) {
int localQuantity = 0; //You define the amount of times the current digit is written
for(int ii = 0; ii < textLength; ii ++) {
if(Text.substring(ii, ii+1).equals(String.valueOf(i)))
localQuantity ++;
}
//If it is bigger than the previous one you replace it
//Note that if there are two or more digits with the same amount it will just take the smallest one
if(localQuantity > maxNumberQuantity) {
maxNumber = i;
maxNumberQuantity = localQuantity;
}
}
//Then you create the new text without the most written character
String NewText = "";
for(int i = 0; i < textLength; i ++) {
if(!Text.substring(i,i+1).equals(String.valueOf(maxNumber))) {
NewText += Text.charAt(i);
}
}
//You print it
System.out.println(NewText);
This should help to give you a count for each char. I typed it quickly off the top of my head, but hopefully it at least conveys the concept. Keep in mind that, at this point, it is loosely typed and definately not OO. In fact, it is little more than pseudo. This was done intentionally. As you convert to proper Java, I am hoping that you will be able to get a grasp of what is happening. Otherwise, there is no point in the assignment.
function findFrequencyOfChars(str){
for (i=0; i<str; i++){
// Start by looping through each char. On each pass a different char is
// assigned to lettetA
letterA = str.charAt(i);
freq = -1;
for (j=0; j<str; j++){
// For each iteration of outer loop, this loops through each char,
// assigns it to letterB, and compares it to current value of
// letterA.
letterB = str.charAt(j);
if(letterA === letterB){
freq++
}
}
System.Out.PrintLn("the letter " + letterA + " occurs " + freq +" times in your string.")
}
}

Swap numbers in a string

I've the below program.
public class swapping {
public static void main(String[] args) {
String num = "31254";
int max = Integer.MIN_VALUE, maxIndex = 0;
for (int i = 0; i < num.length(); i++) {
if (num.charAt(i) > max) {
max = num.charAt(i);
maxIndex = i;
}
}
swap(num, num.charAt(0), maxIndex);
}
private static void swap(String num, char charAt, int maxIndex) {
System.out.println("number is " + num + " Initial char is " + charAt
+ " Maximum is " + maxIndex);
char t = charAt;
char s = num.charAt(maxIndex);
System.out.println("numbers:" + t + " " + s);
char temp = t;
t = s;
s = temp;
System.out.println("Final string after swap is " + num);
}
}
here my aim is to get the maximum number in the string to be swapped with the first number in the string. i.e. I want to convert 31254 to 51234. But i'm unable to know how to do this.
number is 31254 Initial char is 3 Maximum is 3
numbers:3 5
Final string after swap is 31254
Here the swapping is not getting done, the previous number is getting printed. please let me know how to print the desired output.
Thanks
Pay attention what you are passing to the method.
You are passing the actual character in the first and max position: 3 and 5 in this case.
But then, after you print them, you call:
char t = num.charAt(initial);
char s = num.charAt(max);
charAt expects the index of the character in the string. The index should be an integer, but you are passing it a char value (the character 3 and the character 5).
Now, in Java, characters are considered numbers between 0 and 65535 - the unicode value of the character. So it allows you to pass a character where you should have passed an integer. The unicode value of 3 is 51, and for 5 it's 53. So you are actually telling it "give me the character in the string num which is in position 51".
This is not what you intended.
Instead of doing that, you should make the method accept the index of the first character and the index of the max character. Then, using charAt will be correct. But pay attention to also use charAt for your print at the beginning.
private static void swap(String num, int initialIndex, int maxIndex) {
...
}
Your other problem is that you are not actually swapping the characters inside the string.
What you did was swap the variables that contain the two characters, t and s. So now t contains what s contained, and s contains what t contained.
However, this has no bearing on the original string num. You have not done anything with the string itself.
One thing to remember is that in Java, you cannot change a string. It's immutable. If you have a string object, Java doesn't give you any way to change things inside it. It only lets you read parts of it, not write.
What you can do is assign a new string value to num. In this new string, you will put the value of the max character in the 0 position, and put the value of what was in the first position, in the max character position. And you'll copy all the other characters in the same positions where they were.
So you'll need to create a temporary string, loop on the original string character by character, and in each position, ask yourself "what character should I add to my new string at this round?". And then add that character to the string with a + operator.
Finally, assign the new, temporary string to num.
(Note: there are more efficient ways to do this in Java, like using a StringBuffer or StringBuilder, but I get the impression that you are not there yet in your studies of Java).
try the below program.
String num = "31254";
int maxIndex = 0;
char maxString = num.charAt(0);
for (int i = 1; i < num.length(); i++) {
if (num.charAt(i) > maxString) {
maxString = num.charAt(i);
maxIndex = i;
}
}
System.out.println(maxString);
System.out.println(maxIndex);
String str1 = num.substring(1,maxIndex);
String str2 = num.substring(maxIndex+1,num.length());
String str3 = num.charAt(maxIndex)+str1+num.charAt(0)+str2;
System.out.println(str3);
Initial is a char. charAt use an integer, so the char will converted in the acii code of 3 wich is 51. So your line is equals to `num.charAt(51) and that is out of range.
So hyou have to change the signature of your mathod to private static void swap(String num, int initial, int max)
Here's how I would do it in just 3 lines. Note that for digits, chars are 1 byte each.
byte[] array = number.getBytes();
Arrays.sort(array);
number = number.replaceFirst("(.)(.*?)(" + (array[array.length - 1] - '0') + ")", "$3$2$1");
Not only is this code quite terse - using regex to perform the swap in one statement - it also automatically handles the edge case of the largest digit being at the start (in which case no match/replacement will be made).
Here's some test code:
String number = "31254";
byte[] array = number.getBytes();
Arrays.sort(array);
number = number.replaceFirst("(.)(.*?)(" + (array[array.length - 1] - '0') + ")", "$3$2$1");
System.out.println(number);
Output:
51234

Comparing array element to zero?

Alright, so my goal is to complete the following assignment:
"Design and implement an application that determines and prints the number of odd, even, and zero digits in an integer value read from the keyboard.
SPECIFICATION OF PROMPTS, LABELS AND OUTPUT : Your code should not have any prompt at all. The input to this program is a single integer . After the integer is read, the output consists of three lines. The first line consists of the number of odd digits in the integer followed by the label "odd digits". The second line consists of the number of even digits in the integer followed by the label "even digits". The third line consists of the number of zero digits in the integer followed by the label "zero digits". For example, if 173048 were read in, the output would be:
3 odd digits
3 even digits
1 zero digits
SPECIFICATION OF NAMES: Your application class should be called DigitAnalyst"
And the code I have produced is:
import java.util.Scanner;
public class DigitAnalyst{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String num = scan.next();
int odd_count = 0;
int even_count = 0;
int zero_count = 0;
//input an int as a string, and set counter variables
int[] num_array = new int[num.length()];
//ready a array so we can so we can parse it sanely
for (int i =0; i < num.length(); i++)
{
num_array[i] = num.charAt(i);
}//fill the array with the values in the initial number using a loop
for ( int i=0;i< num_array.length; i++)
{
if (num_array[i] % 2 ==0)
{
if (num_array[i] ==0 )//the hell is going on here?
{
zero_count++;
}
else if (num_array[i] != 0)
{
even_count++;
}
}
else if (num_array[i] % 2 != 0)
{
odd_count++;
}
}//use this loop to check each part of the array
System.out.println(odd_count+ " odd digits");
System.out.println(even_count+" even digits");
System.out.println(zero_count+" zero digits");
}
}
And yet I keep getting the wrong output. More specifically, it returns the correct amount of odd numbers but it keeps counting 0 as an even and not as a zero.
I know where the problem is but I have no idea what is wrong, and I've spent a few hours on this.
If someone could point me in the right direction I'd be ectstatic.
When you encounter a problem that involves the manipulation of digits in an integer, the standard approach is to use an actual integer and the operator %, rather than strings. Instead of scan.next() use
int num = scan.nextInt();
And then you can do this:
do {
int digit = num % 10;
if ( digit == 0 ) {
zero_count ++;
} else if ( digit % 2 == 0 ) {
even_count ++;
} else {
odd_count ++;
}
num /= 10;
} while ( num > 0 );
The idea is that when you divide a number by 10, the remainder is exactly the rightmost digit, and the quotient will have all the other digits. That's simply how the decimal system works.
In this method you get the digit directly without calling any method, and you don't need any arrays.
If you assign the integer element with num.charAt(i) the ASCII value of the character is assigned and you get wrong results. In order to fix this, change
num_array[i] = num.charAt(i);
to
num_array[i] = Integer.parseInt(String.valueOf(num.charAt(i)));
or similar.
I'll give you some help here. First, charAt() returns the character at the index in the string, as a char data type. You're storing in an array of ints, which is assuming the numerical value of the character in the set, not the actual value.
Try this instead...
Change:
int[] num_array = new int[num.length()];
to:
char[] num_array = new char[num.length()];
and wrap all your num_array[i] references in your conditionals with:
Character.getNumericValue(num_array[i])
You should get your expected results.
Input = 12340
Output =
2 odd digits
2 even digits
1 zero digits

how to find most occurring digit of number

How to find most popular digit inside the number. for example I have number 222244, the most occurring digit is 2. Please help.
I have something like this, but don't really understand this first part of method, what is going on with int j = liczba.charAt(i) - 47; why 47 is here? anyone can explain it?
int digits[] = new int [10];
for(int i = 0; i <liczba.length(); i++){
int j = liczba.charAt(i) - 47;
digits[j]++;
}
int digit = 0;
int count = digits[0];
for(int i=1;i <10; i++){
if(digits[i] >count){
count = digits[i];
digit = i;
}
}
return digit;
The line
int j = liczba.charAt(i) - 47;
Subtracts the character code of (i+1)th character liczba by 47. Refering to an ASCII table, 47 maps to "/", whose ASCII code is one less than "0".
Note that I am assuming the following, as your code appears to be in Java.
String indexes starts at zero i.e. first character has index 0, second character has index 1, and so on
It seems that characters and integers can be used interchangeably, because a character is internally represented by an integer, namely, the ASCII code of the character.
That said, the char type is actually an integer type, with less range
Hence, this code is to turn characters "0" to the integer 1, "1" to the integer 2, etc.
For example, when the 1st character (liczba.charAt(0)) is the character 0, liczba.charAt(0) returns character '0', which is also equals to number 48 -- because '0' has an ASCII code of 48.
Subtracts 48 with 47 gets 1, so it would convert character '0' to integer 1.
However it seems that this code could cause array index out of bounds error (assuming zero-based array indexes). when a digit is '9', this line returns 10. This would cause an aforementioned error. Unless this code's language's array are 1-based. However, even in this case, this line
int count = digits[0];
would simply fail. This code seems to fail with the common Off by one error
I believe this line should actually read
int j = liczba.charAt(i) - 48;
so that character '0' is converted to number 0.
If this still disturb you, you may change this line to
int j = liczba.charAt(i) - '0';
so it would be clearer. Subtract the code of '1' and the code of '0' gets you the integer 1, clear enough :)

(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...

Categories

Resources