Is this code correct for 2's complement? - java

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.

Related

Binary to Decimal calculator InputMismatchException

My goal is to create a simple binary to decimal calculator. I try to go about this by first having the user input a string of the binary value they are trying to calculate and later use the length of this string to run a for loop (as seen in the code below). The calculator appears to work fine but fails when the user enters a binary number (of all 1's) longer than 20 digits. I receive a java.util.InputMismatchException error and I don't know how to fix it.
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a binary number to convert to decimal: ");
long binaryNum = scan.nextLong();
System.out.println(binaryConverter(binaryNum));
scan.close();
}
public static long binaryConverter(long binaryNum) {
String binaryString = Long.toString(binaryNum);
long decimalValue = 0;
for(int i = 0; i < binaryString.length(); i++) {
if((binaryNum%10) == 0) {
binaryNum = binaryNum/10;
} else if((binaryNum%10) == 1) {
decimalValue += Math.pow(2, i);
binaryNum = binaryNum/10;
} else {
System.out.println("This isn't a binary number. Please try again.");
break;
}
}
return decimalValue;
}
}
The way you want to do this to use scanner.nextLong(2) where 2 is the radix. Then you will be reading in an actual binary number.
long number = scanner.nextLong(2);
System.out.println(number);
produces
144115188075855871
for input of
111111111111111111111111111111111111111111111111111111111
If I understood you correctly you always want to convert the binary input to a decimal value. A very simple solution would look like this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a binary number to convert to decimal: ");
final String input = scan.next();
System.out.println(Integer.parseInt(input, 2));
scan.close();
}
If you are interested how it works under the hood, take a look at the java source for Integer.parseInt.

How can I ignore part of an input in Java?

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));

converting to decimal but without using integer.parseInt() method

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
}
}

moving the characters in a text string a specified number of positions

I am new in programming and I am trying to write a program that moves the characters in a text string a specified number of positions.
The program must include a method whose inputs will be a text string (type String) and the number of positions (type int). The output will be a string with characters shifted.
For example, moving 4 positions:
rabbit eats a carrot
it eats a carrotrabb
Now I have this partial code. I can erase first characters but I don't know how to put them to the end of this text. How can i make it?
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
char firstLetter = a.charAt(0);
b--;
a = a.substring(b);
String m = a + firstLetter ;
System.out.println("now it is "+ m);
}
If you use regex, it's just one line:
return str.replaceAll("^(.{" + n + "})(.*)", "$2$1");
import java.util.*;
public class JavaApplication5 {
public static void main(String[] args) {
System.out.println("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.println("enter number of positions= ");
int b = cti.nextInt();
String firstPart = a.substring(0,b); // line 1
b--;
a = a.substring(b);
String m = a + firstPart ; // line 2
System.out.println("now it is "+ m);
}
}
See the changes above in statement marked with comment line 1 and line 2.
In line 1, we are getting the first part of string and in line 2, adding at the end of second string part.
public String foo(String s, int n) {
String s2 = s.substring(0, n);
s = s.substring(n) + s2;
return s;
}
you can put a few validations on this, like null string or n is less than s.length() etc.
It is better to use modulus operator to calculate number of shifts. When initial number of shift is more than string length. Check this :
public String shift(String string,int n){
int nshift = string.length() < n ? n%string.length() : n ;
String a = string.substring(0,nshift);
return string.substring(nshift) + a ;
}
One more version. All the work is essentially done in 1 line here:
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
Anyway, the full code is:
import java.util.*;
public class ShiftLetters {
public static void main(String[] args) {
System.out.print("enter the text: ");
Scanner cti = new Scanner(System.in);
String a = cti.nextLine();
System.out.print("Enter number of positions: ");
int b = cti.nextInt();
String result = new StringBuilder(a).delete(0, b).append(a.substring(0,b)).toString();
System.out.println(result);
}
}
Also, you might want to be more accurate with your indentation style to improve readability.

Converting a 5 digit integer into a column

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

Categories

Resources