Count the number of occurrences of all the digits in the string - java

My task is write a program to take string as input(only numbers) and for each digit starting from 0 to 9, print the count of their occurrences in the string.
I have completed it. I have declared 10 integers with zero. Each integer will count the corresponding integers. But in the last when I am printing the result it is giving me the result as 48+count
Count represents the number of count of values occurrences.
For the correct result I need to subtract 48. I am unable to understand why I am getting value.
class TestClass {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int a='0',b='0',c='0',d='0',e='0',f='0',g='0',h='0',i='0',j='0';
String s=sc.next();
OUTER:
for (int k = 0; k<s.length(); k++) {
char ch=s.charAt(k);
switch (ch) {
case '0':
a++;
break;
case '1':
b++;
break;
case '2':
c++;
break;
case '3':
d++;
break;
case '4':
e++;
break;
case '5':
f++;
break;
case '6':
g++;
break;
case '7':
h++;
break;
case '8':
i++;
break;
case '9':
j++;
break;
case ' ':
break OUTER;
default:
break;
}
}
System.out.println("0 "+(a-48));
System.out.println("1 "+(b-48));
System.out.println("2 "+(c-48));
System.out.println("3 "+(d-48));
System.out.println("4 "+(e-48));
System.out.println("5 "+(f-48));
System.out.println("6 "+(g-48));
System.out.println("7 "+(h-48));
System.out.println("8 "+(i-48));
System.out.println("9 "+(j-48));
}
}
please anyone explain me what I can do for removing this extra value in this program.
thanks

Instead of
int a = '0'
use
int a = 0
'0' is equal to 48 in ASCII and it is a character, not a number. So by int a = '0', you actually initialize a to 48

I would suggest to use an array instead. it'll be easier to process.
String str = sc.next();
char[] input = str.toCharArray();
int[] count = new int[10]; // stores the count, int array initialized to 0 by default
for(int i = 0 ; i < input.length; i++){
// get index value by substracting ASCII value
int c = input[i] - 48; // 48 being ASCII Value of '0'
count[c]++;
}
// print the count array
System.out.println(Arrays.toString(count));
count[0] has no of 0's
count[1] has no of 1's
.....

Related

Beginner level Java - Zellers algotrithm

I have an assignment in Java (intro to programming) based on Zellers algorithm, Write input as integers, loop and counter code and I have to use a while loop to get the day and year first then the month, treating Jan & Feb as prior year. I thought I was at least in the ballpark, but cannot get my code to work. Any suggestions on how to improve?
import java.util.Scanner;
import java.text.NumberFormat;
public class ZellersAlgorithm {
public static void main(String[] args) {
//declarations go here
int count, Month, Day, Year;
int C = (int)(Year / 100.0); // the century
int D = (int) (Year % 100); // The year of the century
int K = Day;
int M = Month;
int G = (K + (int)((26 * (M + 1)) / 10.0) + C + (int)(C / 4.0)
+ (int)(D / 4.0) + (5 * D)) % 7;
Month = (M);
Day = (K);
Year = (C + D);
Scanner scan = new Scanner(System.in);
//Title
System.out.println("Project 2 - Zellers Algorithm");
while(M != 0){
System.out.print("Enter a numberic day: ");
K = scan.nextInt();
if (K == 0)
System.out.print("Saturday");
else if (K == 1)
System.out.print("Sunday");
else if (K == 2)
System.out.print("Monday");
else if (K == 3)
System.out.print("Tuesday");
else if (K == 4)
System.out.print("Wednesday");
else if (K == 5)
System.out.print("Thursday");
else
System.out.print("Friday");
System.out.print("Enter a nummeric year: ");
///Need to convert 4 digit year to C & D variable
// Add counter, possibly include length counter 1st 2 digits are century/C last 2 are year
Year = scan.nextInt();
System.out.print("Enter a numeric month: ");
M = scan.nextInt();
switch (M) {
case 1:
System.out.println("March");
break;
case 2:
System.out.println("April");
break;
case 3:
System.out.println("May");
break;
case 4:
System.out.println("June");
break;
case 5:
System.out.println("July");
break;
case 6:
System.out.println("August");
break;
case 7:
System.out.println("September");
break;
case 8:
System.out.println("October");
break;
case 9:
System.out.println("November");
break;
case 10:
System.out.println("December");
break;
case 11:
System.out.println("January" + D + count--);
break;
case 12:
System.out.println("February" + D + count--);
break;
default:
System.out.println("Invalid month.");
break;
}
}
//formula one
//G =([2.6M-.2]+K+D+[D/4]+[C/4]-2C mod 7;
//display as integer
String result = "Day of the week is ";
System.out.println();
Please clarify on what but cannot get my code to work means.
Some comments though
int count, Month, Day, Year; -- variables should be lower case (this does not change the behaviour of your program but is common code style for Java programs - Most people would read Year as a class name). The same goes for "all uppercase" like C, which is normally used for constants
Use variable names that express meaning. M, K, C, D do not help the reader to understand, what they mean.

Switches on eclipse

Why is the output "ADC" and where the D came from ? Also, what is the goal of the default and continue commands in this code?
char x = 'A';
while(x != 'D') {
switch(x) {
case 'A':
System.out.print(x); x = 'D';
case 'B':
System.out.print(x); x = 'C';
case 'C':
System.out.print(x); x = 'D';
default:
continue;
}
You start with A. Since x != 'D' you enter the while loop.
Now the flow is the following:
enter case 'A'
print A and assign x = 'D'
fall-through to case 'B'
print D (since x == 'D') and assign x = 'C'
fall-through to case 'C'
print C (since x == 'C') and assign x = 'D'
fall-through to default (which will normally be reached, when you can't find a matching case)
continue (which means return to the start of the while loop)
Since x == 'D' the condition evaluates to false and won't enter the loop.
==> Result: ADC is printed.
Yes, you forgot the breaks between the steps. So all steps after the matching case will be executed. Try it with:
switch (x) {
case 'A':
System.out.print(x);
x = 'D';
break;
case 'B':
System.out.print(x);
x = 'C';
break;
case 'C':
System.out.print(x);
x = 'D';
break;
}
Switch statements have what is called "fall through".
You need a break at the end of every case, otherwise all of them will run, as is happening here.
char x = 'A'; //starts off as A
while(x != 'D') {
switch(x) {
case 'A':
System.out.print(x); x = 'D'; //here is gets printed and changed to D
case 'B': //you fall through here because there's no break
System.out.print(x); x = 'C'; //print again then change to C
case 'C': //fall through again
System.out.print(x); x = 'D'; //print again then change to D
default:
continue;
You only enter the case if it matches (so if it starts as C it will only print once) but once a match is found you can fall through to the other cases as well.
If you add breaks, then you won't fall through anymore.
char x = 'A';
while(x != 'D') {
switch(x) {
case 'A': //match
System.out.print(x); x = 'D'; //print then modify
break; //break
case 'B':
System.out.print(x); x = 'C';
break;
case 'C':
System.out.print(x); x = 'D';
break;
default:
continue;
look at this switch:
int a = 0;
switch(a) {
case 0:
System.out.println("0");
case 1:
System.out.println("1");
}
The lines of code which are executed are:
int a = 0;
System.out.println("0");
System.out.println("1");
In order to only execute the statement you want to execute you have to use break at the end of every case:
int a = 0;
switch(a) {
case 0:
System.out.println("0");
break;
case 1:
System.out.println("1");
break;
}
When first time switch executes, case 'A' selected, prints A and set x to 'D',
There no break between cases, so next line executes - print D (as x set to 'D' before) and set x to 'C'. And so on.

Compare two hex strings to find number of matching bits

I have two hex strings:
string x = "928fe46f228555621c7f42f3664530f9";
string y = "56cd8c4852cf24b1182300df2448743a";
I'm trying to convert them to binary to find how many bits matches between the two hex strings.
I used this function to convert HEX to Binary:
string GetBinaryStringFromHexString (string sHex)
{
string sReturn = "";
for (int i = 0; i < sHex.length (); ++i)
{
switch (sHex [i])
{
case '0': sReturn.append ("0000"); break;
case '1': sReturn.append ("0001"); break;
case '2': sReturn.append ("0010"); break;
case '3': sReturn.append ("0011"); break;
case '4': sReturn.append ("0100"); break;
case '5': sReturn.append ("0101"); break;
case '6': sReturn.append ("0110"); break;
case '7': sReturn.append ("0111"); break;
case '8': sReturn.append ("1000"); break;
case '9': sReturn.append ("1001"); break;
case 'a': sReturn.append ("1010"); break;
case 'b': sReturn.append ("1011"); break;
case 'c': sReturn.append ("1100"); break;
case 'd': sReturn.append ("1101"); break;
case 'e': sReturn.append ("1110"); break;
case 'f': sReturn.append ("1111"); break;
}
}
return sReturn;
}
So String x in binary is-->
10010010100011111110010001101111001000101000010101010101011000100001110001111111010000101111001101100110010001010011000011111001
and String y in binary is --> 01010110110011011000110001001000010100101100111100100100101100010001100000100011000000001101111100100100010010000111010000111010
But now I'm stuck, how can I xor the two strings to find the number of matching bits ? and how can I count them?
It doesn't matter whether I use Java or C++, can anyone help please
Thank you,
In Java it's pretty easy.
public static int numberOfMatchingOnes(String a, String b) {
BigInteger aNumber = new BigInteger(a, 16);
BigInteger bNumber = new BigInteger(b, 16);
return aNumber.xor(bNumber).bitCount();
}
In C++ you might use a bitset. What you're looking for is called Hamming weight.
If you really want to do it without BigInteger:
Take 4 chars of both strings, convert them into an int, xor them and count the one-bits. Repeat until the strings end.
public static int numberOfMatchingOnes(String a, String b) {
if (a.length() != b.length() || a.length() % 4 != 0) {
throw new IllegalArgumentException("invalid strings");
}
int totalCount = 0;
for (int i = (a.length()-1)/4; i >= 0; i--) {
int aValue = Integer.valueOf(a.substring(i * 4, i * 4 + 4), 16);
int bValue = Integer.valueOf(b.substring(i * 4, i * 4 + 4), 16);
totalCount += Integer.bitCount(aValue ^ bValue);
}
return totalCount;
}
You can look at the Java Sourcecode to see how bitCount() works.
You have two strings. Why not run through them character by character and see if they match or not? Initialize a counter to zero and start incrementing them for each match and display at the end of the loop. Much simpler.
Here is a one-liner solution though (with the power of all the libraries in the world):
System.out.println(StringUtils.countMatches(new BigInteger("928fe46f228555621c7f42f3664530f9",16).xor(new BigInteger("56cd8c4852cf24b1182300df2448743a",16)).toString(2),"1"));
It depends your purpose if you want to find where they matched together you can use AND
in C :
#include <stdio.h>
int toBinary(unsigned int b1,unsigned int b2){
unsigned int b = b1 & b2;
printf("%x & %x = %x\n",b1,b2,b);
}
int main(){
int i,a,b;
unsigned int b1 = 0x100100;
unsigned int b2 = 0x010101;
toBinary(b1,b2);
return 0;
}
the above code from right to left compare numbers in binary and wherever a two bit were 1 then return 1 else return 0
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if you want to find where are the same or not use XOR
in C :
#include <stdio.h>
int toBinary(unsigned int b1,unsigned int b2){
unsigned int b = b1 ^ b2;
printf("%x & %x = %x\n",b1,b2,b);
}
int main(){
int i,a,b;
unsigned int b1 = 0x100100;
unsigned int b2 = 0x010101;
toBinary(b1,b2);
return 0;
}

Coverting roman numeral exceptions to decimal

For some class homework I need to create a program that converts roman numerals to decimal form. I can convert just fine as long as there are no exception characters such as IV or IX. How do I check for these exceptions? My attempt was to translate both the current character and the next one into decimal, then to compare them and if the next one (going right to left) is smaller to then subtract it. The problem is that I get out of bounds errors from this.
My current code is this:
Scanner keyboard = new Scanner(System.in);
String roman;
int decimal = 0;
int number = 0;
System.out.print("Enter a Roman Numeral to convert to decimal form: ");
roman = keyboard.next();
roman = roman.toUpperCase();
for (int count = roman.length()-1; count >= 0; count--)
{
char numeral = roman.charAt(count);
switch (numeral){
case 'I':
decimal = 1;
break;
case 'V':
decimal = 5;
break;
case 'X':
decimal = 10;
break;
case 'L':
decimal = 50;
break;
case 'C':
decimal = 100;
break;
case 'D':
decimal = 500;
break;
case 'M':
decimal = 1000;
break;
default:
System.out.println("Error: Invalid character detected.");
break;
}
number = number + decimal;
}
System.out.println("The decimal equivalent is: " + number);
System.out.println("Later!");
I'm still a beginner and most of the information I see on this kind of problem uses advanced solutions that I simply don't understand. I know I need to compare the characters but I'm not sure how to do this in a way that won't eventually go out of bounds.
EDIT: Solved! After posting the question I was struck by insight and solved the problem myself. This code works but I would appreciate any insights into how to improve it!
Scanner keyboard = new Scanner(System.in);
String roman;
int decimal = 0;
int number = 0;
int last = 0;
System.out.println("This program converts Roman Numerals to decimal form.");
System.out.println("Note: Roman Numerals are I, V, X, L, C, D and M.");
System.out.println("All letters entered will be treated as capitalized.");
System.out.print("Enter a Roman Numeral to convert to decimal form: ");
roman = keyboard.next();
roman = roman.toUpperCase();
for (int count = roman.length()-1; count >= 0; count--)
{
char numeral = roman.charAt(count);
switch (numeral){
case 'I':
decimal = 1;
break;
case 'V':
decimal = 5;
break;
case 'X':
decimal = 10;
break;
case 'L':
decimal = 50;
break;
case 'C':
decimal = 100;
break;
case 'D':
decimal = 500;
break;
case 'M':
decimal = 1000;
break;
default:
System.out.println("Error: Invalid character detected.");
System.exit(0);
break;
}
if (decimal >= last){
number = number + decimal;
}
else {
number = number - decimal;
}
last = decimal;
}
System.out.println("The decimal equivalent is: " + number);
System.out.println("Later!");
Well, a decimal is ##.##, and an integer is ##, so you should probably change demical to num.
Set the number as you already do, and add a check after it for the exception character. But first ensure that it exists:
if(this character is not the first && the previous character is an exception)
adjust the number as necessary
This will avoid an out-of-bounds exceptions.

Using an "or" statement inside a "if" statement with a string length method

So in my fifth line of code [if(length == 2 || 1)] I'm getting an error with my or statement saying the Operator || is undefined for the argument types boolean, int. Any ideas on what is wrong with my syntax and how I can fix it? Thanks!
//Write a program that translates a letter grade into a number grade. Letter grades are
//A B C D F, possibly followed by + or -. Their numeric values are 4, 3, 2, 1, and 0.
//There is no F+ or F-. A + increases the numeric value by 0.3, a - decreases it by 0.3.
//However, an A+ has the value 4.0. All other inputs have value –1.
//Enter a letter grade:
//Use a class Grade with a method getNumericGrade.
public class Grade {
private double grade = 0.0;
public double getNumericGrade(String letterGrade){
int length = letterGrade.length();
if(length == 2 || 1){
char startChar = letterGrade.charAt(0);
char endChar = letterGrade.charAt(1);
switch(startChar){
case 'A':
this.grade = 4.0;
break;
case 'B':
this.grade = 3.0;
break;
case 'C':
this.grade = 2.0;
break;
case 'D':
this.grade = 1.0;
break;
case 'F':
this.grade = 0.0;
break;
default:
this.grade = -1;
}
if(length == 2){
switch(endChar){
case '-':
this.grade = this.grade - .3;
break;
case '+':
if(startChar != 'A'){
this.grade = this.grade + .3;
}
break;
default:
this.grade = -1;
}
}
if(startChar == 'F' && length != 1){
this.grade = -1;
}
}else{
this.grade = -1;
}
return this.grade;
}
}
It means that the || operator doesn't take a boolean and an int, you have to give it two boolean expressions.
if(length == 2 || length == 1)
You want to be saying if(length == 1 || length == 2). What you're doing right now is saying if(length == 2 OR 1). The former involves two logical statements that can evaluate true or false, the latter involves a logical statement on the one hand and an integer on the other.
The computer doesn't interpret length == 2 OR 1 as "return true if length is either one or two" but as "(return true if length equals two) or (the integer 1)".
You can do something like:
if (Arrays.asList(1,2,3).contains(l.lenghth))
// code

Categories

Resources