How to separate integers using arrays? - java

I am a noob at programming so I might have trouble with some key terms.
I'm trying to write a program where a user types in a minimum number and a maximum number and it generates a random number. After that I want to know how many even numbers and odd numbers are in the random generated number. I was able to successfully complete the first part but I am having trouble detecting how many even and odd numbers are in the random generated number.
SAMPLE OUTPUT:
Ex:
Random generated number is: 478,099
# of even digits: 2
# of odd digits: 3
I tried creating local variables that did not work, I want to use a switch case statement but I am having trouble. For now I used a for loop but I want to use a switch case.
public static void main(String[] args)
{
DecimalFormat fmt = new DecimalFormat("###,###,###,###,###");
Scanner scanner = new Scanner(System.in);
int max = -1;
int min = 0;
int [] diffvalue = new int [1];
System.out.println("Enter in a maximum value: ");
max = scanner.nextInt();
System.out.println("Enter in a minimum value: ");
min = scanner.nextInt();
if (min > max)
{
System.out.println("Your minimum value is greater then your
maximum value.");
}
for (int i = 0; i < diffvalue.length; i++)
{
diffvalue[i] = (int)(Math.random()*(max-min)+min);
}
System.out.println("Random Value: ");
for(int i = 0; i < diffvalue.length; i++)
{
System.out.println(fmt.format(diffvalue[i]));
}
}
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
}
I can't look at the whole number separately.
**EDIT 1**
import java.util.Scanner;
import java.text.DecimalFormat;
public class MyClass
{
public static void main(String args[])
{
DecimalFormat fmt = new DecimalFormat("###,###,###,###,###");
Scanner scanner = new Scanner(System.in);
int max = -1;
int min = 0;
int [] diffvalue = new int [1];
System.out.println("Enter in a maximum value: ");
max = scanner.nextInt();
System.out.println("Enter in a minimum value: ");
min = scanner.nextInt();
int even = 0; int odd = 0;
if (min > max)
{
System.out.println("Your minimum value is greater then your
maximum value.");
}
for (int i = 0; i < diffvalue.length; i++)
{
diffvalue[i] = (int)(Math.random()*(max-min)+min);
}
System.out.println("Random Value: ");
for(int i = 0; i < diffvalue.length; i++)
{
System.out.println(fmt.format(diffvalue[i]));
}
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
System.out.println("Even:" + even);
System.out.println("Odd: " + odd);
}
}
}
I have gotten it to detect the even numbers and the odd numbers now I am curious to know if there is a way to do it without having the the two variables (odd, even).

You are not dividing the value l by 10. Which is why it is going into a infinite loop.
public static void even(int[] diffvalue)
{
int even = 0;
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
if((l % 10)%2==0) // this line is changed
{
even++;
}
l = l/10; // this line is changed
}
}
}
Also, if you are checking for even, you have to do ...%2 == 0. Find your errors fixed in the code above.
EDIT: you can also calculate the odd numbers in the same loop, like this:
if((l % 10)%2==0) // this line is changed
{
even++;
}
else
{
odd++;
}
EDIT3: The code was supposed to go inside the method, not replace the method.
I do not see any use case for a switch case here, but it can be accommodated like this:
public static void even(int[] diffvalue)
{
int even = 0;
for(int i = 0; i < diffvalue.length; i++)
{
int l = diffvalue[i];
while (l > 0)
{
switch ((l % 10) % 2)
{
case 1:
odd++;
break;
default:
even++;
}
l /= 10;
}
}
Hope this helps. Good luck.

Related

Multiple the sum of digit of a number

I am having a hard time figuring out the solution to this problem. I need to write a program that gets an input n (via scanner), then goes with a for loop till that input number, checks if the numbers are divisible by 13 and then multiplies the digits of each number.
So for an example, if the input number is 40, the divisible numbers by 13 would be 13, 26, 39
1+3 = 4,
2+6 = 8,
3+9 = 12
so that's 4*8*12 = 384.
My current code, but I'm stuck here. I probably didn't do it right, too:
Scanner myScanner = new Scanner(System.in);
int num = myScanner.nextInt();
int sum = 0;
for (int i = 0; i < 30; i = i + 1) {
if (i % 13 == 0) {
while (i > 0) {
int add = i % 10;
sum = sum + add;
i = i / 10;
}
}
}
You're computing the sum of the digits, not the product. Also, you're loop is going to 30, not to num. (There's also no reason to start the loop at 0 instead of 1.) Finally, you shouldn't be changing i inside the loop itself; that will screw up the iteration logic. Use an auxiliary variable. Something like this (untested) should work:
Scanner myScanner = new Scanner(System.in);
int num = myScanner.nextInt();
int prod = 1;
for (int i = 1; i < num; i++) {
if (i % 13 == 0) {
int j = i,
sumOfDigits = 0;
while (j > 0) {
int digit = j % 10;
sumOfDigits += digit;
j /= 10;
}
prod *= sumOfDigits;
}
}
Your whole code is messy. You need to work more on loops and variable assignments and scopes.
Given below is the correct code.
Scanner myScanner = new Scanner(System.in);
int num = myScanner.nextInt();
int mul = 1;
for (int i = 1; i < num; i = i + 1) {
if (i % 13 == 0) {
int sum = 0;
int number = i; // = some int
while (number > 0) {
sum = sum + (number % 10);
number = number / 10;
}
mul = mul * sum;
}
}
System.out.println(mul);
myScanner.close();
Another way to do it, change the number that are divisible to char array, then add and multiply.
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number: ");
int num = sc.nextInt();
int prod = 1;
for (int i = 1; i < num; i++) {
if (i % 13 == 0) {
String number = String.valueOf(i);
char[] digits1 = number.toCharArray();
int sum = 0;
for (char ii:digits1) {
sum = Character.getNumericValue(ii) + sum;
}
prod = prod*sum;
}
}
System.out.println(prod);

Find the median of n values given by the user without using arrays or any function that uses arrays or any other collection

Only manual algorithms on variables are allowed. Collections like list, arrays etc. aren't to be used. (I Used .length() function in the program but it can be manually done by putting a space after every input and counting the number of chars till a space is found)
The problem that using arrays would solve is to store any number of values that the user inputs. This can be solved by storing the values in a string. Since we'd have to know how many characters to pick from the string to form a number, I've also stored the lengths of the numbers in a separate string(Length would generally be of only 1 digit so we'd know for sure that the length of nth number would be at the nth char in the lengthstorage string.)
The algorithm:
Take a number from the string and subtract it from every other number in the string.
If the result is positive, add 1 to the int 'pos'; if negative, to 'neg'; if zero, to 'copy'.
If odd number of numbers are inputed, then the number for which pos + copy >= n/2 and neg + copy >= n/2 is the median.
If even number of numbers are inputed, then we'd have 2 middle numbers fmedian and smedian whose average would be the median. (Refer the code for algorithm).
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input,inputstorage,lengthstorage,inputlength;
int nonrep=0;
System.out.println("Enter the number of values");
int n = sc.nextInt();
int fmedian=0,smedian=0;
System.out.println("Enter a value");
input= sc.next(); //String
inputlength = "" + (char)(input.length()+48);
inputstorage = input;
lengthstorage = inputlength;
for (int i=1; i<n; i++)
{
System.out.println("Enter a value");
input = sc.next();
inputstorage = inputstorage + input;
lengthstorage = lengthstorage + (char)(input.length()+48);
}
int mainnumpos = 0;
for(int j=0;j<n;j++)
{
int copy=0;
int mainnumlength = lengthstorage.charAt(j) - 48;
int neg=0,pos=0;
int mainnum = 0; int factor = 1;int mainnumsign = 0;
for (int m =mainnumlength-1; m >= 0; m--)
{
if(inputstorage.charAt(mainnumpos+m)=='-')
{
mainnumsign = 1;
}
else
{
mainnum += (inputstorage.charAt(mainnumpos+m) - '0') * factor;
factor *= 10;
}
}
mainnumpos = mainnumpos + mainnumlength;
if(mainnumsign==1)
{
mainnum = -mainnum;
}
int position = 0;
for (int q=0;q<n;q++)
{ int fnumsign = 0;
int fnumlength = lengthstorage.charAt(q) - 48;
int fnum = 0;
factor = 1;
for (int l =fnumlength-1; l >= 0; l--)
{
if(inputstorage.charAt(position+l)=='-')
{
fnumsign = 1;
}
else{
fnum += (inputstorage.charAt(position+l) - '0') * factor;
factor *= 10;
}
}
if(fnumsign==1)
{
fnum = -fnum;
}
if((mainnum-fnum)>0)
{
pos++;
}
else if((mainnum-fnum)<0)
{
neg++;
}
else{
copy++;
}
position = position + fnumlength;
}
if((n%2)!=0){
if((double)(pos+copy)>=((double)n)/2.0 && (double)(neg+copy)>=((double)n)/2.0)
{
if(nonrep==0)
{
System.out.println("The median is: "+ mainnum);
nonrep++;
}
}
}
else
{
if ((double)(pos+copy)==(double)n/2.0)
{
fmedian=mainnum;
}
else if((double)(neg+copy)==(double)n/2.0)
{
smedian = mainnum;
}
else if((double)(pos+copy)>=(double)n/2.0 && (double)(neg+copy)>=(double)n/2.0 )
{
fmedian = mainnum;
smedian = mainnum;
}
if(j==n-1){
double evenmedian = ((double)(smedian + fmedian))/2.0;
System.out.println("The median is: "+evenmedian);
}
}
}
}
}

How to find a specific number from a user set upperbound and lowerbound in java

The purpose of my code is to determine the number of times the number 3 appears between a range of numbers, the lower and upper bounds determined by the user.
So far, I can check if the number 3 is in the ten's place my using the modulus. But I am having trouble figuring out if a 3 resides in the hundreds, thousandths, etc. I know I need to use a nested loop, but I can't quite figure out how to code it.
Here is my code so far.
public class JavaThree {
public static void main (String [] args) {
int count = 0;
int num;
System.out.print("Enter lower end: ");
int lowerEnd = IO.readInt();
System.out.print("Enter upper end: ");
int upperEnd = IO.readInt();
if (lowerEnd > upperEnd) {
IO.reportBadInput();
return;
} else {
for(num = lowerEnd; num <= upperEnd; num++) {
if(num % 10 == 3) {
count = count + 1;
} else {
count = count;
}
}
}
IO.outputIntAnswer(count);
}
}
here is proper for loop for your task:
for(num = lowerEnd; num <= upperEnd; num++)
{
int nNum = num;
while (nNum > 0)
{
if( (nNum % 10) == 3)
count = count + 1;
nNum = nNum / 10;
}
}
Another solution, although not as efficient as the solution proposed #Ilya Bursov is to convert the number to a string and count the appearences of the char '3':
int threeCount = 0;
for (int num = lowerEnd; num < upperEnd; num++) {
String strNumber = String.valueOf(num);
for (int i = 0; i < strNumber.length(); i++) {
if (strNumber.charAt(i) == '3') {
threeCount++;
}
}
}

Debugging for loop in palindrome numbers code

This code gets an integer n and displays all palindrome numbers less than n.
But seems the for loop doesn't work; because when I enter a number except 0, 1 and negatives, nothing happens.
I tried debugging, but couldn't find the problem!
Sample input: 30
Sample output: 1 2 3 4 5 6 7 8 9 11 22
import java.util.Scanner;
public class PalindromeNumbers {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
if (n == 0 || n == 1 || n < 0)
System.out.println("There's no Palindrome Number!");
else {
for (int num = 1; num < n; num++) {
int reversedNum = 0;
int temp = 0;
while (num > 0) {
// use modulus operator to strip off the last digit
temp = num % 10;
// create the reversed number
reversedNum = reversedNum * 10 + temp;
num = num / 10;
}
if (reversedNum == num)
System.out.println(num);
}
}
}
}
You run into an infinite loop: you use num in your for loop as an index, and reset it to 0 inside the loop. Use different variables, and it should work!
for (int i = 1; i < n; i++) {
int num = i;
...
if (reversedNum == i)
System.out.println(i);
}
You can do it in a more concise way:
public static void main(final String args[]) {
final Scanner input = new Scanner(System.in);
final int max = input.nextInt();
if (max <= 0) {
System.out.println("There's no Palindrome Number!");
} else {
for (int i = 1; i < max; i++) {
if (isPalindrome(i)) {
System.out.println(i);
}
}
}
}
private static boolean isPalindrome(final int num) {
final String temp = "" + num;
return new StringBuilder(temp).reverse().toString().equals(temp);
}
You are changing your num variable inside your for loop. The next time num < n is executed, the value changed (to 0). Try something like this:
for (int num = 1; num < n; num++) {
int reversedNum = 0;
int temp = 0;
int temp2 = num;
while (temp2 > 0) {
// use modulus operator to strip off the last digit
temp = temp2 % 10;
// create the reversed number
reversedNum = reversedNum * 10 + temp;
temp2 = temp2 / 10;
}
if (reversedNum == num)
System.out.println(num);
}
This way, you use a temp variable to calculate your reversedNum, and still keeps the value of num for the next loop iteration.

Count of most occurring digit... Find the digit that occurs most in a given number

the following s the code to
Find the number of occurrences of a given digit in a number.wat shall i do in order to Find the digit that occurs most in a given number.(should i create array and save those values and then compare)
can anyone please help me ..
import java.util.*;
public class NumOccurenceDigit
{
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
System.out.println("Enter a Valid Digit.(contaioning only numerals)");
int number = s.nextInt();
String numberStr = Integer.toString(number);
int numLength = numberStr.length();
System.out.println("Enter numer to find its occurence");
int noToFindOccurance = s.nextInt();
String noToFindOccuranceStr = Integer.toString(noToFindOccurance);
char noToFindOccuranceChar=noToFindOccuranceStr.charAt(0);
int count = 0;
char firstChar = 0;
int i = numLength-1;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
static void recFunNumOccurenceDigit(char firstChar,int count,int i,char noToFindOccuranceChar,String numberStr)
{
if(i >= 0)
{
firstChar = numberStr.charAt(i);
if(firstChar == noToFindOccuranceChar)
//if(a.compareTo(noToFindOccuranceStr) == 0)
{
count++;
}
i--;
recFunNumOccurenceDigit(firstChar,count,i,noToFindOccuranceChar,numberStr);
}
else
{
System.out.println("The number of occurance of the "+noToFindOccuranceChar+" is :"+count);
System.exit(0);
}
}
}
/*
* Enter a Valid Digit.(contaioning only numerals)
456456
Enter numer to find its occurence
4
The number of occurance of the 4 is :2*/
O(n)
keep int digits[] = new int[10];
every time encounter with digit i increase value of digits[i]++
the return the max of digits array and its index. that's all.
Here is my Java code:
public static int countMaxOccurence(String s) {
int digits[] = new int[10];
for (int i = 0; i < s.length(); i++) {
int j = s.charAt(i) - 48;
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;
}
}
System.out.println("digit = " + digit + " count= " + count);
return digit;
}
and here are some tests
System.out.println(countMaxOccurence("12365444433212"));
System.out.println(countMaxOccurence("1111111"));
declare a count[] array
and change your find function to something like
//for (i = 1 to n)
{
count[numberStr.charAt(i)]++;
}
then find the largest item in count[]
public class Demo{
public static void main(String[] args) {
System.out.println("Result: " + maxOccurDigit(327277));
}
public static int maxOccurDigit(int n) {
int maxCount = 0;
int maxNumber = 0;
if (n < 0) {
n = n * (-1);
}
for (int i = 0; i <= 9; i++) {
int num = n;
int count = 0;
while (num > 0) {
if (num % 10 == i) {
count++;
}
num = num / 10;
}
if (count > maxCount) {
maxCount = count;
maxNumber = i;
} else if (count == maxCount) {
maxNumber = -1;
}
}
return maxNumber;
}}
The above code returns the digit that occur the most in a given number. If there is no such digit, it will return -1 (i.e.if there are 2 or more digits that occurs same number of times then -1 is returned. For e.g. if 323277 is passed then result is -1). Also if a number with single digit is passed then number itself is returned back. For e.g. if number 5 is passed then result is 5.

Categories