Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

So far I have this but certain inputs do not produce the right output. For examp

ID: 3630912 • Letter: S

Question

So far I have this but certain inputs do not produce the right output. For example, when I input 0101, the output is 65 instead of 5. When I input 1010 I get 3f2 instead of A. What should my final code look like?



import java.util.Scanner;
import java.io.IOException;

public class YourProgram {
public static void main(String[] args) throws IOException{
//Create Scanner object
Scanner scan = new Scanner(System.in);

//Prompt
System.out.print("Enter an integer value: ");
int myInt = scan.nextInt();

//Convert
String retval = binaryToHex(
Integer.toBinaryString(myInt));

System.out.println("Hex value: " + retval);
}

public static String binaryToHex(String binaryValue) throws IOException{
long num = Long.parseLong(binaryValue);
long rem;
while(num > 0){
rem = num % 10;
num = num / 10;
if(rem != 0 && rem != 1){
System.out.println("This is not a binary number.");
System.out.println("Please try once again.");
System.exit(0);
}
}
int i= Integer.parseInt(binaryValue,2);
String hexString = Integer.toHexString(i);
return hexString;
}
}

Explanation / Answer

// working perfectly now


import java.util.Scanner;
import java.io.IOException;

public class YourProgram {
public static void main(String[] args) throws IOException{
//Create Scanner object
Scanner scan = new Scanner(System.in);

//Prompt
System.out.print("Enter an integer value: ");
String myInt = scan.next();

//Convert
String retval = binaryToHex(myInt);

System.out.println("Hex value: " + retval);
}

public static String binaryToHex(String binaryValue) throws IOException{
long num = Long.parseLong(binaryValue);
long rem;
while(num > 0){
rem = num % 10;
num = num / 10;
if(rem != 0 && rem != 1){
System.out.println("This is not a binary number.");
System.out.println("Please try once again.");
System.exit(0);
}
}
int i= Integer.parseInt(binaryValue,2);
String hexString = Integer.toHexString(i);
return hexString;
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote