Related
I want to execute the 'addition of 2 fractions' code. Below are my code. How do I pass the input from the Scanner to my other Fraction variable? Please have a look at my if (operation.equals("+")) code. I know how to add the 2 fractions given that I set the values beforehand, but how do I pass the inputs from the scanner to my addFraction method with 2 parameters?
import java.util.Scanner;
public class FractionCalculator {
public static Scanner input = new Scanner(System.in);
public static Fraction f = new Fraction(1,2);
public static Fraction addFrac = new Fraction();
public static void main(String[] args) {
getOperation();
}
public static String getOperation() {
System.out.println("\nPlease enter an operation (+, -, /, *, = or Q to quit): ");
Scanner input = new Scanner(System.in);
String operation = input.nextLine();
if (operation.equals("+")) {
System.out.println("Please enter a fraction (a/b) or integer (a): ");
int addFrac = input.nextInt();
System.out.println(f.add(addFrac()));
}
return getOperation();
}
}
public class Fraction {
private int numerator;
private int denominator;
Fraction(int num, int den) {
numerator = num;
denominator = den;
if (den == 0) {
throw new IllegalArgumentException("Not possible to use denominator zero");
} else if (den < 0) {
numerator = num * -1;
denominator = den * -1;
} else {
this.numerator = num;
this.denominator = den;
}
}
public Fraction add(Fraction other) {
Fraction addFraction = new Fraction(((numerator*other.denominator)+(other.numerator*denominator)),(denominator*other.denominator));
addFraction.toLowestTerms();
return addFraction;
}
}
You can't read a/b using nextInt(). So, my suggestion is you read the fraction as a/b as a string and then convert a and b to integers as below.
System.out.println("Please enter a fraction (a/b): ");
String line = input.nextLine();
String[] parts = line.split("/");
int numerator = Integer.parseInt(parts[0]);
int denominator = Integer.parseInt(parts[1]);
Fraction addFrac = new Fraction(numerator, denominator ));
I don't know why my fractions won't reduce. I think it's because I didn't call it but I don't know where to call it. (sorry the spacing is so bad. they never check that at school)
import java.util.*;
public class FracCalc_Egg {
public static String f1;
public static String op;
public static String f2;
public static int w1;
public static int w2;
public static int n1;
public static int n2;
public static int d1;
public static int d2;
public static void main(String[] args) {
System.out.println("Welcome to the Fraction calculator!");
Scanner console = new Scanner(System.in);
System.out.print("Enter an expression (or \"quit\"): ");
//get the first fraction, or quit
f1 = console.next();
//test fraction1 to see if the user types "quit"
if(f1.equalsIgnoreCase("quit")){
System.out.println("Goodbye!");
}
while(!f1.equalsIgnoreCase("quit")){
op = console.next();
f2 = console.next();
processFractions(f1, op, f2);
System.out.print("Enter an expression (or \"quit\"): ");
f1 = console.next();
if(f1.equalsIgnoreCase("quit")){
System.out.println("Goodbye!");
}
}//end while loop
//while loop continues the calc until the user types "quit"
}//end of main
public static void processFractions(String f1, String op, String f2){
//get int variables from fractions
//testing fraction 1 to get int values
if(f1.contains("_")){ //testing for mixed number
w1=Integer.parseInt(f1.substring(0,f1.indexOf("_")));
n1=Integer.parseInt(f1.substring(f1.indexOf("_")+1,f1.indexOf("/")));
d1=Integer.parseInt(f1.substring(f1.indexOf("/")+1));
n1=(w1*d1)+n1; //making mixed number improper
} else if(f1.contains("/")) { //testing for fraction
n1=Integer.parseInt(f1.substring(0,f1.indexOf("/")));
d1=Integer.parseInt(f1.substring(f1.indexOf("/")+1));
} else {//testing for whole number
w1=Integer.parseInt(f1.substring(0));
n1=w1;
d1=1;
}//end if, else if, else method
//testing fraction 2 to get int values
if(f2.contains("_")){ //mixed fraction
w2=Integer.parseInt(f2.substring(0,f2.indexOf("_")));
n2=Integer.parseInt(f2.substring(f2.indexOf("_")+1,f2.indexOf("/")));
d2=Integer.parseInt(f2.substring(f2.indexOf("/")+1));
n2=w2*d2+n2;
} else if(f2.contains("/")) { //fraction
n2=Integer.parseInt(f2.substring(0,f2.indexOf("/")));
d2=Integer.parseInt(f2.substring(f2.indexOf("/")+1));
} else { //whole number
w2=Integer.parseInt(f2.substring(0));
n2=w2;
d2=1;
}//end if, else if, else method
dotheMath(n1, n2, d1, d2, op);
}//end processFraction method
//dotheMath detmerines the operator
public static void dotheMath(int n1, int n2, int d1, int d2, String op) {
if(op.equals("+")){
System.out.println(add(n1, n2, d1, d2));
} else if(op.equals("-")) {
n2=-1*n2;
System.out.println(add(n1, n2, d1, d2));
} else if(op.equals("*")) {
System.out.println(multiply(n1, n2, d1, d2));
} else {
int x = n2;
int y = d2;
d2=x;
n2=y;
System.out.println(multiply(n1, n2, d1, d2));
} //end the if, else if, else statement
}//end dotheMath method
public static String add(int n1, int n2, int d1, int d2) {
int newn = (n1*d2) + (n2*d1);
int newd = d1*d2;
int divisor = reduce(newn,newd);
newn/=divisor;
newd/=divisor;
String answer = newn+"/"+newd;
return answer;
}//end add method
public static String multiply(int n1, int n2, int d1, int d2) {
int newn = n1*n2;
int newd = d1*d2;
int divisor = reduce(newn,newd);
newn/=divisor;
newd/=divisor;
String answer = newn+"/"+newd;
return answer;
}//end multiply method
public static int lcd(int n1,int d1, int n2, int d2){
int dividend=(d1*n2)+(n1*d2);
int divisor = d1*d2;
int rem = dividend % divisor;
while (rem != 0){
dividend = divisor;
divisor = rem;
rem = dividend % divisor;
}
return divisor;
} //end lcd
public static int reduce (int newn, int newd) { //
int newn_abs = Math.abs (newn);
int newd_abs = Math.abs (newd); //
int min_num = Math.min (newn_abs, newd_abs);
int divisor = 1;
for (int i = 1; i <= min_num; i++) {
if (newn%i == 0 && newd%i == 0){
divisor = 1;
}//end if
}//end for
return divisor;
}//end reduce
}//end of class
example-
Welcome to the Fraction calculator!
Enter an expression (or "quit"): 1/4 + 1_1/2
14/8
the expected output is 1_3/4
and I'm stuck right at the reduce method. someone told me in class that I didn't call that method but I don't know what they mean. They told me to call it in the add and multiply method but how/where do you do that?
When you class mates tell you, that you didn't call the reduce method, they mean, that you never use the reduce method.
Your add-method should look somewhat like this:
public static String add(int n1, int n2, int d1, int d2) {
int newn = (n1*d2) + (n2*d1);
int newd = d1*d2;
int divisor = reduce(newn, newd);
newn/=divisor;
newd/=divisor;
int integerComponent=0;
while(newn >= newd) {
integerComponent++;
newn-=newd;
}
String answer ="";
if(integerComponent>0) {
answer += integerComponent +"_";
}
if(newn!=0) {
answer += newn+"/"+newd;
}
return answer;
}
and the multiply method should look like this:
public static String multiply(int n1, int n2, int d1, int d2) {
int newn = n1*n2;
int newd = d1*d2;
int divisor = reduce(newn, newd);
newn/=divisor;
newd/=divisor;
int integerComponent=0;
while(newn >= newd) {
integerComponent++;
newn-=newd;
}
String answer ="";
if(integerComponent>0) {
answer += integerComponent +"_";
}
if(newn!=0) {
answer += newn+"/"+newd;
}
return answer;
}
Remember that you also have to change your reduce method, as it always returns 1 right now!
Edit: Added code to print fraction as mixed fraction.
Before I get to my answer, I just have one request, please, please fix your indentation. By providing newly formatted, easy to code in your question, you're much more likely to get an answer and much more likely to get a high quality answer.
Now, for my answer. This is a school project, you're supposed to learn through it. On that note, I won't give you the full answer but I will try to guide you. So, a couple of things, firstly, your friend is right, and secondly, your reduce function is incorrect. You are generating a function in two places, in your add function and in your multiply function at the line:
String answer = newn+"/"+newd;
What you have to do instead at this step is call your reduce function in
String answer = reduce(newn, newd);
Now, it's up to you to change the reduce function to properly reduce the fraction and handle improper fractions.
I have the following code:
public static void main (String args[])
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter a Numerator");
int num =reader.nextInt();
System.out.println("Enter a Denominator");
int den =reader.nextInt();
System.out.println("Enter a Numerator and a Denominator");
Rational r = new Rational(num,den);
System.out.println(r.getRational() + " equals " +r.getDecimal());
}
}
class Rational
{
double getNum()
{
return num;
}
double getDen()
{
return den;
}
//getDecimal
double getDecimal()
{
double r = num/den;
return r;
}
String getRational()
{
return getNum()+"/"+getDen();
}
private int getGCF(int n1, int n2)
{
int rem = 0;
int gcf = 0;
do
{
rem = n1 % n2;
if (rem == 0)
gcf = n2;
else
{
n1 = n2;
n2 = rem;
}
}
while (rem != 0);
return gcf;
}
}
The purpose of the code is let the user enter a numerator and denominator. Then the program will divide and give the answer to the equations. What I need help on, is I keep on getting an Error on the line of code reading : Rational r = new Rational(num,den). I don't know why.
You forgot to set a constructor in your Rational-Class. You try to initiate the Object with:
Rational r = new Rational(num,den);
But only have the standard COnstructor Rational(). To achieve that you can call this Constructor you have to add this construcotr:
private int num =0;
private int den =0;
public Rational(int unum, int uden){
this.num = unum;
this.den = uden;
}
Within your Rational-Class you have to use then this.numand this.dento get the the constructor setted objects.
I have a question about multiple instances of a constructor in Java.
My assignment is to receive two fractions and then multiply and divide those fractions.
I am unsure as to how to go about having separate values for the instances of the class objects themselves.
Here is the sample code of where I am having the issue:
import java.util.Scanner;
public class TextLab05
{
static int num1, den1; // numerator and denominator of the 1st rational number
static int num2, den2; // numerator and denominator of the 2nd rational number
public static void main (String args[])
{
enterData();
Rational r1 = new Rational(num1,den1);
Rational r2 = new Rational(num2,den2);
}
}
class Rational
{
private int firstNum; // entered numerator
private int firstDen; // entered denominator
private int num; // reduced numerator
private int den; // reduced denominator
public Rational()
{
}
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
//Here specifically is where I am having comprehension issues. How can I include num2 and den2 if I only have int n and int d?
}
}
If this is hard to understand out of context, here is the entire starting code I was given:
import java.util.Scanner;
public class TextLab05
{
static int num1, den1; // numerator and denominator of the 1st rational number
static int num2, den2; // numerator and denominator of the 2nd rational number
public static void main (String args[])
{
enterData();
Rational r1 = new Rational(num1,den1);
Rational r2 = new Rational(num2,den2);
Rational r3 = new Rational();
r3.multiply(r1,r2);
System.out.println("\n\n" + r1.getOriginal() + " * " + r2.getOriginal() + " = " + r3.getRational());
r3.divide(r1,r2);
System.out.println("\n" + r1.getOriginal() + " / " + r2.getOriginal() + " = " + r3.getRational());
// 100 Point Version Only
// r3.add(r1,r2);
// System.out.println("\n" + r1.getOriginal() + " + " + r2.getOriginal() + " = " + r3.getRational());
// r3.subtract(r1,r2);
// System.out.println("\n" + r1.getOriginal() + " - " + r2.getOriginal() + " = " + r3.getRational());
System.out.println();
}
public static void enterData()
{
Scanner input = new Scanner(System.in);
System.out.print("\nEnter the 1st numerator ----> ");
num1 = input.nextInt();
System.out.print("\nEnter the 1st denominator --> ");
den1 = input.nextInt();
System.out.print("\nEnter the 2nd numerator ----> ");
num2 = input.nextInt();
System.out.print("\nEnter the 2nd denominator --> ");
den2 = input.nextInt();
}
}
class Rational
{
private int firstNum; // entered numerator
private int firstDen; // entered denominator
private int num; // reduced numerator
private int den; // reduced denominator
public Rational()
{
}
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
}
private int getGCF(int n1,int n2)
{
int rem = 0;
int gcf = 0;
do
{
rem = n1 % n2;
if (rem == 0)
gcf = n2;
else
{
n1 = n2;
n2 = rem;
}
}
while (rem != 0);
return gcf;
}
public int getNum()
{
return TextLab05.num1;
}
public int getDen()
{
return TextLab05.den1;
}
public double getDecimal()
{
return (double)TextLab05.num1 / TextLab05.den1;
}
public String getRational()
{
String rational = "" + TextLab05.num1 + "/" + TextLab05.den1;
return rational;
}
public String getOriginal()
{
String original = "" + TextLab05.num1 + "/" + TextLab05.den1;
return original;
}
public void reduce()
{
}
public void multiply(Rational r1, Rational r2)
{
}
public void divide(Rational r1, Rational r2)
{
}
public void add(Rational r1, Rational r2)
{
}
public void subtract(Rational r1, Rational r2)
{
}
}
When you call:
Rational r1 = new Rational(num1, den1);
Rational r2 = new Rational(num2, den2);
in the main method of your program you are creating two instances of the Rational class, one named r1 and one named r2. Because you are passing int values to the Rational constructors, the constructor that will be called is the constructor which requires two integer arguments:
public Rational(int n, int d)
{
...
}
The compiler knows this because it matches the name of the Constructor as well as the types of the arguments passed (known as matching the "signature" of the Constructor).
In the code you have provided, the Rational Constructor code doesn't really make sense - this code:
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
}
should probably look something like this:
public Rational(int n, int d)
{
this.firstNum = n;
this.firstDen = d;
}
The values n and d are passed to the constructor, and then in the body of the constructor the instance variables firstNum and firstDen (which are declared in the private part of the Rational class and effectively "belong" to the instance being created) would then be initialised to the values of n and d.
Everywhere within the body of the Rational class you should refer to the member variables firstNum and firstDen, rather than variables that do not "belong" to the class instance.
I assume the Rational class is supposed to represent a rational number. You say:
//Here specifically is where I am having comprehension issues. How can I include num2 and den2 if I only have int n and int d?
You don't need to store two numerators and two denominators in the Rational class. You just need to creat two Rational objects. One to store num1 and den1, the other to store num2 and den2. You are already doing this:
Rational r1 = new Rational(num1,den1);
Rational r2 = new Rational(num2,den2);
It does not make sense to store two numerators and two denominators in Rational. A rational number only has one of each.
In summary: r1 stores num1 and den1, while r2 stores the other two. When you create a new Rational, n and d refer to the numerator and denominator of that particular instance you are creating.
I am not sure if your implementation of Rational is what you intend, but the constructor is not limited to local varables, it can access any static variables from other classes it can access.
public Rational(int n, int d)
{
n = TextLab05.num1;
d = TextLab05.den1;
}
n and d are local variables, num1 and den1 are static variables in class TextLab05.
So you are assigning the local variables with the static values from the other class.
The code doesn't make sense, as you don't do anything with the values after assigning them to local variables that are disposed when the method ends.
The most important thing to do is understand the concept. You are going to store a rational number in your Rational class. When you do this:
Rational r1 = new Rational(num1,den1);
You are making a single instance of a Rational and naming it r1. r1 should now contain a numerator and a denominator (in this case num1 and den1).
Let's say you want to make the number one half, or 1/2. You could do this:
Rational oneHalf = new Rational(1,2);
Realize that new Rational(1,2) is calling the constructor of your Rational class. In your constructor you need to assign num and den to the passed values (in this case 1 and 2). So you would need something like this:
this.num = num1;
this.den = den1;
So if you want to have the ability to multiply one Rational with another Rational you would need a method or function to do that. In your Rational class, create a method called multiply(Rational anotherRational).
That function would do something like this:
this.num = this.num * anotherRational.num;
this.den = this.den * anotherRational.den;
I gave away half the answer, I'll let you do the rest. Don't just copy what you find here, think about what you're doing.
I am trying to convert decimal to binary numbers from the user's input using Java.
I'm getting errors.
package reversedBinary;
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number=in.nextInt();
if (number <0)
System.out.println("Error: Not a positive integer");
else {
System.out.print("Convert to binary is:");
System.out.print(binaryform(number));
}
}
private static Object binaryform(int number) {
int remainder;
if (number <=1) {
System.out.print(number);
}
remainder= number %2;
binaryform(number >>1);
System.out.print(remainder);
{
return null;
} } }
How do I convert Decimal to Binary in Java?
Integer.toBinaryString() is an in-built method and will do quite well.
Integer.toString(n,8) // decimal to octal
Integer.toString(n,2) // decimal to binary
Integer.toString(n,16) //decimal to Hex
where n = decimal number.
Your binaryForm method is getting caught in an infinite recursion, you need to return if number <= 1:
import java.util.Scanner;
public class ReversedBinary {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive integer");
number = in.nextInt();
if (number < 0) {
System.out.println("Error: Not a positive integer");
} else {
System.out.print("Convert to binary is:");
//System.out.print(binaryform(number));
printBinaryform(number);
}
}
private static void printBinaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return; // KICK OUT OF THE RECURSION
}
remainder = number % 2;
printBinaryform(number >> 1);
System.out.print(remainder);
}
}
I just want to add, for anyone who uses:
String x=Integer.toBinaryString()
to get a String of Binary numbers and wants to convert that string into an int. If you use
int y=Integer.parseInt(x)
you will get a NumberFormatException error.
What I did to convert String x to Integers, was first converted each individual Char in the String x to a single Char in a for loop.
char t = (x.charAt(z));
I then converted each Char back into an individual String,
String u=String.valueOf(t);
then Parsed each String into an Integer.
Id figure Id post this, because I took me a while to figure out how to get a binary such as 01010101 into Integer form.
/**
* #param no
* : Decimal no
* #return binary as integer array
*/
public int[] convertBinary(int no) {
int i = 0, temp[] = new int[7];
int binary[];
while (no > 0) {
temp[i++] = no % 2;
no /= 2;
}
binary = new int[i];
int k = 0;
for (int j = i - 1; j >= 0; j--) {
binary[k++] = temp[j];
}
return binary;
}
public static void main(String h[])
{
Scanner sc=new Scanner(System.in);
int decimal=sc.nextInt();
String binary="";
if(decimal<=0)
{
System.out.println("Please Enter greater than 0");
}
else
{
while(decimal>0)
{
binary=(decimal%2)+binary;
decimal=decimal/2;
}
System.out.println("binary is:"+binary);
}
}
The following converts decimal to Binary with Time Complexity : O(n) Linear Time and with out any java inbuilt function
private static int decimalToBinary(int N) {
StringBuilder builder = new StringBuilder();
int base = 2;
while (N != 0) {
int reminder = N % base;
builder.append(reminder);
N = N / base;
}
return Integer.parseInt(builder.reverse().toString());
}
In C# , but it's just the same as in Java :
public static void findOnes2(int num)
{
int count = 0; // count 1's
String snum = ""; // final binary representation
int rem = 0; // remainder
while (num != 0)
{
rem = num % 2; // grab remainder
snum += rem.ToString(); // build the binary rep
num = num / 2;
if (rem == 1) // check if we have a 1
count++; // if so add 1 to the count
}
char[] arr = snum.ToCharArray();
Array.Reverse(arr);
String snum2 = new string(arr);
Console.WriteLine("Reporting ...");
Console.WriteLine("The binary representation :" + snum2);
Console.WriteLine("The number of 1's is :" + count);
}
public static void Main()
{
findOnes2(10);
}
It might seem silly , but if u wanna try utility function
System.out.println(Integer.parseInt((Integer.toString(i,2))));
there must be some utility method to do it directly, I cant remember.
public static void main(String[] args)
{
Scanner in =new Scanner(System.in);
System.out.print("Put a number : ");
int a=in.nextInt();
StringBuffer b=new StringBuffer();
while(a>=1)
{
if(a%2!=0)
{
b.append(1);
}
else if(a%2==0)
{
b.append(0);
}
a /=2;
}
System.out.println(b.reverse());
}
Binary to Decimal without using Integer.ParseInt():
import java.util.Scanner;
//convert binary to decimal number in java without using Integer.parseInt() method.
public class BinaryToDecimalWithOutParseInt {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number: ");
int binarynum =input.nextInt();
int binary=binarynum;
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int temp = binary%10;
decimal += temp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
System.out.println("Binary="+binarynum+" Decimal="+decimal); ;
}
}
Output:
Enter a binary number:
1010
Binary=1010 Decimal=10
Binary to Decimal using Integer.parseInt():
import java.util.Scanner;
//convert binary to decimal number in java using Integer.parseInt() method.
public class BinaryToDecimalWithParseInt {
public static void main(String[] args) {
Scanner input = new Scanner( System.in );
System.out.println("Enter a binary number: ");
String binaryString =input.nextLine();
System.out.println("Result: "+Integer.parseInt(binaryString,2));
}
}
Output:
Enter a binary number:
1010
Result: 10
A rather simple than efficient program, yet it does the job.
Scanner sc = new Scanner(System.in);
System.out.println("Give me my binaries");
int str = sc.nextInt(2);
System.out.println(str);
All your problems can be solved with a one-liner!
To incorporate my solution into your project, simply remove your binaryform(int number) method, and replace System.out.print(binaryform(number)); with System.out.println(Integer.toBinaryString(number));.
/**
* converting decimal to binary
*
* #param n the number
*/
private static void toBinary(int n) {
if (n == 0) {
return; //end of recursion
} else {
toBinary(n / 2);
System.out.print(n % 2);
}
}
/**
* converting decimal to binary string
*
* #param n the number
* #return the binary string of n
*/
private static String toBinaryString(int n) {
Stack<Integer> bits = new Stack<>();
do {
bits.push(n % 2);
n /= 2;
} while (n != 0);
StringBuilder builder = new StringBuilder();
while (!bits.isEmpty()) {
builder.append(bits.pop());
}
return builder.toString();
}
Or you can use Integer.toString(int i, int radix)
e.g:(Convert 12 to binary)
Integer.toString(12, 2)
public static String convertToBinary(int dec)
{
String str = "";
while(dec!=0)
{
str += Integer.toString(dec%2);
dec /= 2;
}
return new StringBuffer(str).reverse().toString();
}
Practically you can write it as a recursive function. Each function call returns their results and add to the tail of the previous result. It is possible to write this method by using java as simple as you can find below:
public class Solution {
private static String convertDecimalToBinary(int n) {
String output = "";
if (n >= 1) {
output = convertDecimalToBinary(n >> 1) + (n % 2);
}
return output;
}
public static void main(String[] args) {
int num = 125;
String binaryStr = convertDecimalToBinary(num);
System.out.println(binaryStr);
}
}
Let us take a look how is the above recursion working:
After calling convertDecimalToBinary method once, it calls itself till the value of the number will be lesser than 1 and return all of the concatenated results to the place where it called first.
References:
Java - Bitwise and Bit Shift Operators https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
If you want to reverse the calculated binary form , you can use the StringBuffer class and simply use the reverse() method . Here is a sample program that will explain its use and calculate the binary
public class Binary {
public StringBuffer calculateBinary(int number) {
StringBuffer sBuf = new StringBuffer();
int temp = 0;
while (number > 0) {
temp = number % 2;
sBuf.append(temp);
number = number / 2;
}
return sBuf.reverse();
}
}
public class Main {
public static void main(String[] args) throws IOException {
System.out.println("enter the number you want to convert");
BufferedReader bReader = new BufferedReader(newInputStreamReader(System.in));
int number = Integer.parseInt(bReader.readLine());
Binary binaryObject = new Binary();
StringBuffer result = binaryObject.calculateBinary(number);
System.out.println(result);
}
}
The better way of doing it:
public static void main(String [] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine().trim());
double ans = 0;
int i=0;
while(t!=0){
int digit = t & 1;
ans = ans + (digit*Math.pow(10,i));
i++;
t =t>>1;
}
System.out.println((int)ans);
}
I just solved this myself, and I wanted to share my answer because it includes the binary reversal and then conversion to decimal. I'm not a very experienced coder but hopefully this will be helpful to someone else.
What I did was push the binary data onto a stack as I was converting it, and then popped it off to reverse it and convert it back to decimal.
import java.util.Scanner;
import java.util.Stack;
public class ReversedBinary
{
private Stack<Integer> st;
public ReversedBinary()
{
st = new Stack<>();
}
private int decimaltoBinary(int dec)
{
if(dec == 0 || dec == 1)
{
st.push(dec % 2);
return dec;
}
st.push(dec % 2);
dec = decimaltoBinary(dec / 2);
return dec;
}
private int reversedtoDecimal()
{
int revDec = st.pop();
int i = 1;
while(!st.isEmpty())
{
revDec += st.pop() * Math.pow(2, i++);
}
return revDec;
}
public static void main(String[] args)
{
ReversedBinary rev = new ReversedBinary();
System.out.println("Please enter a positive integer:");
Scanner sc = new Scanner(System.in);
while(sc.hasNextLine())
{
int input = Integer.parseInt(sc.nextLine());
if(input < 1 || input > 1000000000)
{
System.out.println("Integer must be between 1 and 1000000000!");
}
else
{
rev.decimaltoBinary(input);
System.out.println("Binary to reversed, converted to decimal: " + rev.reversedtoDecimal());
}
}
}
}
import java.util.*;
public class BinaryNumber
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number");
int n = scan.nextInt();
int rem;
int num =n;
String str="";
while(num>0)
{
rem = num%2;
str = rem + str;
num=num/2;
}
System.out.println("the bunary number for "+n+" is : "+str);
}
}
This is a very basic procedure, I got this after putting a general procedure on paper.
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Number:");
int number = input.nextInt();
while(number!=0)
{
if(number%2==0)
{
number/=2;
System.out.print(0);//Example: 10/2 = 5 -> 0
}
else if(number%2==1)
{
number/=2;
System.out.print(1);// 5/2 = 2 -> 1
}
else if(number==2)
{
number/=2;
System.out.print(01);// 2/2 = 0 -> 01 ->0101
}
}
}
}
//converts decimal to binary string
String convertToBinary(int decimalNumber){
String binary="";
while(decimalNumber>0){
int remainder=decimalNumber%2;
//line below ensures the remainders are reversed
binary=remainder+binary;
decimalNumber=decimalNumber/2;
}
return binary;
}
One of the fastest solutions:
public static long getBinary(int n)
{
long res=0;
int t=0;
while(n>1)
{
t= (int) (Math.log(n)/Math.log(2));
res = res+(long)(Math.pow(10, t));
n-=Math.pow(2, t);
}
return res;
}
Even better with StringBuilder using insert() in front of the decimal string under construction, without calling reverse(),
static String toBinary(int n) {
if (n == 0) {
return "0";
}
StringBuilder bldr = new StringBuilder();
while (n > 0) {
bldr = bldr.insert(0, n % 2);
n = n / 2;
}
return bldr.toString();
}
No need of any java in-built functions. Simple recursion will do.
public class DecimaltoBinaryTest {
public static void main(String[] args) {
DecimaltoBinary decimaltoBinary = new DecimaltoBinary();
System.out.println("hello " + decimaltoBinary.convertToBinary(1000,0));
}
}
class DecimaltoBinary {
public DecimaltoBinary() {
}
public int convertToBinary(int num,int binary) {
if (num == 0 || num == 1) {
return num;
}
binary = convertToBinary(num / 2, binary);
binary = binary * 10 + (num % 2);
return binary;
}
}
int n = 13;
String binary = "";
//decimal to binary
while (n > 0) {
int d = n & 1;
binary = d + binary;
n = n >> 1;
}
System.out.println(binary);
//binary to decimal
int power = 1;
n = 0;
for (int i = binary.length() - 1; i >= 0; i--) {
n = n + Character.getNumericValue(binary.charAt(i)) * power;
power = power * 2;
}
System.out.println(n);