Convert 4-Bit Binary Number to Decimal in Java

  • Context: Java 
  • Thread starter Thread starter J.live
  • Start date Start date
  • Tags Tags
    Binary
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
34 replies · 22K views
hey J.live
I am currently working on this problem as well. I've tried your code but i keep getting an error for the code line:

number=keyboard.nextLine();
number=keyboard.nextLine();

do you know why by any chance?
 
Physics news on Phys.org
Mark44 said:
Here's the code with the extra input line removed, and using the += operator, plus the addition of some white space for better readability.
Code:
int value;
String number;
				
		 	     
System.out.print("Enter Number ");
number = keyboard.nextLine();
		 		
value=0;
value += (number.charAt(0) - '0') * 8;
value += (number.charAt(1) - '0') * 4;
value += (number.charAt(2) - '0') * 2;
value += (number.charAt(3) - '0') * 1;

System.out.println(value);
hey Mark44
I am currently working on this problem as well. I've tried your code but i keep getting an error for the code line:

number=keyboard.nextLine();
number=keyboard.nextLine();

do you know why by any chance?
 
my codes are:


import java.util.Scanner;

public class project11p117 {
Scanner input = new Scanner(System.in);
public static void main(String [] args){

int value;
String number;


System.out.print("Enter Number");
number=keyboard.nextLine();


value=0;
value= value+(number.charAt(0)-'0')*8;
value=value+(number.charAt(1)-'0')*4;
value=value+(number.charAt(2)-'0')*2;
value=value+(number.charAt(3)-'0')*1;

System.out.println(value);

}
}
 
my codes are:import java.util.Scanner;

public class project11p117 {
Scanner input = new Scanner(System.in);
public static void main(String [] args){

int value;
String number;System.out.print("Enter Number");
number=keyboard.nextLine();value=0;
value= value+(number.charAt(0)-'0')*8;
value=value+(number.charAt(1)-'0')*4;
value=value+(number.charAt(2)-'0')*2;
value=value+(number.charAt(3)-'0')*1;

System.out.println(value);

}
}