Binary to Decimal Conversion in Java (breaking out of the loop) - java

My conversion code is working fine, however I can't seem to restrict the user from inputting numbers other than 0 and 1. I've managed to deal with it to a certain extent: the program recognizes the number (for example 2), but it continues converting numbers that come after it simply ignoring the 2 itself and moving on. If I enter 2011, it's going to convert it to 3 in decimal (011 = 3), instead of breaking completely. I'm assuming it has something to do with the first condition, but I don't know how to fix it, so any help is greatly appreciated.
I'm working in JavaFX, hence the usage of the textfield (t3).
int decimal = 0;
int power = 0;
int bin = Integer.parseInt(t3.getText());
while (bin != 0) {
int temp = bin%10;
if(temp > 1) {
break;
} else {
bin = bin / 10;
decimal += temp * Math.pow(2, power);
power++;
}
}

You can specify the radix in the parseInt call
int bin = Integer.parseInt(t3.getText(), 2);
which will parse a binary number and throw a NumberFormatException on illegal input.

Instead of just break out of look if number is greater than 1, throw NumberFormatException.
int decimal = 0;
int power = 0;
int bin = Integer.parseInt("11");
while (bin != 0) {
int temp = bin%10;
if(temp > 1) {
throw new NumberFormatException("Invalid input"); //throw exception if input contains number greater than 0
} else {
bin = bin / 10;
decimal += temp * Math.pow(2, power);
power++;
}
}

Related

Converting a Binary Integer to a Decimal Integer using Recursion

I am having trouble getting this method, which converts an integer from binary to decimal, to work properly. The main problem I have found is that with binary numbers that end in 0, the last 0 is ignored by the program. For example, if I input 1010, the program would return 5 instead of 10. Below is my method for this conversion.
public int toDecimal(int inBase2){
int num = 0;
if(inBase2 < 0){
num = -1;
return num;
}
if(inBase2 == 0 && num == 0){
return num;
}else{
num = inBase2 % 10 * (int)(Math.pow(2, Math.log10(inBase2)));
return num + toDecimal(inBase2 / 10);
}
}
How would I go about fixing the program in a way that allows it to read the final 0 in the binary integer correctly?
You're doing the calculation the wrong way round. The least significant digit in the binary number is treated as though it's the most significant. So effectively, 1010 returns the result for 0101. Right now, the first digit you process, in the ones place, is multiplied by Math.pow(2, Math.log10(inBase2)), and given the most weight. Instead, you should multiply the results of the recursive function, so later calls (which represent higher value digits) are multiplied more. Example
public int toDecimal(int inBase2){
int num = 0;
if(inBase2 < 0){
num = -1;
return num;
}
if(inBase2 == 0 && num == 0){
return num;
}else{
num = inBase2 % 10;
return num + 2 * toDecimal(inBase2 / 10);
}
}

How to put numbers to array in while loop in java?

I am trying to add two binary numbers and then get their sum in binary system. I got their sum in decimal and now I am trying to turn it into binary. But there is problem that when I take their sum (in decimal) and divide by 2 and find remainders(in while loop), I need to put remainders into array in order print its reverse. However, there is an error in array part. Do you have any suggestions with my code? Thanks in advance.
Here is my code:
import java.util.Scanner;
public class ex1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int m = scan.nextInt();
int k = dec1(n)+dec2(m);
int i=0,c;
int[] arr= {};
while(k>0) {
c = k % 2;
k = k / 2;
arr[i++]=c; //The problem is here. It shows some //error
}
while (i >= 0) {
System.out.print(arr[i--]);
}
}
public static int dec1(int n) {
int a,i=0;
int dec1 = 0;
while(n>0) {
a=n%10;
n=n/10;
dec1= dec1 + (int) (a * Math.pow(2, i));
i++;
}
return dec1;
}
public static int dec2(int m) {
int b,j=0;
int dec2 = 0;
while(m>0) {
b=m%10;
m=m/10;
dec2= dec2 + (int) (b * Math.pow(2, j));
j++;
}
return dec2;
}
}
Here:
int[] arr= {};
creates an empty array. Arrays don't grow dynamically in Java. So any attempt to access any index of arr will result in an ArrayIndexOutOfBounds exception. Because empty arrays have no "index in bounds" at all.
So:
first ask the user for the count of numbers he wants to enter
then go like: int[] arr = new int[targetCountProvidedByUser];
The "more" real answer would be to use List<Integer> numbersFromUsers = new ArrayList<>(); as such Collection classes allow for dynamic adding/removing of elements. But for a Java newbie, you better learn how to deal with arrays first.
Why are you using two different methods to do the same conversion? All you need is one.
You could have done this in the main method.
int k = dec1(n)+dec1(m);
Instead of using Math.pow which returns a double and needs to be cast, another alternative is the following:
int dec = 0;
int mult = 1;
int bin = 10110110; // 128 + 48 + 6 = 182.
while (bin > 0) {
// get the right most bit
int bit = (bin % 10);
// validate
if (bit < 0 || bit > 1) {
throw new IllegalArgumentException("Not a binary number");
}
// Sum up each product, multiplied by a running power of 2.
// this is required since bits are taken from the right.
dec = dec + mult * bit;
bin /= 10;
mult *= 2; // next power of 2
}
System.out.println(dec); // prints 182
An alternative to that is to use a String to represent the binary number and take the bits from the left (high order position).
String bin1 = "10110110";
int dec1 = 0;
// Iterate over the characters, left to right (high to low)
for (char b : bin1.toCharArray()) {
// convert to a integer by subtracting off character '0'.
int bit = b - '0';
// validate
if (bit < 0 || bit > 1) {
throw new IllegalArgumentException("Not a binary number");
}
// going left to right, first multiply by 2 and then add the bit
// Each time thru, the sum will be multiplied by 2 which shifts everything left
// one bit.
dec1 = dec1 * 2 + bit;
}
System.out.println(dec1); // prints 182
One possible way to display the result in binary is to use a StringBuilder and simply insert the converted bits to characters.
public static String toBin(int dec) {
StringBuilder sb = new StringBuilder();
while (dec > 0) {
// by inserting at 0, the bits end up in
// correct order. Adding '0' to the low order
// bit of dec converts to a character.
sb.insert(0, (char) ((dec & 1) + '0'));
// shift right for next bit to convert.
dec >>= 1;
}
return sb.toString();
}

Reverse the digits of an integer [duplicate]

This question already has answers here:
Java reverse an int value without using array
(33 answers)
Closed 3 years ago.
I'm a Java beginner so please pardon me if the question seems silly but I already searched the forums but it seems like no one has my problem.
I need to reverse the digits of an integer, and my class hasn't covered while or if loops yet, so I can't use those. All answers I can find on stackoverflow use those, so I can't use those.
the input I am given is below 10000 and above 0 and the code I have written has no problem reversing the integer if the input is 4 digits (e.g. 1000 - 9999) but once the input is between 1 - 999 it creates zeroes on the right hand side but according to the answer sheets its wrong.
For example: 1534 gets turned into 4351, but
403 becomes 3040 instead of the 304 it should be, and 4 becomes 4000 instead of 4.
I've tried different things in the code but it seems to just keep giving the same answer. Or maybe I'm just missing some key mathematics, I'm not sure.
Scanner scan = new Scanner(System.in);
System.out.println ("Enter an integer:");
int value = scan.nextInt();
int digit = (value % 10);
value = (value / 10);
int digit2 = (value % 10);
value = (value / 10);
int digit3 = (value % 10);
value = (value / 10);
int digit4 = (value % 10);
String reversednum = ("" + digit + digit2 + digit3 + digit4);
System.out.println ( reversednum);
and
Scanner scan = new Scanner(System.in);
System.out.println ("Enter an integer:");
int value = scan.nextInt();
int digit = (value % 10);
int reversednum = (digit);
value = (value /10);
digit = (value % 10);
reversednum = (reversednum * 10 + digit);
value = (value / 10);
digit = (value % 10);
reversednum = (reversednum * 10 + digit);
value = (value / 10);
digit = (value);
reversednum = (reversednum * 10 + digit);
System.out.println (reversednum);
What am I doing wrong?
You can convert from int to String -> reverse String -> convert again in int.
This is a code example.
public int getReverseInt(int value) {
String revertedStr = new StringBuilder(value).reverse().toString();
return Integer.parseInt(revertedStr);
}
Your code assumes that the number can be divided by 1000, which is clearly not the case for numbers below 1000. So add some if statements:
public int reverseNumber(int n) {
// step one: we find the factors using integer maths
int s = n;
int thousands = s / 1000; // this will be 0 if the number is <1000
s = s - thousands*1000;
int hundreds = s / 100; // this will be 0 if the number is <100
s = s - hundreds*100;
int tens = s / 10; // etc.
s = s - tens*10;
int ones = s;
// then: let's start reversing. single digit?
if (n<10) return n;
// two digits?
if (n<100) {
return ones*10 + tens;
}
// etc.
if (n<1000) {
return ones*100 + tens*10 + hundreds;
}
if (n<10000) {
return ones*1000 + tens*100 + hundreds*10 + thousands;
}
// if we get here, we have no idea what to do with this number.
return n;
}
Without spoon-feeding you code (leaving the value of writing your own homework code intact)...
Although you've said you can't use a loop, I don't think there's a sane approach that doesn't use one. Your basic problem is you have hard-coded a solution that works when the number happens to have 4 digits, rather than using code that adapts to a variable length. ie, are not using a loop.
All is not lost with your code however. You have figured out the essence of the solution. You just need to convert it to work processing one digit at a time. Consider using recursion, that divides the number by 10 each time and continues until the number is zero. Of course, you’ll have to capture the end digit before it’s lost by division.
Pseudo code may look like:
pass in the number and the current result
if the number is 0 return result
multiply result by 10 and add remainder of number divided by 10
return the result of calling self with number divided by 10 and result
then call this passing number and zero
Using modulus and division:
int nbr = 123; // reverse to 321 or 3*10*10 + 2*10 + 1
int rev = 0;
while(nbr > 0) {
rev *= 10; // shift left 1 digit
int temp = nbr % 10; // get LO digit
rev += temp; // add in next digit
nbr /= 10; // move to next digit
}
Or a recursive method:
public static int reverseInt(int number, int value) {
switch(number) { // is this conditional statement allowed???
case 0:
return value;
}
value *= 10;
int lod = number % 10;
value += lod;
number /= 10;
return reverseInt(number, value);
}

How to convert a decimal to binary using for loops?

/* This program converts decimal to binary */
import javax.swing.JOptionPane;
public class BinaryLoop {
public static void main(String []args) {
String askForDecimal = JOptionPane.showInputDialog("Enter the decimal number you would like to convert?");
int decimalNumber = Integer.parseInt(askForDecimal);
int remainder = 0;
for (int i = 1; decimalNumber > 0; i++) {
decimalNumber /= 2;
remainder = decimalNumber % 2;
System.out.print(remainder);
}
}
}
For example I type in 15 but it returns 1110 which should be 1111.
p.s. this the result will be read from right to left.
decimalNumber /= 2;
remainder = decimalNumber % 2;
These two lines should be in the opposite order. Can you see why?
You don't need the variable i in your for loop at all, just use a while loop.
There is a flaw in your algorithm because you are dividing first:
15 / 2 = 7
7 / 2 = 3
3 / 2 = 1
1 / 2 = 0
You need to check the remainder before dividing, not afterwards.
If you understand the intent of the program, you should see the problem if you output some of the intermediate workings:
int remainder = 0;
for (int i = 1; decimalNumber > 0; i++) {
System.out.println("Entering for() block");
System.out.println("decimalNumber=" + decimalNumber);
decimalNumber /= 2;
System.out.println("decimalNumber=" + decimalNumber);
remainder = decimalNumber % 2;
System.out.println(remainder);
}
}
Examine the output of this and the error should become obvious, which is that because two statements are the wrong way around, you're missing the first, biggest, value of decimalNumber.
You might also notice that remainder is not used outside the block, so you don't need to declare it outside the block, and you don't need to initialise it to zero.
Likewise, you might notice that the value of i is never used, so you could change the for loop to:
for(;decimalNumber > 0;)
... which is equivalent to:
while(decimalNumber > 0)
Many people get into the habit of putting temporary println statements in their code to debug. However it's a bad habit. Instead, learn to use a debugger as soon as you can. With a debugger you can pause a program and step through it line by line, looking at the values of all the variables as they change.
You need to do this:
String s = "";
Integer remainder = 0;
while(decimalNumber > 0) {
remainder = decimalNumber % 2;
decimalNumber /= 2;
s = remainder.toString() + s;
}
System.out.println(s);
you have to change the code to
remainder = decimalNumber % 2;
decimalNumber /= 2;
You have to get the remainder before dividing the number by 2.

Java recursion and integer double digit

I'm trying to take an integer as a parameter and then use recursion to double each digit in the integer.
For example doubleDigit(3487) would return 33448877.
I'm stuck because I can't figure out how I would read each number in the digit I guess.
To do this using recursion, use the modulus operator (%), dividing by 10 each time and accumulating your resulting string backwards, until you reach the base case (0), where there's nothing left to divide by. In the base case, you just return an empty string.
String doubleDigit(Integer digit) {
if (digit == 0) {
return "";
} else {
Integer thisDigit = digit % 10;
Integer remainingDigits = (digit - thisDigit) / 10;
return doubleDigit(remainingDigits) + thisDigit.toString() + thisDigit.toString();
}
}
If you're looking for a solution which returns an long instead of a String, you can use the following solution below (very similar to Chris', with the assumption of 0 as the base case):
long doubleDigit(long amt) {
if (amt == 0) return 0;
return doubleDigit(amt / 10) * 100 + (amt % 10) * 10 + amt % 10;
}
The function is of course limited by the maximum size of a long in Java.
I did the same question when doing Building Java Programs. Here is my solution which works for negative and positive numbers (and returns 0 for 0).
public static int doubleDigits(int n) {
if (n == 0) {
return 0;
} else {
int lastDigit = n % 10;
return 100 * doubleDigits(n / 10) + 10 * lastDigit + lastDigit;
}
There's no need to use recursion here.
I'm no longer a java guy, but an approximation of the algorithm I might use is this (works in C#, should translate directly to java):
int number = 3487;
int output = 0;
int shift = 1;
while (number > 0) {
int digit = number % 10; // get the least-significant digit
output += ((digit*10) + digit) * shift; // double it, shift it, add it to output
number /= 10; // move to the next digit
shift *= 100; // increase the amount we shift by two digits
}
This solution should work, but now that I've gone to the trouble of writing it, I realise that it is probably clearer to just convert the number to a string and manipulate that. Of course, that will be slower, but you almost certainly don't care about such a small speed difference :)
Edit:
Ok, so you have to use recursion. You already accepted a perfectly fine answer, but here's mine :)
private static long DoubleDigit(long input) {
if (input == 0) return 0; // don't recurse forever!
long digit = input % 10; // extract right-most digit
long doubled = (digit * 10) + digit; // "double" it
long remaining = input / 10; // extract the other digits
return doubled + 100*DoubleDigit(remaining); // recurse to get the result
}
Note I switched to long so it works with a few more digits.
You could get the String.valueOf(doubleDigit) representation of the given integer, then work with Commons StringUtils (easiest, in my opinion) to manipulate the String.
If you need to return another numeric value at that point (as opposed to the newly created/manipulated string) you can just do Integer.valueOf(yourString) or something like that.

Categories