I need to make a program that can convert hexadecimal values to decimal. I got the program to work but I need to make my program display the same output no matter if the hexadecimal value entered contains the "0x" in front or not.
this is my code.
import java.util.Scanner;
public class Main {
public static long hex2decimal(String s){
String digits = "0123456789ABCDEF";
int val = 0;
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int d = digits.indexOf(c);
val = 16*val + d;
}
return val;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long decimal;
System.out.println("Please enter the hex string:");
String s = sc.next().toUpperCase();
decimal = hex2decimal(s);
System.out.println(decimal);
}
}
Why should you not using Integer.parseInt("121",16), rather custom logic for converting hex to decimal. Here 16 is radix telling number is hexadecimal and will be converted to decimal.
System.out.println(Integer.parseInt("121",16));
Related
I have the following code written with the purpose of the program is for the user to input a number i.e. 123 and the program will output it as 1 2 3 vertically. No matter what I do, my program does it as 3 2 1. I need to use a loop in this program and I can't seem to figure it out.
import java.util.Scanner;
public class DigitsDisplay {
public static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int a = getInt("Give a non-negative integer: ");
double backwards = 0;
int reverse;
int numOfDigits = numOfDigits(a);
double place = Math.pow(10, numOfDigits);
while (a != 0) {
reverse = a % 10;
backwards = backwards + place * reverse;
System.out.println(reverse);
a = a / 10;
}
}
public static int getInt(String prompt) {
int input;
System.out.print(prompt);
input = console.nextInt();
return input;
}
public static int numOfDigits(int a) {
int numOfD = (int)(Math.log10(a)) + 1;
return numOfD;
}
}
Reverse the reversed value
Your program is designed to reverse the digits. And it does. If you want to reverse them back, I suggest you append them to a StringBuilder and then reverse that. Like,
StringBuilder sb = new StringBuilder();
while (a != 0) {
reverse = a % 10;
sb.append(reverse).append(System.lineSeparator());
backwards = backwards + place * reverse;
a = a / 10;
}
System.out.print(sb.reverse());
Using a Regular Expression
Your algorithm could be simplified by using String.replaceAll(String, String) with a regular expression that matches and groups all digits of a and then replaces each digit with itself plus a new line. Something like,
int a = getInt("Give a non-negative integer: ");
System.out.println(String.valueOf(a).replaceAll("(\\d)",
"$1" + System.lineSeparator()));
So this is my first programming course and I have an assignment to convert a binary number entered by the user to a decimal. And my binary number should be stored in a a string.
And to check that all my digits are 1s and 0s I need to use a method to make sure it's valid and return true if the the number is correct and false otherwise.
So I did a search and saw that everyone was using the integer.parseInt(String , int radix) method to convert a binary string to int which worked completely fine, however, the only problem is we didn't take this with my professor so I'm not sure if it's OK and that maybe he wants another way to convert it?
So my question is: how can I write this code in another way that doesn't use this method?.
Here's my code:
import java.util.*;
import java.lang.*;
public class Assignment2
{static Scanner stdIn= new Scanner (System.in);
public static void main(String[] args) {
{String st;
int converttodecimal;
System.out.println("enter a binary number to convert to decimal: ");
st = stdIn.next();
while(!validbinary(st)) {
System.out.println("invalid value, enter a binary number which consists of 1s and 0s only: ");
st = stdIn.next();
}
converttodecimal = Integer.parseInt(st,2);// integer.parseInt(String , int radix);
System.out.println("the equivalent decimal value is: " +converttodecimal );
}
}//end of main method
public static boolean validbinary(String st) {
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) != '0' && st.charAt(i) != '1') {
return false;
}
}
return true;
}
}//end of class
This is the output:
enter a binary number to convert to decimal:
110101
the equivalent decimal value is: 53
Thank you in advance I already asked this question else where but I didn't get the answer I wanted.
UPDATE:
I wrote the program again based on your suggestions #akhil_mittal #fabian but if i want to write the converting method in the program itself (not calling the method) how can i do that ?
here's the code:
import java.util.*;
import java.lang.*;
public class Assignment2test
{static Scanner stdIn= new Scanner (System.in);
public static void main(String[] args) {
{String st;
int result;
System.out.println("enter a binary number to convert to decimal: ");
st = stdIn.next();
while(!validbinary(st)) {
System.out.println("invalid value, enter a binary number which consists of 1s and 0s only: ");
st = stdIn.next();
}
result = convertBinaryToDecimal(st);
System.out.println("the equivalent decimal value is: " + result );
}
}//end of main method
public static boolean validbinary(String st) {
for (int i = 0; i < st.length(); i++) {
if (st.charAt(i) != '0' && st.charAt(i) != '1') {
return false;
}
}
return true;
}
public static int convertBinaryToDecimal(String st){
double decimal =0;
for(int i=0;i<st.length();i++){
if(st.charAt(i)== '1'){
decimal = decimal + Math.pow(2,st.length()-1-i);
}
}
return (int) decimal;
}
}
//end of class
Do it manually, you can just multiply each digit for the corresponding power of two and sum the results.
Regarding the last part of your question, you can simply use java.lang.Math.pow(2,exponent), there is no specific operator for that if that was what you were wondering.
You can use the bit-shift operator to get powers of 2:
int pow2(int exponent) {
return 1 << exponent;
}
which should be more efficient than Math.pow.
But you could also calculate a binary number like this (example for 0b110101):
((((((1)*2+1)*2+0)*2+1)*2+0)*2+1)
i.e. by repeatedly multiplying by 2 and adding the next digit.
I have written two methods which use basic computation to convert binary to decimal, one takes long and other takes String. You can also use them to check the differences in implementation. The method is very simple and easy to understand.
public static int convertBinaryToDecimal(String binary){
double decimal =0;
for(int i=0;i<binary.length();i++){
if(binary.charAt(i)== '1'){
decimal = decimal + Math.pow(2,binary.length()-1-i);
}
}
return (int) decimal;
}
public static int convertBinaryToDecimal(long numberInBinary){
int decimal = 0;
int power = 0;
while(true){
if(numberInBinary == 0){
break;
} else {
long temp = numberInBinary%10;
decimal += temp*Math.pow(2, power);
numberInBinary = numberInBinary/10;
power++;
}
}
return decimal;
}
public static void main(String a[]){
int binaryNumber = 110011;
System.out.println(binaryNumber+ " converts to "+convertBinaryToDecimal(binaryNumber));
String binaryNumberInString = "110011";
System.out.println(binaryNumber+ " converts to "+convertBinaryToDecimal(binaryNumberInString));
}
If you want to ensure that String only contains 0 and 1 then you can try yourself and let me know if you need any help.
Binary to decimal Conversion without using Integer.parseInt method
public class BinaryDecimal
{
public static int binaryToDecimal(int binary) {
int decimal = 0;
for (int power = 1; binary > 0; power *= 2, binary /= 10)
decimal += power * (binary % 10);
return decimal;
}
public static void main(String a[]) {
System.out.println("11 ===> " + binaryToDecimal(11));
//System.out.println("11 ===> " + binaryToDecimal(Integer.parseInt(a[0]))); //Input from command line
}
}
For part of my program, I am trying to ask the user for input on generating a number of random characters. I have already done this with integers and doubles, how would I do this for characters using ASCII values? Would I use the same format as I did for generating integers (Shown in code)?
import java.util.Random;
import java.util.Scanner;
public class NewNumberCharacter {
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Ask the user to enter in the command: integer, double, or character
System.out.println("What do you want to generate, integer, double, or character?");
// Prompt the user to enter a string, or command, then follow the prompts
String command = input.nextLine();
if(command.equals("character")){
System.out.println("How many characters would you like generated?");
int numcharacter = input.nextInt();
RandomDataGenerator.random(numcharacter);
}
if (command.equals("integer")){
System.out.println("What is the upper limit and lower limit of the integers you want to generate?");
int maxn1 = input.nextInt();
int minn2 = input.nextInt();
System.out.println("How many integers do you want to generate?");
int numinteger = input.nextInt();
RandomDataGenerator.random(minn2,maxn1,numinteger); //Call the method
}
if (command.equals("double")){
System.out.println("What is the upper limit and lower limit of the doubles you want to generate?");
double maxn3 = input.nextDouble();
double minn4 = input.nextDouble();
System.out.println("How many doubles do you want to generate?");
int numdouble = input.nextInt();
RandomDataGenerator.random(maxn3,minn4,numdouble);
}
}
}class RandomDataGenerator {
public static int random(int maxn1, int minn2, int numinteger){
for(int i = 0 ; i < numinteger ; i++ ) {
System.out.println(maxn1 + (int)(Math.random()* minn2));
}
return 0;
}
public static double random(double maxn3, double minn4, int numdouble){
for (int i = 0; i < numdouble; i++){
Random r = new Random();
System.out.println(minn4 + (maxn3- minn4) * r.nextDouble());
}
return 0;
}
public static String random(int numcharacter){
for (int i = 0; i < numcharacter; i++){
System.out.println();
}
return null;
}
}
UpdateV2
import java.util.Random;
import java.util.Scanner;
public class NewNumberCharacter {
public static void main(String[] args) {
// Create a Scanner
Scanner input = new Scanner(System.in);
// Ask the user to enter in the command: integer, double, or character
System.out.println("What do you want to generate, integer, double, or character?");
// Prompt the user to enter a string, or command, then follow the prompts
String command = input.nextLine();
if(command.equals("character")){
System.out.println("Enter in an ASCII value for the character" +
"\n 33 to 47 for special characters" +
"\n 65 to 90 for uppercase letters" +
"\n 97 to 102 for lowercase letters");
int ascii1 = input.nextInt();
int ascii2 = input.nextInt();
System.out.println("How many characters would you like generated?");
int numcharacter = input.nextInt();
RandomDataGenerator.random(ascii1,ascii2,numcharacter);
}
if (command.equals("integer")){
System.out.println("What is the upper limit and lower limit of the integers you want to generate?");
int maxn1 = input.nextInt();
int minn2 = input.nextInt();
System.out.println("How many integers do you want to generate?");
int numinteger = input.nextInt();
RandomDataGenerator.random(minn2,maxn1,numinteger); //Call the method
}
if (command.equals("double")){
System.out.println("What is the upper limit and lower limit of the doubles you want to generate?");
double maxn3 = input.nextDouble();
double minn4 = input.nextDouble();
System.out.println("How many doubles do you want to generate?");
int numdouble = input.nextInt();
RandomDataGenerator.random(maxn3,minn4,numdouble);
}
}
}
class RandomDataGenerator {
public static int random(int maxn1, int minn2, int numinteger){
for(int i = 0 ; i < numinteger ; i++ ) {
System.out.println(maxn1 + (int)(Math.random()* minn2));
}
return 0;
}
public static double random(double maxn3, double minn4, int numdouble){
for (int i = 0; i < numdouble; i++){
Random r = new Random();
System.out.println(minn4 + (maxn3- minn4) * r.nextDouble());
}
return 0;
}
public static char randChar(int ascii1 , int ascii2 , int numcharacter) {
for (int i = 0; i < numcharacter; i++){
Random r = new Random();
}
return(char)(Random.nextInt(ascii1-ascii2+1) + ascii1);
}
}
You would do it in a similar way. First of all, you need to learn about characters. Lookup keywords like ASCII table and Unicode.
Then select an alphabet from which you want the random characters. Printing random Chinese characters is a bit different from printing random Latin characters. Also, printing random Latin characters depends on whether you want to print them just from the base alphabet or whether you want to include additional characters from specific scripts, i.e. German Umlauts and German sz ligature.
The following example demonstrates how to create a String of random characters for uppercase Latin characters.
private static final Random random = new Random();
public static String random(final int numChars) {
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < numChars; i++) {
sb.append((char) (random.nextInt(26) + 'A'));
}
return sb.toString();
}
By the way, you may want to rethink a few things about your program:
You might want to return the computed value(s) instead of printing them in the functions.
You might want to move the System.out.println() out of the functions to the caller.
You might want to not generate a new random number generator in every loop iteration. One global for yourself should be enough.
If you need a random range you can do
static final Random rand = new Random();
public static char randChar(char first, char last) {
return (char)(rand.nextInt(last-first+1) + first);
}
Homework time again.
I have to create a program to print 1s and 2s complement of a binary number.
So far is tis correct for 2s compliment? Should I allow input, then calculate 1's compliment before 2's?
import java.util.Scanner;
public class BitWiseComplement {
public static void main (String [] args) {
String a = "1";
String b = "0";
Scanner reader = new Scanner(System.in);
String binary;
String binary2;
System.out.println("Please enter your binary number:");
binary = reader.nextLine();
binary2 = binary.replaceAll(a, b);
System.out.println(binary2);
}
}
For 1's complement of an integer you can 1st convert the integer to binary using Integer class library method toBinaryString() and then run a loop and convert 1's to 0 and vice-versa.
void firstcomplement(int num)
{
String binary=Integer.tobinaryString(num);
String complement="";
for(int i=0; i<binary.length(); i++)
{
if(binary.charAt(i)=='0')
complement[i] += "1";
if(binary.charAt(i)=='1')
complement[i] += "0";
}
}
Try:
String s3=String.format("%4s",
Integer.toBinaryString(i1))
.replace(' ', '0')
.replace('0' ,'a')
.replace('1' ,'0')
.replace('a' ,'1');
and then add one to it.
I have to write a program to convert a 5 digit integer such as 12345 or 00005 into a column showing each individual digit on separate lines. I am asked to use two different methods, a mathematical method and string method. While the string method has given me no problems at all I am having trouble pulling each digit out individually using a mathematical method. This is my code thus far.
import java.util.Scanner; //load scanner
public class digitseparator{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Enter a five-digit integer: ");
String name = in.nextLine();
double n = in.nextDouble();
double ffthdgt = Double.parseInt((double)n%10000);
double frthdgt = Double.parseInt((double)n%1000);
double thrddgt = Double.parseInt((double)n%100);
double scnddgt = Double.parseInt((double)n%10);
double frstdgt = Double.parseInt((double)n%1);
System.out.println(frstdgt);
System.out.println(scnddgt);
System.out.println(thrddgt);
System.out.println(frthdgt);
System.out.println(ffthdgt);
System.out.println("String method Solution");
char frst = name.charAt(0);
System.out.println(frst);
char scnd = name.charAt(1);
System.out.println(scnd);
char thrd = name.charAt(2);
System.out.println(thrd);
char frth = name.charAt(3);
System.out.println(frth);
char ffth = name.charAt(4);
System.out.println(ffth);
}
}
First, Double has no parseInt method. It has parseDouble, which is meant to parse a String into a double. But you already have a double.
Next, you can extract a digit by...
Dividing by a power of 10 to eliminate digits to the right of the desired digit.
Taking the remainder of dividing by 10 to extract the last digit, with the % operator.
import java.util.Scanner; //load scanner
public class digitseparator
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int arr[] = new int[5];
System.out.println("Enter a five-digit integer: ");
int d =in.nextInt();
String name = Integer.toString(d);
System.out.println(name);
for(int i=0;i<5;i++)
{
arr[i] = d%10;
d = d/10;
}
for(int k=0;k<5;k++)
{
System.out.println(arr[k]);
}
System.out.println("String method Solution");
for(int m=0;m<5;m++)
{
System.out.println(name.charAt(m));
}
}
}
Hope this is what you want