Java decimal to binary error in conversion - java

I'm doing a number systems code right now and on my decimalToBinary, whenever I enter a decimal number it always converts it to a 1 no matter what decimal number it is. The code is down here.
public static void decimalToBinary() {
do {
System.out.println("Enter your decimal number");
numDecimal = input.nextInt();
if (numDecimal < 0) {
System.out.println("Enter a valid number!");
}
} while (numDecimal < 0);
int intNum = Integer.valueOf(numDecimal);
int counter = 0;
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
for (int i = counter-1; i >= 0; i--) {
System.out.println("Your binary number is " + binaryVal[i]);
}
}

You missed a loop while doing the conversion. below is the working code
public static void decimalToBinary() {
int numDecimal = 0;
Scanner input = new Scanner(System.in);
int[] binaryVal = new int[100];
do {
System.out.println("Enter your decimal number");
numDecimal = input.nextInt();
if (numDecimal < 0) {
System.out.println("Enter a valid number!");
}
} while (numDecimal < 0);
int intNum = Integer.valueOf(numDecimal);
int counter = 0;
while(intNum >0){
binaryVal[counter++] = intNum % 2;
intNum = intNum/2;
}
System.out.println("Your binary number is :");
for (int i = counter-1; i >= 0; i--) {
System.out.print("" + binaryVal[i]);
}
input.close();
}

I recommend you to change the code by the following snippet, you also need to consider to create binaryVal array with a sufficient dimension in order to hold the complete number digits that it is going to generate the transformation to binary.
do {
binaryVal[counter++] = intNum % 2;
intNum = intNum / 2;
} while (intNum > 0);
for (int i = counter - 1; i >= 0; i--) {
System.out.print(binaryVal[i]);
}

If you are learning programming you can do as follows
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int intNum;
while ((intNum = scanner.nextInt()) > 0) {
decimalToBinary(intNum);
System.out.println();
}
}
public static void decimalToBinary(int intNum) {
int counter = 0;
int[] binary = new int[31];
while (intNum > 0) {
binary[counter++] = intNum % 2;
intNum = intNum / 2;
}
for (int i = counter - 1; i >= 0; i--) {
System.out.print(binary[i]);
}
}
}
Off course there are more optimized solution.
But if for other purpose you can simply do
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int intNum;
while ((intNum = scanner.nextInt()) > 0) {
String binary = Integer.toBinaryString(intNum);
System.out.println(binary);
}
}

Related

In java, how do I make a loop statement to print the sum of positive nums from 1 to the value assigned to an int from an input from a scanner?

how do I make a loop statement to print the sum of positive numbers from 1 to the value assigned to int from input from a scanner?
public static void main(String[] args) {
int num = 0;
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Input a number over value 1 ");
num = Integer.parseInt(sc.nextLine());
if (num <= 0) {
System.out.println("the number has be an Integer");
return;
}
for (int i = 1; i <= num; i++) {
System.out.println(i + "+");
sum += i;
// I have no idea what I can do from here one?
}
}
public static void getData() {
System.out.println("Please enter user input ");
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
if (input == 0) {
System.out.println("user input cann't accept.");
} else {
int sumValue = 0;
for (int j = 1; j <= input; j++) {
sumValue = sumValue + j;
}
System.out.println(sumValue);
}
}

I am trying to find the prime numbers from 0 to a given number from the user

My code doesn't work and i don't know either why or how to make it work. This is my code.
public static void ex5(){
Scanner scan = new Scanner(System.in);
int givenNr = scan.nextInt();
int m = 1;
for (int i = 2; i < givenNr; i++){
while (m <= i/2 ){
if(i % m != 0) {
System.out.print(i + " ");
}
m++;
}
}
}
public static void ex5() {
Scanner scan = new Scanner(System.in);
int givenNr = scan.nextInt();
for (int i = 2; i < givenNr; i++) {
if (isPrime(i))
System.out.println(i);
}
}
public static boolean isPrime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0)
return false;
}
return true;
}

How to separate integers using arrays?

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.

How to sum the digits of two integers?

How could I use the following method to sum the integers of two numbers in a separate method? I'm trying to teach myself how to use overloaded methods but this is starting to confuse me. Thanks!
public static void sumNUmber(){
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int sum = 0;
while (num > 0) {
sum = sum + num % 10;
num = num / 10;
}
System.out.println(sum);
public static void main(String[] args) throws ClassNotFoundException {
System.out.println("Enter a number");
Scanner in = new Scanner(System.in);
int num = in.nextInt();
System.out.println(sumDigits(num));
}
public static int sumDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
output
Enter a number
234
9
You probably want to take your core algorithm and put it into a single function and then call it twice, once for each number. For example,
// Core algorithm.
public static int sumDigits(int num) {
int sum = 0;
while (num > 0) {
sum += num % 10;
num = num / 10;
}
return sum;
}
public static void sumNumber() {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int numA = in.nextInt();
System.out.println("Enter another number");
int numB = in.nextInt();
int totalDigits = sumDigits(numA) + sumDigits(numB);
System.out.println(totalDigits);
}
//Merry Xmas :D
public int sumNumbers(int num) {
int returnval;
if (num < 10) {
return num;
} else if (num < 100) {
returnval = Math.floor(num/10) + (num%10);
} else if (num < 1000) {
returnval = Math.floor(num/100) + Math.floor(num/10) + (num%10);
} //repeat as needed
return 0;
}

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