Comparing array element to zero? - java

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

Related

Problem in code and need a short code to solve problem

fist thing first , the code :
package com.company;
import java.util.Scanner;
public class index {
public static void main (String[] args)
{
System.out.println("enter any three digit number ");
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
//let a= 2 7 4
int b= a%10;//4
int c=a/10;//27
int d= c%10;//7
int e=c/10;//2
//e=first num;
//d=middle num;
//b= last num ;
// for searching the greatest number
if (d>e && d>b )
System.out.printf(" the greatest number is %d%d%d",d,e,b);
else if(e>d && e>b )
System.out.printf(" the greatest number is %d%d%d",e,d,b);
else if (b>e && b>d )
System.out.printf(" the greatest number is %d%d%d",b,e,d);
// for the smallest number
else if(d<e && d<b && b>e)
System.out.printf(" the smallest number is %d%d%d",b,e,d);
else if(d<e && d<b && e>b)
System.out.printf(" the smallest number is %d%d%d",e,b,d);
else if (e<d && e<b && b>d)
System.out.printf(" the smallest number is %d%d%d",b,d,e);
else if(e<d && e<b && d>b)
System.out.printf(" the smallest number is %d%d%d",d,b,e);
else if (b<e && b<d && e>d)
System.out.printf(" the smallest number is %d%d%d",e,d,b);
else
System.out.printf(" the smallest number is %d%d%d",d,e,b);
}
}
now the problem:
this code is make to take number from the user as the input **of any three digit number ** and change it to the greatest number and smallest number ,
for example:
input number =274
output :
greatest number=742
smallest number=247
the above code is giving the greatest number but not the smallest number and the code is very lengthy ,
my output:
enter any three digit number
546
the greatest number is 654
so please help ,any error in code and if there is any short code then please help
I think that the problem is in the way of solution. As for me that is better to use some array or list and sort it. Something like that
public static void main (String[] args)
{
System.out.println("enter any three digit number ");
Scanner sc=new Scanner(System.in);
int a=sc.nextInt();
int[] array = new int[3];
for (int i = 0; i < 3; i++) {
array[i] = a % 10;
a = a / 10;
}
Arrays.sort(array);
int smallest = 0;
int greatest = 0;
for (int i = 0; i < 3; i++) {
smallest += array[i];
if (i != 2) {
smallest *= 10;
}
}
for (int i = 2; i > -1; i--) {
greatest += array[i];
if (i != 0) {
greatest *= 10;
}
}
System.out.println(Arrays.toString(array));
System.out.println(smallest);
System.out.println(greatest);
}
May I suggest a whole different approach?
void printGreatestAndSmallest(int number) {
char[] digits = String.valueOf(number).toCharArray();
Arrays.sort(digits);
String smallest = new String(digits);
String greatest = new StringBuilder(smallest).reverse().toString();
System.out.println("Greatest number is " + greatest);
System.out.println("Smallest number is " + smallest);
}
What happens here, is that we convert the digits to a char[], which can be sorted using Arrays.sort(...). This way, the smallest digit comes in front, the largest at the end. The char[] is converted back to a string with the String(char[]) constructor.
That is the smallest value. The largest value is the reverse of it! We can get the largest number using StringBuilder's reverse() method.
Note that this code cannot handle negative numbers.
The problem with your current approach is that it contains a lot of repetitions, and is not quite flexible; it is bound to an input of exactly three digits.
In order to fix the issue your are facing, remove the else keyword from the line else if(d<e && d<b && b>e). Each if-elseif-else statement only executes a single branch, but you need two branches to be executed, one for the smallest number, and one for the greatest number.
Further:
Use descriptive variable names. You have a comment in your code:
//e=first num;
//d=middle num;
//b= last num ;
but why don't you rename e, d and b to firstDigit, middleDigit and lastDigit respectively?
Follow the Java Naming Conventions. Variable and method names are written in camelCase, and class names in PascalCase. So class index should be class Index. Also make sure to rename index.java to Index.java.
You are defining variables with almost the same function: in your case firstNum, middleNum and lastNum. They all allow to store a specific digit of the input number. In such a case, you should use an array instead of separate variables. Loops work well with arrays.
If your code somehow iterates over all possible permutations of some collection, using if-else statements, that is probably not the best way.
For example:
if (d>e && d>b )
else if(e>d && e>b )
else if (b>e && b>d )
You should ask yourself: should these digits be in a certain order? The answer here is yes, they need to be sorted from low to high (and high to low). In that case, you probably want to sort them.

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

Converting multiple strings into one then parsing to int

I know this is not the simplest way to find a palindrome...but I was hoping someone might tell me if there is a way to convert multiple strings of integers into a single int. Maybe that builds a single string from others? Below I have an output that reverses the number you input. However, it comes out as a string of separate integers. Would I be able to typecast this into a single int then bool it against the original number somehow?
If I overlooked a topic similar to this, I'm sorry. I checked around and didn't find one that clearly solved my issue.
import java.util.Scanner;
public class Palindrone{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 2 and 6 digits:");
int num1 = input.nextInt();
int rev = 0;
//find last number
if(num1 >= 10){
rev = num1%10;
System.out.print(rev);
}
//find 2nd to last and 3rd from last
if(num1 >= 100){
rev = num1%100/10;
System.out.print(rev);
rev = num1%1000/100;
System.out.print(rev);
}
//find 4th from last
if(num1 >= 1000){
rev = num1%10000/1000;
System.out.print(rev);
}
//find 5th
if(num1 >= 10000){
rev = num1%100000/10000;
System.out.print(rev);
}
//find 6th
if(num1 >= 100000){
rev = num1%1000000/100000;
System.out.print(rev);
}
}
}
I'm trying to go from printing string (int rev)(int rev)(int rev)(int rev) to
one solid string then converting to int. Then if(newInt == num1) run statement.
You could go this way without the headache of string-int conversion:
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 2 and 6 digits: ");
String number = input.next();
System.out.println(new StringBuilder(number).reverse()); //prints reverse number
Easy, the following method uses Guava to perform the various steps:
public static boolean palindrome(int number) {
// Split into an array of digits and reverse
List<String> digits = Lists.transform(
Lists.reverse(
Lists.transform(
Lists.transform(
Lists.charactersOf(Integer.toString(number)),
Functions.toStringFunction()),
Ints.stringConverter())),
Ints.stringConverter().reverse());
// Join the strings and parse to an integer
int result = Integer.parseInt(Joiner.on("").join(digits));
// And check if a palindrome
return (result == number);
}
So, you could use the same technique with your code, if you create an empty list at the beginning, and add each parsed integer to the end of the list. However the way you are using the modulus operator with the fixed sequence of numbers multiplying by 10 each time is limiting. Instead, if you want to use this parsing method, consider a loop instead:
List<Integer> digits = Lists.newArrayList();
while (number > 10) {
int digit = number % 10;
digits.add(digit);
number /= 10;
}
Then reverse and transform back to a list of strings, and convert to an integer:
List<String> strings = Lists.transform(
Lists.reverse(digits),
Ints.stringConverter().reverse());
int result = Integer.parseInt(Joiner.on("").join(strings));
And again just check for equality with the original number.

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

How do I update the integer while the loop is running?

When we enter 0 in the program it is supposed to stop running the loop and print the average of the numbers. When I run the program and initially enter 0, the program exits. If I enter in an integer that is not zero first, and then enter 0, the program keeps running and I can't quit.I figure that the integer value needs to update when the user enters a new value for the program to quit, and the sum to be correct.
How do I update the integer value while the loop is running? I should change or add something in the loop I'm guessing.
import java.util.Scanner;
public class Exercise05_01 {
public static void main(String[] args){
float negCount = 0;
float sum = 0;
float posCount = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a positive or negative integer. Entering 0 ends program");
int integer = input.nextInt();
while (integer != 0) {
if (integer > 0) {
posCount = +1;
sum = +integer;
}
if (integer < 0) {
negCount = +1;
sum = +integer;
}
float count = negCount + posCount;
if (integer == 0) {
System.out.println("The answer");
}
}
}
}
There are two problems.
First, you don't get any input while you're in the loop. That's fixable with a suggestion provided earlier by Lunchbox.
Second, this is not accumulating the value:
posCount = +1;
That assigns a positive 1 to posCount every time.
You want to either increment the value...
posCount++;
...or add one explicitly.
posCount += 1;
I think you need to add the line that gets input in your while loop.
while (integer != 0) {
integer = input.nextInt();
.
.
.
This way while the loop is running, every iteration it will check for an input still.
Also I have to say this looks suspiciously like homework... especially the class name...
As Lunchbox points out in his answer, you need to request input from the user from inside your loop, otherwise integer never changes and you never exit your loop; the behaviour you're observing is the program running forever.
The best way to do this is Lunchbox's suggestion:
int integer = input.nextInt();
while(integer != 0){
// Do stuff
integer = input.nextInt();
}
However, you have many other problems with your code. For one thing, why are you using floats to store your counters and sum values? Why not use ints?
For another, you're never actually incrementing those values. As Makoto points out in his answer, the line posCount = +1 is not an increment operator.
In that case, the + operator is the unary plus operator. What this will do is force your signed value to be positive, so +(-1) == 1. While this is useful, it's not what you want to happen, and it's definitely not what you want to be doing around your sum.
Instead, you want to do one of the following three things:
posCount = posCount + 1;
posCount += 1;
posCount++;
Those are all equivalent statements. The ++ operator is the postfix increment operator, which will add 1 to the value of the variable and then return it (It's slightly more complicated than that, but you can read that on your own time). So don't use that syntax for your sum; use one of the other two.

Categories

Resources