Question

Please explain if the following code is actually correct. If the following code correct, please explain...

Please explain if the following code is actually correct. If the following code correct, please explain why the code works and is also correct. Don’t use * Java’s Integer .toBinaryString(int) in this program./* According to the textbook and the instructor, I am not supposed to use arrays such as int binary[] = new int[25]; I guess this is the reason why this problem is starting to look kind of hard.   Chapter 5 Exercise 37: Java Programming
*
* (Decimal to binary) Write a program that prompts the user to enter a
* decimal integer and displays its corresponding binary value. Don’t use
* Java’s Integer .toBinaryString(int) in this program./* Note : if access specifier is specified as public then file name and class name should be same and main should be within that class only */
Programming Exercise Solution
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Dec_to_bin
{
public static void main (String[] args)
{
  
Scanner in = new Scanner(System.in);
//Take User input from keyboard
System.out.println("Enter decimal number: ");
int num = in.nextInt();
int bin =0;
int i=0;
while (num != 0)
{
  
int d = num % 2;
bin=bin+(d*((int)Math.pow(10,i)));
num /= 2;
i++;
}   
System.out.print("\nBinary representation is:");
System.out.print(bin);
System.out.println();
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Following code is correct.

You just need to add "import java.util.Scanner;" before class as it is requried for using scanner.

Reason for correctness.

>> int d = num % 2;

it is checking whether bit in binary represenation will be set or not.

>> bin=bin+(d*((int)Math.pow(10,i)));

This is shifting set bit to its correct position in binary representation and then add existing binary representation of number so far.

>> num /= 2

This will reduce number to half (that is shift last bit to go away) and thus helpng in using one bit at a time.

As you are using int in this you won't be able to handle large values depending on large values of decimal

It will work till 1023

For 1024 it will print 2147483647 because of limit on max value of int.

Add a comment
Know the answer?
Add Answer to:
Please explain if the following code is actually correct. If the following code correct, please explain...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Look for some finshing touches java help with this program. I just two more things added...

    Look for some finshing touches java help with this program. I just two more things added to this code. A loop at the end that will ask the user if they want to quit if they do want to quit the program stops if they don't it loads a new number sequence. import java.util.Random; import java.util.ArrayList; import java.util.Scanner; import java.util.Arrays; import java.util.List; import java.util.Collections; public class main { public static void main(String[] args) { List < Sequence > list =...

  • In the following program, declare an integer array daysInMonth that stores the number of days in January, February, March, April, and so on

    # JAVA In the following program, declare an integer array daysInMonth that stores the number of days in January, February, March, April, and so on. Fill it with the appropriate values (31, 28, 31, 30, ...).The program reads a month and year from the user.When the year is a leap year, change the entry for February to 29.Print out how many days the given month has.CODE:import java.util.Scanner;public class NumberOfDays{   public static void main(String[] args)   {      // Declare and initialize daysOfMonth      ....

  • For the below code find and fix the errors then tell what the output would be....

    For the below code find and fix the errors then tell what the output would be. import java.utils.*; public class pin public void main(String[] args); { char s; int num; Scanner br = Scanner(System.in); System.out.print("Enter the first letter of your name :"); s = BR.next().charAt(0); num = s; System.out.println(“The value associated with your letter is” num); }

  • I need help on creating a while loop for my Java assignment. I am tasked to...

    I need help on creating a while loop for my Java assignment. I am tasked to create a guessing game with numbers 1-10. I am stuck on creating a code where in I have to ask the user if they want to play again. This is the code I have: package journal3c; import java.util.Scanner; import java.util.Random; public class Journal3C { public static void main(String[] args) { Scanner in = new Scanner(System.in); Random rnd = new Random(); System.out.println("Guess a number between...

  • Please write where its written write your code here!! please use java for the code! please...

    Please write where its written write your code here!! please use java for the code! please use the given code and I will rate thanks Magic index in an array a[1..n] is defined to be an index such that a[ i ] = i. Given an array of integers, write a recursive method to find the first magic index from left to right. If one exists in the given array, return the index number i, otherwise return -1. Here are...

  • The following code is a Java code for insertion sort. I would like this code to...

    The following code is a Java code for insertion sort. I would like this code to be modified by not allowing more than 10 numbers of integer elements (if the user enters 11 or a higher number, an error should appear) and also finding the range of the elements after sorting. /* * Java Program to Implement Insertion Sort */ import java.util.Scanner; /* Class InsertionSort */ public class InsertionSortTwo { /* Insertion Sort function */ public static void sort( int...

  • (Java with Netbeans) Programming. Please show modified programming code for already given Main class, and programming...

    (Java with Netbeans) Programming. Please show modified programming code for already given Main class, and programming for code for the new GameChanger class. // the code for Main class for step number 6 has already been given, please show modified progrraming for Main class and GameCHanger class, thank you. package .games; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String args[]) { System.out.println("Welcome to the Number Guessing Game"); System.out.println(); Scanner sc = new Scanner(System.in); // Get upper...

  • Please edit my following JAVA code so that there is no main function. I would like...

    Please edit my following JAVA code so that there is no main function. I would like one function in this class that completes what the current program is trying to do so that I can call this class in my main class which will be separate. import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.Scanner; public class enterwklyincme { private static DecimalFormat df = new DecimalFormat("0.00"); public static float readFloat(Scanner reader) { float num; while (true) { try { num = Float.parseFloat(reader.nextLine()); return...

  • The files provided in the code editor to the right contain syntax and/or logic errors. In...

    The files provided in the code editor to the right contain syntax and/or logic errors. In each case, determine and fix the problem, remove all syntax and coding errors, and run the program to ensure it works properly. // DebugFive2.java // Decides if two numbers are evenly divisible import java.util.Scanner; public class DebugFive2 { public static void main(String args[]) { int num; int num2; Scanner input = new Scanner(System.in); System.out.print("Enter a number "); num = input.nextInteger() System.out.print("Enter another number ");...

  • Add on to the java code below to include a welcome message and menu for the...

    Add on to the java code below to include a welcome message and menu for the user. The user should be able to decide when to exit the program ( the user can enter his data included in code below ), and then can either exit, OR enter another one. Need a loop structure in this code. import java.util.Scanner; public class ReduceFraction { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a numerator: "); int n...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT