Double int conversion messup - java

I have no idea of why this code snippet produces the following output when I try to multiply 2 int values. This might be too dumb but I just dont get it. I have pasted the code and the output here
public static void main(String[] args) {
// TODO code application logic here
String numstring = "12122";
char[] numArray = numstring.toCharArray();
int num =0;
int index = 10;
int count = 0;
for(int i=numArray.length-1;i>=0;i--){
int ind = (int)(Math.pow(index,count));
System.out.print(numArray[i]+"*"+ind);
System.out.println(" prints as ----->"+numArray[i]*ind);
count++;
}
}
output:
2*1 prints as ----->50
2*10 prints as ----->500
1*100 prints as ----->4900
2*1000 prints as ----->50000
1*10000 prints as ----->490000

You're not multiplying two ints. Your multiply an int, ind, with a char, '2', whose ASCII value is 50 (at least in the first case). You could use an int[], or if you want to stick with the char[], you could do the following:
System.out.println(" prints as ----->"+ Character.getNumericValue(numArray[i]) * ind);

Characters are really integers under the hood, so for example, the character '2' has int value 50.
To see which integer corresponds to which character, check out the ascii table.
To do what you want, you should use Character.getNumericValue() method:
System.out.println(" prints as ----->"+Character.getNumericValue(numArray[i])*ind);

Related

How do you get the numerical value from a string of digits?

I need to add certain parts of the numerical string.
for example like.
036000291453
I want to add the numbers in the odd numbered position so like
0+6+0+2+1+5 and have that equal 14.
I tried the charAt(0)+charAt(2) etc, but it returns the digit at those characters instead of adding them. Thanks for your help.
Use charAt to get to get the char (ASCII) value, and then transform it into the corresponding int value with charAt(i) - '0'. '0' will become 0, '1' will become 1, etc.
Note that this will also transform characters that are not numbers without giving you any errors, thus Character.getNumericValue(charAt(i)) should be a safer alternative.
String s = "036000291453";
int total = 0;
for(int i=0; i<s.length(); i+=2) {
total = total + Character.getNumericValue(s.charAt(i));
}
System.out.println(total);
You can use Character.digit() method
public static void main(String[] args) {
String s = "036000291453";
int value = Character.digit(s.charAt(1), 10);
System.out.println(value);
}
Below code loops through any number that is a String and prints out the sum of the odd numbers at the end
String number = "036000291453";
int sum = 0;
for (int i = 0; i < number.length(); i += 2) {
sum += Character.getNumericValue(number.charAt(i));
}
System.out.println("The sum of odd integers in this number is: " + sum);
I tried the charAt(0)+charAt(2) etc, but it returns the digit at those
characters instead of adding them.
Character.getNumericValue(string.charAt(0));

Java error: char cannot be dereferenced

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." );
}

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

Multiply array by java

I was curious how to muliply an array by a factor? Not each cell (t[0], t[1], etc) individually, but as a whole number. Ex: t[0] = 9 t[1] =2 t[2] = 5, t[] = 925. 925 times 3 =2775
Basically, I am receiving a value and converting from ASCII to Decimal(I have already done this). However, I want to multiply by it a factor of 3. Do I need to store the entire array as a string, and then use the multiply function?
The relevant code for this section
byte[] readBuf =(byte[]) msg.obj);
char x;
String readMessage = newString(readBuf,0,msg.arg1);
int[] t = new int[readMessage.length()];
for(int i = 0; i<readMessage.length(); i++)
{
x = readMessage.charAt(i);
int z = (int) x;//Array has been converted from ASCII into decimal values
t[i] = z;//Array has been populated with decimal values
//Confused about the next part, Convert back into string and then multiply string?
}
Why make extra variables for char and int, use space for tables and pass things from one variable to another when you can do it all in one line? From what i've understood this is all you need.
byte[] readBuf =(byte[]) msg.obj);
String readMessage = newString(readBuf,0,msg.arg1); //You create the string here
String final=""; //new string to be parsed
for(int i = 0; i<readMessage.length(); i++){
final+=""+(int)readMessage.charAt(i); // get the charAt(i) cast it to int and give it to the string
}
return Integer.parseInt(final)*factor; //return the int multiplied by 3
Edit: Use Double.parseDouble(readMessage) to convert it to decimal
ASCII characters are only Integer numbers
I'm not sure if I understand the format of your input string. Does this example solve your problems?
public static void main(String args[]) throws Exception {
String input = "925";
int parsed = Integer.parseInt(input);
parsed *= 3;
System.out.println(parsed); // prints 2775
}
Your ask is not clear, I try to understand: you have a String in an array where the zero index is the most significative position and the last is the less significative position. So, if you have 123, the situation is t[0]=1, t[1]=2, t[2]=3.
If it's correct, then you say you want to rebuild the number (in my example 123 and return that multiplyed by a factor, i.e. 3). So return 369.
Here's my solution assuming that the resulting number will be lower than MAXINT.
I also mantain your code as is, and return the result multiplyed by a factor in value "factor" (int).
byte[] readBuf =(byte[]) msg.obj);
char x;
String readMessage = newString(readBuf,0,msg.arg1);
int[] t = new int[readMessage.length()];
String final="";
for(int i = 0; i<readMessage.length(); i++)
{
x = readMessage.charAt(i);
int z = (int) x;//Array has been converted from ASCII into decimal values
t[i] = z;//Array has been populated with decimal values
final+=""+t[i]; // add to String the char in position i.
//Confused about the next part, Convert back into string and then multiply string?
}
return Integer.parseInt(final)*factor;

(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