Find occurrence of a digit in a number - java

I am writing a program in which user will enter a digit a and find the number of times a will occur in another number b entered by the user.
import java.util.Scanner;
class Number
{
public static void main(String args[])
{
System.out.println("Enter the digit to match");
Scanner s=new Scanner(System.in);
int a=s.nextInt(); //Digit whose occurrence is to find
System.out.println("Enter the number to match");
int b=s.nextInt(); //Number in which occurrence is to find
int ctr=0;
int ctr1=0;
while(b!=0) //Number of digits in the entered number
{
b/=10;
ctr++;
}
int arr[]=new int[ctr];
for(int i=0;i<ctr;i++) //Breaking the number into array of digits
{
arr[i]=b%10;
b/=10;
if(arr[i]==a)
{
ctr1++;
}
}
System.out.println("Number of occurrences are " +ctr1);
}
}
Each and every time the output is 0. Where I am wrong?

after executing this cycle
while(b!=0) //Number of digits in the entered number
{
b/=10;
ctr++;
}
b becomes 0 and thus it contains no digit but 0.
You need to store the value of b in some variable and re-initialize it after this cycle and before iterating over the digits. Alternatively use only a single cycle of the first type - you don't actually use the number of digits anywhere.
EDIT: another approach would be to convert the number to string and then use lastIndexOf on it to find where the given digit is found. The performance will be a bit worse, but the code will be easier to understand(and shorter).

Something in the lines of:
int count=0;
char a = (char)(47 + s.nextInt());
char[] b = s.nextInt().ToString().ToCharArray();
for(int i=0; i < b.lenght(); i++)
{
if(b[i]==a)
{
count++;
}
}

One basic error that I can find is that you have modified b to get the number of digits and so you can not get the individual bits from that now.
Try copying it into a separate variable before modifying the value of b.

When this is executed, b is always 0.
arr[i]=b%10;

Related

How can I get the printed 1 digit number rather than the original number I typed in?

Hello this is my first post, sorry if I asked this question wrong, however, I am also new to Java programming, I am trying to find the largest digit and print the largest digit and continue to print the largest digit (if that makes sense), so the code that I am using is this:
public static void max(String number) {
if (number.isEmpty()) {
System.out.println("The string is empty. Good-bye.");
System.exit(0);
}
int max = Integer.parseInt(number.charAt(0)+"");
for (int i = 1; i < number.length(); i++) {
int compare = Integer.parseInt(number.charAt(i)+"");
if (compare > max) {
max = compare;
}
}
System.out.println(max);
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
double weight, temp;
boolean special, immediate;
System.out.println("Please enter three numbers for serial number: "); // serial and msb question
String msb = sc.nextLine(); // input serial
System.out.println("The MSB of the serial number is: ");
max(msb); // determines largest number
this does print out the largest number in the sequence, but when I go to print it out again:
System.out.println("Item "+ msb);
I get the original typed number
If I do:
System.out.println("Item "+ max(msb));
I get a "'void' type not allowed" error.
The original output is this (I removed most of the unnecessary code):
Please enter three numbers for serial number:
456
The MSB of the serial number is:
6
true
What is the weight?
12
Item 456 is 12.0kg. Moved to station 7.
Instead, I want it to say:
Please enter three numbers for serial number:
456
The MSB of the serial number is:
6
true
What is the weight?
12
Item 6 is 12.0kg. Moved to station 7.
TLDR, what am I missing or am I not seeing that is preventing me from getting the 1 digit MSB print out?
First of all, it is good practice to encapsulate. So to find maxDigit for given number (integer or long) it is better to accept it as a parameters and return max digit: int maxDigit(int msb).
Second, you could transfer your number into a string and iterate over all digit to find a maximum, it takes O(n) time:
public static int maxDigit(int msb) {
char max = '\0';
for(char ch : String.valueOf(Math.abs(msb)).toCharArray())
max = Math.max(max, ch);
return max - '0';
}
As alternative, you can first sort an array of characters, and then retrieve last element array, it takes O(nlogn)
public static int maxDigit(int msb) {
char[] arr = String.valueOf(Math.abs(msb)).toCharArray();
Arrays.sort(arr);
return arr[arr.length - 1] - '0';
}
And finally client method could look like this:
public static void main(String... args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Please enter three numbers for serial number: ");
System.out.println("The MSB of the serial number is: " + maxDigit(scan.nextInt()));
}
}

how do you split a string of numbers into separate integers and use those in a loop? (java)

i have a project wherein i have to create multiple classes that form the image of each (ex: Digit0, Digit1,...,Digit9) with a small and a large size. there are 10 different classes so i'll just simplify to what's important. (for example class Digit1 contains a print function that outputs a small number 1 or a big number 1). i have no problem creating the classes for these digits, where i'm stuck is in figuring out the tester program.
the tester program should allow the user to input a number (ex: 1, 25, 4354435454 etc.) and input a size (1 for small, and 2 for large) and print out the desired images. so far i have this code and it works but it only allows single digit numbers
import java.util.Scanner;
public class DigitDisplay
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
int digits = scan.nextInt();
int segmentSize = scan.nextInt();
while ((digits!=0)&&(segmentSize!=0)) //terminates when 0 0 is input
{
if (digits==0)
{
if (segmentSize==1) //this is the small size
{
Digit0 small = new Digit0(1);
//this references the small sized 0 created as a method in class Digit0
System.out.println(small.toString());
//this prints the small digit 0
}
else //this is the large size
{
Digit0 big = new Digit0(2);
System.out.println(big.toString());
}
}
//...the other digits are placed as else ifs
}
}
}
i tried altering the scanner objects so that it takes in String digits instead of int digits. so that i could simply split it and use a for loop to go through each character of the string, but i can't seem to get it to work. i really hope i made sense here. i'm a beginner and would really appreciate the help
import java.util.Scanner;
public class DigitDisplay
{
public static void main (String[] args)
{
Scanner scan = new Scanner (System.in);
String digits = scan.next(); //takes in a string of numbers
digits.split(" "); //splits the string into its digits
//int segmentSize = scan.nextInt(); commenting this out because it works. just need to focus on the
digits themselves
while ((!digits.equals("0")) && (segmentSize!=0)) //terminates when input is 0 0
{
for (int i=0; i<digits.length(); i++) //goes through all digits of string
{
int num = digits.charAt(i);
switch (num)
{
case 0:
System.out.println("zero"); //there is a longer code referencing the two sizes but the sizes work but i simplified it again. this is just for me to know whether it is printing the right thing
break;
default:
System.out.println("other"); //these are the other digits, but i just condensed them together just to see if its printing right
break;
}
}
digits = scan.next();
digits.split(" ");
//segmentSize = scan.nextInt();
}
}
}
when i input 002, i want to ouput:
zero
zero
other
but instead, it just outputs "other" for all three.
Looking at the question, I think this is what you're looking for:
Scanner scan = new Scanner (System.in);
String digits = scan.nextLine(); //takes in a string of numbers.
int[] digits_split = new int[0]; //creates an int array to store split digits.
digits_split = digits.split(" "); //splits the string into the digits_split array.
By creating an int array it's now easier to validate the digits.
now you can use this loop to check your split digits:
note below is Pseudo Code and has not been tested...
for(int i = 1; i <= digits.length; i++)
{
if(digits_split[i]=0)
{
System.out.println("zero");
}
else
{
System.out.println("other");
}
}
Also ensure that when entering your digits you put a space in between each one so when the program requests for digits you type: 0 0 2
EDIT:
If your digits contain commas use:
digits = digits.replace(",","");
Also once you've split the string use trim:
digits = digits.trim();
It tidy's things up a little.
ALSO:
when i input 002, i want to ouput:
You need to input: (0[space]0[space]2) to get the output you want. As you're splitting on a " ". Otherwise use a symbol.
Hope this helps,
Rob.

Why does my program keep looking for inputs?

This code is in Java. It allows me to enter the first input fine, but after the second is inputted it keeps looking for more strings, none of the rest of my code follows. Idealy the code will find if 2 strings are anagrams, but I have not been able to test this due to this annoying problem.
import java.util.*;
public class Anagram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a word");
String first = scan.nextLine();
System.out.println("Please enter a second word");
String second = scan.next();
first = first.toLowerCase();
second = second.toLowerCase();
int lengthF = first.length();
int lengthS = first.length();
int x = 0;
int y = 0;
int placeF=0;
int placeS=0;
char g = 97;
int count =0;
if(lengthF != lengthS)
{
System.out.println("The words are not anagrams");
x=1;
}
while(x == y||g<123)
{
x=0;
y=0;
for(int i = 0;i<lengthF;i++)
{
if(first.charAt(i)==g)
{
x++;
}
}
for(int i = 0;i<lengthS;i++)
{
if(second.charAt(i)==g)
{
y++;
}
}
count++;
g++;
}
if(count==23)
System.out.println("Anagram");
else
System.out.println("Not Anagram");
}
}
I've spotted three bugs in your code, which you can easily find by yourself if you always follow these general rules for programming:
Never use numbers obscurely. Write them in a way that explains where that value comes from: Instead of:
char g=97;
... let it be:
char g='a';
And the same goes for every single "special" number in your program: 97, 123 and 23 (In this way you'll see 23 is wrong).
Indexed loops should be always for, with its initial value, its ongoing condition and its increment operation. Ongoing condition must be the index interval condition, plus optional secondary conditions combined by AND operators.
And the third bug... Well, right now I cannot think of any general rule to avoid it. It must have been a copy-and-paste issue: The variable lengthS is wrongly initialized.
Also, I recommend you not to code the same algorithm more than once: Take it out to an individual function and reuse it. So you can do with the loop that counts the number of occurrences of a certain char within a certain string. You could define it like this:
private static int countOccurrencesOfChar(String s, char c) {...}

How to print each number up to a certain number

I am taking an online MOOC to learn Java, the only problem i have is it is from the university of Helsinki in Finland i live in the US so there are limited times when i can be awake to ask for help on an exercise. my current exercise is to ask the user for a number and then print each whole number up to that number while using a
while {
}
statement
this is the code i have currently
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int number = Integer.parseInt(reader.nextLine());
System.out.print("up to what number?:"+ number);
while (number<=number){
System.out.println(number);
number++;
}
}
and what it looks like it is doing is ignoring the
while (number<=number) {
System.out.println(number);
part of my code and proceeding straight to the
number++;
portion of my code do i need to declare another int(variable) to store a value?
the way the course has the test cases for grading i can't simply declare a variable with a definite value as they run several test cases like positive numbers and negative numbers.
is there a way to use the reader to store a value to two separate variables so that they can be compared against each other and only print the numbers up to that number?
i also know that i am missing a
Break;
statement but i am not sure where i would place it in the code i have, i have tried to use
} else {
break;
but get an error stating that i have an else without an if.
i am using netbeans as it is required for my course because the server submissions are setup through TMC.
thinking about it now i'm sure its not skipping the while statement but simply continues to print because as it prints and increments the users input is incremented as well since i only have the one variable but i am again not sure how i would go about storing the user input value in two different variables where i can compare them with the less than or equal to statement and stop the printing once it reaches the number input by the user, in that case i would not necessarily need the break statement as it would stop once it prints up to the number input.
ANSWERED: here is what i finally came up with as my answer.
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("up to what number?:");
int numbers = 1;
int number = Integer.parseInt(reader.nextLine());
while (numbers <= number){
System.out.println(numbers);
numbers++;
}
}
You are comparing number to itself. So (number <= number) is always true.
Use a different variable, such as count to actually count up. Initialize it at zero.
Change the condition to (count < number), then in the loop change the increment to count++ and then output count.
Oh, and you should probably prompt for the number before you read it in.
ie your whole program will be:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("up to what number?:");
int number = Integer.parseInt(reader.nextLine());
int count = 0;
System.out.println(number);
while (count<number){
count++;
System.out.println(count);
}
}
You need another variable to increment upto inserted number
int i=1;
while (i<=number){
System.out.println(i++);
}
What your loop is doing
while (number<=number){
System.out.println(number);
number++;
}
for example number=10 so it's checking like this 10<=10 do you need this,absolutely not.
So for your code you need an another variable to increment up to entered number.
This would do it:
public static void main(String[] args) {
int startingInt = 1; //begin printing from 1
System.out.println("Up to what number?");
Scanner reader = new Scanner(System.in);
int number = Integer.parseInt(reader.nextLine());
while (startingInt <=number){
System.out.println(startingInt);
startingInt++;
}
}
i'm c# expert, so first of all please use c#.
But I know I know you can't always select your laguagued, ;)
Here is solution , it works on my machine.
while (number<=number){
System.out.println(number);
number++;
if (number==arg[0]) break;
}
Enjoy the solution!
System.out.println("Up to what number?");
int number = Integer.parseInt(reader.nextLine());
int n = 1;
while (n <= number) {
System.out.println(n);
n++;
}

Showing process completed but no output is coming up

I am trying to create a program that accepts two numbers and outputs the smallest digit in one number that is larger than the other number(for example, given 4687 and 5, the program should output 6).
The problem that I'm having is that when I compile the program, even though I'm getting no errors, after inputting the two numbers, no output is being shown. The cursor just continues blinking where it is. This is the code:
import java.io.*;
import java.util.*;
public class Numbers {
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
int smallest = 10;
int num;
System.out.printf("Enter a value for n: \n");
int n = in.nextInt();
System.out.printf("Enter a value for num: \n");
num = in.nextInt();
int ch = System.in.read();
while (ch>n && ch<smallest) {
smallest=ch;
ch = System.in.read();
}
System.out.printf("Smallest number that is larger is %d", smallest);
}
}
I ran your program just fine. What you are experiencing is probably just that the program is waiting on input from you that you do not expect to enter.
It's expecting three inputs from the user, is that how you ran it?
Did you remember to hit the enter button on your keyboard after you input the numbers?
Here's a sample output from your program:
Enter a value for n:
100
Enter a value for num:
2
0 // <-- This value corresponds to your program prompting for int ch = System.in.read();
Smallest number that is larger is 10D
HINT: You probably want to convert the value entered for n to a String, then use the toCharrArray() method on String so you can traverse each character, like what you're doing in the while loop.
Try something like:
for(char ch : Integer.toString(n).toCharArray()) {
// rest of your while loop logic
}

Categories