I'm trying to find the high and low number in an array, but I'm not sure why my codes not working correctly. It's giving me the output of 0 and 56. I understand why it's giving the 0, but where did the 56 come from?
package test;
public class Test {
public static void main(String[] args) {
int[] numbs = { '2', '4', '2', '8', '4', '2', '5'};
int count = 0;
int low = 0;
int high = 0;
while(count < numbs.length)
{
if(numbs[count]< low) {
low = numbs[count];
}
if(numbs[count]> high) {
high = numbs[count];
}
count++;
}
System.out.println(low);
System.out.println(high);
}
}
You need to start the low low enough; currently, you start it at zero - too low to "catch" the lowest element of the array.
There are two ways to deal with this:
Use Integer.MAX_VALUE and Integer.MIN_VALUE to start the high and low, or
Use the initial element of the array to start both high and low, then process the array starting with the second element.
int low = Integer.MAX_VALUE;
int high = Integer.MIN_VALUE;
P.S. You would find strange numbers printed, because you used characters instead of integers:
int[] numbs = { 2, 4, 2, 8, 4, 2, 5};
Also.. It is probably printing the ASCII representation... use actual integers (I'm not sure if your usage of chars was intentional).
You use chars instead of ints at the array init block, this is immediately converted to ints to fit in the int[] array, but don't use its actual value, but the unicode value, where: 2 = 52 and 8 = 56.
'8' is char literal, not an int. The Java Language Specification defines char as follows:
The integral types are byte, short, int, and long [...] and char, whose values are 16-bit unsigned integers representing UTF-16 code units.
If you use a char where an int is expected, the char is implicitly converted to int. Since char is a numeric type, this will preserve its numeric value, i.e. its UTF-16 code point. The utf-16 code point of 8 is 56.
Treating char as a numeric type can be useful. For instance, we can compute the n-th letter of the alphabet by
char nthLetter = (char) `A` + n;
or find the numeric value of a digit by
if ('0' <= digit && digit <= '9')
return value = digit - '0';
else
throw new IllegalArgumentException(digit);
You should set both the low and high to the value in the first position of the array.
int low = numbs[0];
int high = numbs[0];
If the first position is indeed the lowest value it will never be swapped, otherwise it will be swapped with a lower number, the same happen to the highest number.
You want an array of ints that you should declared like such:
int[] numbs = {2, 4, 2, 8, 4, 2, 5};
You are getting 56 as the highest value because the decimal representation of the char '8' according to the ASCII table is 56.
Related
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." );
}
How to input an integer's binary expression into a bitSet in java?
say a = 15 I want put 1111 into a bitSet,
is there a function for this?
BitSet has a static valueOf(long[]) method which
Returns a new bit set containing all the bits in the given long array.
So an array with one long will have 64 bits, an array with two longs will have 128 bits, etc.
If you only need to get a BitSet from a single int value, use it like so
Integer value = 42;
System.out.println(Integer.toBinaryString(value));
BitSet bitSet = BitSet.valueOf(new long[] { value });
System.out.println(bitSet);
It prints
101010
{1, 3, 5}
In other words, from the right to left in the representation above, the 2nd, 4th, and 6th bit are set.
In java you can do this! = )
int value = 10; //0b1010
String bits = Integer.toBinaryString(value); //1010
BitSet bs = new BitSet(bits.length());
Then add the result to the bitset = )
for (int i = 0; i < bits.length(); i++) {
if (bits.charAt(i) == '1') {
bs.set(i);
} else {
bs.clear(i);
}
}
System.out.println(bs); //{0, 2} so 0th index and 2nd index are set.
My question seems very simple, but I've tried searching for a specific answer and have found none. I've found answers similar to what I've been looking for, but they've only managed to confuse me further:
All I want to do is add two character arrays and print the resulting array. The project deals with binary numbers, but I'll deal with base-2 arithmetic later, so just pretend they're base-10 numbers.
char[] array = {'1', '0', '0', '1'};
char[] array2 = {'1', '1', '0', '0'};
char[] sum = new char[4];
for(i=0; i < 4; i++){
sum[i] = char(array[i] + array2[i]);
System.out.print(sum[i] + " ");
}
My answer is "b''b" when I run it, so it seems some ASCII conversion is happening I guess? My expected answer should be "2101" and I realize the problem is in my casts, I just don't know how to proceed. Sum must remain a character array as part of the program's parameters.
EDIT: I KNOW using an int array for sum would solve this problem. As I stated in my original post, sum MUST remain a character array as part of the parameters of this project.
You can use Character.toString() to conver a char to String. Second, use Integer.parseInt() to convert a char to int. Then add those integers. Finally, use Character.forDigit(digit, 10) to convert the int (digit) to char.
char[] array = { '1', '0', '0', '1' };
char[] array2 = { '1', '1', '0', '0' };
char[] sum = new char[4];
for (int i = 0; i < 4; i++) {
sum[i] = Character.forDigit(
Integer.parseInt(Character.toString(array[i])) + Integer.parseInt(Character.toString(array2[i])),
10);
System.out.println(sum[i]);
}
Output:
2
1
0
1
Of course you can avoid this, if you use an array of integers:
int[] array = {1, 0, 0, 1};
Your assumption that ASCII math is coming into play is correct. char variables are glorified int variables under the hood. Adding char variables basically takes the ASCII decimal value, adds those values and then gives you the ASCII character representation. This is a bit over-simplified, but I wanted to give you an idea of why this is happening.
For example, if '1' is decimal 49 in ASCII, '1' + '1' = 49 + 49 = 98. 98 in ASCII is 'b'.
I'd suggest just switching the type of arrays you are using to be int:
int[] array = {1, 0, 0, 1};
int[] array2 = {1, 1, 0, 0};
int[] sum = new int[4];
for(int i = 0; i < 4; i++) {
sum[i] = array[i] + array2[i];
System.out.print(sum[i] + " ");
}
try to cast the character into int . something like
int i = Integer.parseInt(array[0] + "");
Similarly you can proceed for rest and then perform addition
If you want to add 1+1 and get 2 then don't use char array. Use int array, or cast it into int using
int i = Integer.parseInt(array[0] + "");
The problem is in your adding.
Basically, what you'll need to do is sum the first character, array[i] + (array2[i] - '0').
This is because with the first character, you're getting a correct ASCII-0-indexed value, but the second one should just be a number of steps from the ASCII 0-index, so "- '0'", will give you just the difference.
Try this. It works. Change this sum variable from char[] array to int[] array
public static void main(String[] args) {
char[] array = {'1', '0', '0', '1'};
char[] array2 = {'1', '1', '0', '0'};
int[] sum = new int[4];
for (int i = 0; i < 4; i++) {
sum[i] = Integer.parseInt(array[i] + "") + Integer.parseInt(array2[i] + "");
System.out.print(sum[i] + " ");
}
}
Output
run:
2 1 0 1 BUILD SUCCESSFUL (total time: 0 seconds)
Use int array instead of char array and store the result into your sum char array. But use int array as we'll for storing result. This will help you in dealing with numerical operation
I think this sounds like a question asked in interviews. The intention of the question is to add Integer characters from two arrays and output the result as an array of characters.
char[] a = { '4', '5', '6' };
char[] b = { '7', '8', '9' };
Integer c = Integer.parseInt(String.valueOf(a)) + Integer.parseInt(String.valueOf(b)); //456 + 789 = 1245
final char[] d = c.toString().toCharArray(); // d = {'1',2,'4','5'}
This solution handles all the cases where the sum can end up with a carry.
I created an array called numbers that will store values of a Fibonacci sequence. 1, 2, 3, 5, etc.
The problem is that when I try to call the array value at a very high index value, the array value becomes negative.
numbers[10] = 144
which is reasonable but
numbers[9999998] = -1448735941
Any help?
public static void main(String[] args) {
int[] numbers = new int[10000000];
numbers[0] = 1;
numbers[1] = 2;
for(int x = 2; x<=numbers.length-1; x++)
{
numbers[x] = numbers[x-1] + numbers[x-2];
}
System.out.println(numbers[9999998]);
System.out.println(numbers[10]);
Overflow. Once the value exceeds the maximum 'capacity' of the 32bit int, the result will wrap around and start from the minimum value (a negative).
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
long and BigInteger are able to store higher values than int.
You are experiencing integer overflow. Take a look at BigInteger for one workaround.
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 :)