Way to get the twos compliment decimal from binary? - java

I have a simple question, how do I get the twos compliment instead of the regular answer from binary? I have a program that does the booths algorithm but when it returns the decimal it gives me a number that's a bit too high, I'm doing 9 * -9 and the answer it gives is 65455. I just want to know if there is a way to get the twos compliment instead (-81). The binary I get from the code is 1111111110101111 which I know from looking around does equal -81 when finding the two's compliment, I just don't know how to get my program to recognize or say that.
Edit: I found a small fix, essentially just checking if the binary of the product equals the result I got, this is how I've been printing the binary and converting it to a decimal, putting in the print area as The answer said something had to be done here, I got it working properly but would like to clean it up if I can
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first number: ");
int operand1 = sc.nextInt();
System.out.print("Enter the second number: ");
int operand2 = sc.nextInt();
String answer = multiply(operand1, operand2);
System.out.println("Final Product (binary): " + answer);
int decimal=Integer.parseInt(answer,2);
if(operand1 * operand2 < 0) {
int decProduct = operand1 * operand2;
String biProduct = toBinary(decProduct, 16);
if (biProduct.length() > 16)
{
biProduct = biProduct.substring(biProduct.length() - 16);
}
if(biProduct.equals(answer)) {
decimal = decProduct;
}
}
System.out.println("Final Answer (decimal): " + decimal);
}

The computer has no idea what it means. It just has some memory and in that memory are bits. The bits that are in it, are e.g. 1111111110101111.
What does that sequence mean? Who knows. The computer doesn't know or care.
It's the print code that decides. IT decides that this is to be taken in and then rendered such that the characters -, 8, and 1 appear on your computer screen.
Thus, the error here, is in the print code. There is no converting required. The bit sequence is all the things, at once: It's 1111111110101111, it's 65455, and it is -81. Which one is shown depends on how you print it.
Given that your print code isn't in the question, you're going to have to figure it out with this information.

Related

How can I add a placeholder to a random Int then pull a single digit from that Int in Java?

I am new to Java and programming all together.. I am trying to make a program that ciphers a number for the user. The user inputs 5 digits separately so I add them together to get a total. I need to pull the first digit and second digit of the total and enter it into (firstDigit+key)%10 and (secondDigit+key)%10. Then need to combine the answer to each equation together.
My total needs to be two digits, so even if the user enters all 1's which would total to be 5, I need it to be displayed and seen as 05 so that both equations have a digit to use. It needs to be two digits. I cant seem to figure how to enter a place holder. I was thinking about trying to use:
if (total < 10)
but then what?
Secondly, the method I used below seems like a terrible way to pull a single digit from a number. I think I changed the int total into a string so I can use .substring to pull the digits, then converted back to an int. Surprisingly it works. Is there a better way to do this knowing that the number is random?
String totalString = Integer.toString(total);
String stringDigit1 = totalString.substring(0,1);
String stringDigit2 = totalString.substring(1,2);
int firstDigitInt1 = Integer.parseInt(stringDigit1);
int firstDigitInt2 = Integer.parseInt(stringDigit2);
int encodedDigit1 = (firstDigitInt1+key)%10;
int encodedDigit2 = (firstDigitInt2+key)%10;
System.out.println("Your encoded Number is: " + encodedDigit1 + encodedDigit2);
Your method for obtaining the individual digits is good, and if you want to maintain it I believe your intuition is correct, it should suffice to say:
if (total < 10) {
firstDigitInt1 = 0
}
This will work out with your following math.
Your method with substrings is far from terrible, but in case you wanted something more sleek you can instead say:
int Digit1 = total / 10;
int Digit2 = total % 10;
Here, you can take advantage of integer truncation (where an integer won't remember decimal places) to get the first digit, which also solves the first problem: 5 / 10 = 0 (in terms of ints). For the second digit, it suffices to say modulo 10, as it is the remainder once the total is divided by 10.

Char of string outputting incorrectly

This is my program and what I am trying to achieve is taking the char value in string amount1 at position 1 i.e for example amount1=$3.00 amount2=2. However it doesn't print out what I expected, 2.
System.out.print("$"+cost[0]+".00 remains to be paid. Enter coin or note: ");
String amount1 = keyboard.nextLine();
char amount2 = amount1.charAt(1);
String amountcheck = "$"+cost[0]+".00";
int [] remainder = new int[1];
if (amount1.equals(amountcheck)) {
System.out.println("Perfect! No change given."); }
if (amount2 < cost[0]) {
remainder[0] = cost[0] - amount2; }
System.out.println("Remainder = "+remainder[0]);
System.out.println(+amount2);
For example,
$3.00 remains to be paid. Enter coin or note: $2.00
Remainder = 0
50
The problem is both in lines 2 and 3. Firstly 3, It don't understand why it outputs 50 as char at amount1 index 1. If i'm not wrong don't char positions work similarly off array index systems. Secondly line 3, the if statement in lines of 8 and 9 of my original code don't seem to catch that amount 2 < cost[0] and don't do the following operations.
So what I expected to happen when I am taking char at position 1 of "$2.00" is newamount would be equal to 2 instead of 50 which the program is outputting.
I've tried changing the char positions but all this seems to do is decrement the value.
You set your amount2 as a char and when you print it, it translates to the ASCII number of that charater which for the charater '2' is 50.
If you want to output 2 you should change your amount2 to type intand parse the char to integer like this Integer.parseInt(""+amount1.charAt(1)); in line 3.
You are using a char to store a numeric value, but that value is a character, not a number. Meaning you are storing '2' which is actually 50 in ASCII. You should remove the value of 48 to get the correct value ('0') or parse the String into a number directly with Integer.parseInt(String).
But as I said in comment, this is easy to correct so I will not provide much more code to this.
But let's be honnest, your logic is risky from the beginning.
You are asking the user to input an amount in a specific format : "$#.00". If the number is two digit $##.00 it fails, if he add a space or don't put the $ or any mistake that users are professional to find, it fails.
First, you should simplified this, do you need the $ ? Ask for dollar currency if you want to specifiy it.
Then, do you need decimals ? Let first assume you don't (see Note for decimal hint).
You just need to input an integer value through the Scanner, which provide method to get Integer -> Scanner.nextInt()
int ammountReceived = keyboard.nextInt();
Then you need to see if this is
Equals
Too much
Not enough
Like this :
int remainder = amountToPay - amountReceived;
if(remainder == 0){
//equals
} else if(remainder > 0){
//not enough
} else {
//too much
}
This would give a simpler solution of :
Scanner sc = new Scanner(System.in);
System.out.print("Amount to pay : $");
int amountToPay = sc.nextInt();
System.out.print("Amount received : $");
int amountReceived = sc.nextInt();
int remainder = amountToPay - amountReceived;
if (remainder == 0) {
System.out.println("That perfect, thanks.");
} else if (remainder > 0) {
System.out.println("Remaining : $" + remainder);
} else {
System.out.println("Need to give back : $" + -remainder);
}
sc.close();
Yours and mine are close, but you will see this is more readable and focused on the problem, I don't play with char to get from a specific String pattern, I am focused on the problem -> to get paid ;)
Now, you have to add a loop here to ask again until you received the correct amount. But please, don't read a numerical String character by character...
Note :
Scanner.nextInt throws exception if the format is incorrect (not an integer)
You can easily adapt this to get double, float or better BigDecimal

Java, even number of even digits, odd number of odd digits

This program is essentially a game where the user must enter numbers to see which numbers are good: numbers with an even number of even digits, and an odd number of odd digits.
So first of all, the program ends when I enter a one digit number, which is not intentional. I assume that has something to do with the while being while (n > 0). There also is likely an issue with the if (numEven % 2 == 0......) because the print results seem almost random, with a number being good and the same number not being good sometimes.
Honestly, I am lost at this point. Thank you so much in advance for any help.
UPDATE: This code is working how I want it to, I just wanted to thank everybody who helped out! It's my first semester of computer science class, so I'm still rather new at this...excuse my mistakes that were likely pretty stupid :)
package quackygame;
import java.util.Scanner;
public class QuackyGame
{
public static void main(String[] args)
{
System.out.println("Welcome to the Number Game!"
+ " Try to figure out the pattern "
+ "in the numbers that Wallace likes!");
Scanner scan = new Scanner (System.in);
int n;
int numEven = 0;
int numOdd = 0;
boolean isEven;
do
{
System.out.print("Enter a number > 0: ");
n = scan.nextInt();
while (n > 0)
{
if (n % 2 == 0)
{
//n is even
isEven = true;
numEven++;
}
else
{
//n is odd
isEven = false;
numOdd++;
}
n /= 10;
}
//if numEven is even and numOdd is odd
if (numEven % 2 == 0 && numOdd % 2 == 1)
System.out.println("Wallace liked your number!");
else
{
System.out.println("Wallace didn't like your number.");
}
numEven = 0;
numOdd = 0;
}
while (n >= 0);
}
}
There are a few core issues in the code based on the desired results that you described. The most glaring issue I see is that you intend for the game to essentially "start from scratch" at the beginning of each round, but you never actually reset the numEven and numOdd variables. This is the source of your print results seeming random. For example, if you started a game and input the number:
34567
The game would process the number and say that it is a favorable number because it is odd, has an odd number of odd digits (3), and has an even number of even digits (2). However, upon playing the game again, it would execute the same code without setting the variables back to 0, which means that upon entering:
34567
The game would process this number as a bad number because the accumulated value of odd digits would be 6 instead of 3 (since 3 the first time + 3 the second time results in 6), and 6 is even. So what we want to do is this:
...
int n;
do
{
int numEven = 0;
int numOdd = 0;
System.out.print("Enter a number: ");
n = scan.nextInt();
...
By placing the numEven and numOdd declarations inside of the "do" block, they are local variables which only exist for the duration of the do block. We could also do something as simple as this:
...
else
{
System.out.println("Wallace didn't like your number.");
}
numEven = 0;
numOdd = 0;
}
while (n > 0);
...
Just resetting the values will help us to keep track of the actual intended values of numOdd and numEven more consistently.
With regard to the program closing when you input a single digit number, I'm not sure. That doesn't make sense because since it is a do-while loop it should at least execute once, and issue one of the print statements. I'm loading this code into my IDE right now to give it a run through. I'll update my answer if I find something.
-EDIT-: Upon reading your question again, it seems that you may not be suggesting that the program closes before actually completing any of its functions, but simply that it closes at all. The reason for the closing of the program is that you are performing an integer division arithmetic function where you probably want to be using a different type of number. Let me explain:
In normal human counting, we have our natural set of numbers which have no decimal points. They usually start like this:
1, 2, 3, 4, 5 ...
Then we have a separate set of numbers for math where we operate with more precision:
0.5, 1.4232, 3.142 ...
When we are talking about numbers with normal human language, we assume that dividing 1 by 2 results in 0.5. However, computers do not implicitly know this. In order for a computer to reach the conclusion "0.5" from the division of 1 by 2, you need to explicitly tell it that it should use a certain type of number to produce that output.
The "normal" numbers I referenced earlier are most loosely related to the integer in programming. It's basically a number without a decimal point. What that means is that whenever you divide two integers together, you always get another integer as the result. So if you were to divide 1 by 2, the computer would not interpret the result as 0.5 because that number has a decimal. Instead, it would round it down to the nearest integer, which in this case is 0.
So for a more specific example referencing the actual question at hand, let's say we input the number 5 into our program. It goes through all of the calculations for odds and evens, but eventually gets to this line:
n /= 10
This is where things get funky. We are dividing two integers, but their result does not come out as a perfect integer. In this case, the result of 5 / 10 is again 0.5. But for the computer, since we are dividing two integers, the result 0.5 just won't do, so after rounding down to the nearest integer we get 0. At this point, there is one fatal mistake:
(while n > 0);
When we perform this check, we get false and the while loop ends. Why? Because after performing n /= 10, n becomes 0. And 0 is not greater than 0.
How can we fix this? The best thing to do is probably just use a floating point number to perform the calculations. In Java, this is pretty easy. All we really have to do is:
n /= 10.0
When Java sees that we are dividing by 10.0, which is not an integer, it automatically converts "n" to a floating point number to divide by 10.0. In this case then, if n is 5, our result in dividing 5 by 10.0 will be 0.5. Then, when we run:
(while n > 0);
This becomes true! And the loop does not break.
I am going to put all of these changes into my IDE just to confirm that everything is working as intended for me. I would suggest you give it a try too to see if it fixes your problems.
Hope this helps.
You are increasing numEven or numOdd count each time you input a number, and then you use if (numEven % 2 == 0 && numOdd % 2 == 1) , it is random because if you put number 33 for the first time => numOdd = 1; => true => "Wallace likes" , but next time you put 33 for the second time => numOdd = 2; => false => "Wallace doesnt like".
Edit* Maybe you wanted something like this?
public static void main(String[] args)
{
System.out.println("Welcome to the Number Game!"
+ " Try to figure out the pattern "
+ "in the numbers that Wallace likes!");
Scanner scan = new Scanner (System.in);
int n;
boolean isEven;
do
{
System.out.print("Enter a number: ");
n = scan.nextInt();
//if 0, you leave the loop
if(n==0) {
System.out.println("You pressed 0, have a nice day");
break;
}
if (n % 2 == 0)
{
//it is even
isEven = true;
}
else
{
//it is not even
isEven = false;
}
//if even then he likes it, otherwise he does not
if (isEven)
System.out.println("Wallace liked your number!");
else
{
System.out.println("Wallace didn't like your number.");
}
}
//put any contition here, lets say if you press 0 , you leave the loop
while (n != 0);
}

Finding 1's complement

I am trying to make a program to calculate 1's complement after entering a binary number.
This is what I have to far:
import java.util.Scanner;
public class BitWiseComplement {
public static void main(String[] args) {
Scanner keysIn = new Scanner(System.in);
System.out.println("Please enter your number: ");
long originalNum = keysIn.nextLong();
System.out.println(~originalNum);
}
}
However, when I enter 0111011, I get -111012. I thought the ~ operator was supposed to invert the number so that all 0s are 1s and all 1s are 0s.
Any help?
You presumably want to work in binary, so try:
Scanner keysIn = new Scanner(System.in);
System.out.print("Please enter your number: ");
long originalNum = keysIn.nextLong(2); // specify radix of 2
System.out.println(Long.toBinaryString(~originalNum)); // print binary string
keysIn.close();
Please enter your number: 0111011
1111111111111111111111111111111111111111111111111111111111000100
As you can see, all bits are flipped. Bear in mind that there are leading 0s in front of the binary number you entered.
The ~ operator does what you think, but keep in mind that there are no unsigned types in Java, so when you enter a positive number (i.e., the high bit is a 0), applying ~ to it will make it negative (by turning the high bit on).
If you were to print the number out in hex (or binary, as other answers have suggested), you should see the answer you expect.
count the number of bits in num.
make a mask of 1s of the same length.
xor with the number to get the complement.
eg. 9^15=6
public static int solution(int num) {
int bits = Integer.toBinaryString(num).length();
int maxBound = (int)( Math.pow(2, bits)-1);
return num ^ maxBound;
}

Convert fraction to decimal number

i'm doing some exercises in my Java book. I'm very new to programming. Therefore, notice (in the code) that i'm still on Chapter one. Now I already did everything, I just want a confirmation if this is legitimate so I can feel free to move on next.
If not, I would sincerely appreciate to not do my code for me; I want advice.
Here's the question written in the book,
"Write an application that prompts/reads the numerator and denominator of a fraction as integers, then prints the decimal equivalent of the fraction."
I'll illustrate this sentence with my code:
I did a revision here. Is this one OK?..
import java.util.*;
public class ExerciseEleven {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
double fraction;
int fractionValue;
int decimal;
double value;
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
fraction = (double) numerator / denominator;
fractionValue = (int) (fraction * 10);
decimal = fractionValue % 10;
value = decimal * 0.1;
System.out.println(value);
}
}
It compiles and works fine.
Thank you.
It doesn't do what task says it should. You read doubles instead of integers, and the decimal equivalent is not what you print out. Decimal equivalent for 1/2 is 0.5. And you print 5.
Also, you can pay attention to your code style: variable names are usually written in lowerCamelCase, like that : simpleVariable.
Update
now it prints what you need. However you do it not in the very right way and your indentation can still be improved.
It's fine (I didn't read the assignment very well, did I? Kudos to Vladimir.) ...but some comments:
Usually you want to indent methods within the class.
Standard practice is to use initial caps (Numerator) only for types (e.g., classes, interfaces, enums). Variable, field, and method names should start with a lower-case letter. Now, you're free to ignore standard practice, but if you do people will have a lot of trouble reading your code. :-)
For rounding, you probably want to look at Math.round rather than truncating with a cast. But the assignment didn't say anything about rounding.
You might want to handle the case where denominator is zero.
So keeping those in mind:
import java.util.*;
public class ExcerciseEleven {
public static void main (String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Enter Numerator: ");
int numerator = sc.nextInt();
System.out.println("Enter Denominator: ");
int denominator = sc.nextInt();
if (denominator == 0) {
System.out.println("Can't divide by zero");
}
else {
double fraction = (double)numerator / denominator;
System.out.println(fraction);
}
}
}
Hey I am doing some thinking about this and I have noticed something interesting after looking at this source and here is the Algorithm that I plan on implementing
First I will convert the number from the Metric using the
Javax.Measure family of functions and I will get a number like
0.3750
Then I will divide the number by ONE_SIXTEENTH which = 0.0625
ONE_SIXTEENTH = 0.0625
The answer 0.3750 / ONE_SIXTEENTH = 6;
So now I know there are 6 sixteenths of the inch
Next I check to see if 6 is divisible by 4, 6/4 = 1.5 ie not a whole number so the fraction is still regarded as 6/16th of an inch for now
Next I check to see if 6 is divisible by 2, 6/2 = 3
This is a whole number so we will use it to reconstitute the fraction
So now that we have divided 6 by 2 and gotten 3 the 16 needs to be divided by 2 and we end up with 8 so 6/16th of an inch becomes 3/8th of an inch.
PS Has anyone noticed that this is similar to a fizz bang program?
____________________________________________
Here is the chart which helped me get my head around this
My workings
There are three important parts of division operation :
Sign of the result.
Integral part
Decimal part
Also, there are few corner cases where you need to deal with the fact that Integer.MIN_VALUE is greater than Integer.MAX_VALUE when compared in absolute form.
For example : -2147483648/-1 can't yield 2147483648 when divided in the form of integer types. The reason is simple. The type of the resulting type will be integer type, and the maximum positive value that a integer type variable can hold is +2147483647
To mitigate that scenario, we should at first convert both the numerator and denominator into their long positive form. That gives us the integral part of the answer.
The XOR of two numbers will have the sign bit as 1 only in case they have opposite signs. That solves the first part (sign of result) of the problem.
For decimal part, we can employ the general division rule i.e. multiply the remainder with 10 and try dividing again and repeat. Keep record of the remainder we have already come across to prevent the loop from going into unbounded iterations.
public String fractionToDecimal(int A, int B) {
StringBuilder sb = new StringBuilder((A^B) < 0 ? "-" : "");
long a = Math.abs((long)A);
long b = Math.abs((long)B);
sb.append(Long.toString(a/b));
long rem = a % b;
sb.append((rem != 0) ? "." : "");
Map<Long, Integer> remainderMap = new HashMap<>();
int pos = 0;
while (rem != 0){
sb.append(Long.toString((rem*10)/b));
remainderMap.put(rem, pos++);
rem = (rem*10) % b;
if (remainderMap.containsKey(rem)){
String currNum[] = sb.toString().split("\\.");
return currNum[0] + "." + currNum[1].substring(0, remainderMap.get(rem)) +
"(" + currNum[1].substring(remainderMap.get(rem)) + ")";
}
}
if (sb.toString().equals("-0")) return "0";
return sb.toString();
}
Sample output :
2/3 gives 0.(6)
-2147483648/-1 gives 2147483648

Categories

Resources